2012-05-05 17 views
1

我不是指我如何包含ActiveRecord,但讓我解釋一下。如何才能使用Ruby做一個has_many關係,即不使用Rails?

我想有一個GamedifficultyLevelIDDifficultyLevel對象。

在Rails和ActiveRecord的(這就是我所熟悉的),這些將是表,我將有has_manybelongs_to方法,然後我可以只使用difficultyLevelID得到的東西,所以難度可能是Game.difficulty_level.name

如果我只是做一個Ruby程序,沒有數據庫,我想用這種關係,即我想Game到有難度的ID和水平name本身是在一個difficulties類,我該怎麼辦(創建,維護和查詢關係)只是用Ruby,這樣我可以說得到遊戲難度級別名稱?

+0

你爲什麼想在遊戲中的困難級別ID? Rails在遊戲中有ID,所以它可以在難度表中查找。如果你只有物體,將難度對象設置爲遊戲,並從難度對象中獲取ID。 – dj2

回答

0

在20小時內沒有答案,所以我發佈了自己的。

class Soduko 
    attr_accessor :name, :rows, :columns, :difficulty_level 
    def initialize // will probably move to parameters as defaults. 
    @rows= 9 
    @columns= 9 
    @name= 'My Soduko' 
    @difficulty_level= 'Medium' 
    end 

    def initial_number_count 
    DifficultyLevel.start_with_numbers('Medium') 
    end 

end 

class DifficultyLevel 

    def self.start_with_numbers(difficulty_level) 
    case difficulty_level 
     when 'Easy' 
     then 30 
     when 'Medium' 
     then 20 
     when 'Hard' 
     then 10 
     else 20 
    end 

    end 

end 

課程和測試:

require './soduko' 

describe Soduko, '.new' do 

    before { @soduko_board = Soduko.new } 

    it "Should allow for a new Board with 9 rows (default) to be created" do 
    @soduko_board.rows.should == 9 
    end 

    it "Should allow for a new Board with 9 columns (default) to be created" do 
    @soduko_board.columns.should == 9 
    end 

    it "should have a default difficulty level of 'Medium'" do 
    @soduko_board.difficulty_level.should == 'Medium' 
    end 

    it "should have 10 initial numbers" do 
    @soduko_board.initial_number_count.should == 20 
    end 

end 

describe DifficultyLevel, '.new' do 

    it "should exist" do 
    @difficulty_level = DifficultyLevel.new 
    end 

    # More to be added... 

end 
+0

soduko?你的意思是「數獨」嗎? :) –

相關問題