3

我有以下 Ruby 类:

class Sandwich
  class << self
    def prepare_with(special_ingredient, &block)
      # Some very very special magic is done here to
      # call instead just .fry! as .fry!({:ingredient=>special_ingredient})
      # and for any other method the same
    end

    def fry!(opts= {})
    end

    def add_mayo(opts = {})
    end
  end
end

class Hamburger < Sandwich
end

=> Hamburger.prepare_with(bacon) do
=>   Hamburger.fry!
=>   Hamburger.add_mayo
=> end

我想修改调用Hamburger类的所有方法并将附加添加key=>value到最后一个参数哈希中。

应该使用一些特殊的魔法来Sandwich.prepare_with调用 Sandwich 的所有方法(及其所有后代),例如as 。call.fry!.fry!({:ingredient=>special_ingredient})

已编辑:理想情况下,我们需要过滤内部块代码的调用的附加点,例如以下代码会引发任何 prepare_with 代码的异常,它不会过滤它使用附加参数调用的方法:

=> Hamburger.prepare_with(bacon) do
=>   Hamburger.fry!
=>   h = Hash.new("Go fish") 
=>   Hamburger.add_mayo
=> end
4

2 回答 2

3

为什么不是fry!实例add_mayo方法?

编辑:作为问题海报所要求的,没有实例方法:

class Sandwich
  class << self
    def prepare_with(special_ingredient, &block)
      @@default_opts = {:special_ingredient => special_ingredient}
      block.call
    end

    def fry!(opts={})
      opts = opts.merge(@@default_opts)
      puts "fried with #{opts[:special_ingredient]}"
    end

    def add_mayo(opts = {})
      puts "added mayo"
    end
  end
end

class Hamburger < Sandwich
end

Hamburger.prepare_with(:bacon) do 
  Hamburger.fry!
  Hamburger.add_mayo
end

Hamburger.prepare_with(:tofu) do 
  Hamburger.fry!
end

输出:

fried with bacon
added mayo
fried with tofu
于 2012-04-24T12:38:04.813 回答
0

简短的回答

block.call :ingredient => special_ingredient

长答案

我认为你应该处理对象。add_mayo 和fry 应该是实例方法而不是类方法。

我会看到类似的东西

class Sandwich
  class << self
    def prepare &block
      sandwich = self.new
      block.call sandwich
      sandwich
    end
  end

  def fry(opts = {})
    #stuff
  end

  def add_mayo(opts = {})
  end
end

class Hamburger < Sandwich; end

hamburger = Hamburger.prepare do |h|
  h.fry :ingredient => :bacon
  h.add_mayo
end
于 2012-04-24T12:33:56.693 回答