2012-06-30 85 views
0

我嘗試寫DSL紅寶石DSL使得

class Warcraft 
    class << self 
    def config 
     unless @instance 
     yield(self) 
     end 
     @instance ||= self 
    end 

    attr_accessor :name, :battle_net 

    def game(&block) 
     @instance ||= Game.new(&block) 
    end 
    end 

    class Game 
    class << self 
     def new 
     unless @instance 
      yield 
     end 
     @instance ||= self 
     end 

     attr_accessor :side, :hero 

     def rune_appear_every(period) 
     @rune_appear_every = period 
     end 

    end 
    end 
end 

Warcraft.config do |war| 
    war.name = "Warcraft III" 
    war.battle_net = :iccup 

    war.game do |game| 
    game.side = :sentinels 
    game.hero = "Furion" 
    game.rune_appear_every 2.minutes 
    end 
end 

,我得到這樣的錯誤:

dsl.rb:41:in `block (2 levels) in <main>': undefined method `side=' for nil:NilClass (NoMethodError) 

回答

3

問題就在這裏:

def new 
    unless @instance 
     yield 
    end 
    @instance ||= self 
    end 

你沒有經過任何當您撥打yield時,請稍後再撥打電話:

war.game do |game| 

game變量爲零。因此,而不是隻是做yield,做yield self