自动创建方法

时间:2015-03-29 18:56:31

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

假设我有这个House课程:

class House

  def self.building_steps
    [
      [Worker, :buy_material],
      [Worker, :blend_material],
      [Truck, :remove_ground],
      ......
      #more Tasks defined by [CLASS,METHOD]
    ]
  end

  def self.buy_material
    check_process(Worker, __method__)
  end

  def self.blend_material
     check_process(Worker, __method__)
  end

  def self.remove_ground
     check_process(Truck, __method__)
  end
  ............
  #More Methods that have same Method names like the building steps

end

正如您在我的代码中所看到的,我有很多重复。

我的问题是我如何从building_steps列表中自动定义类方法。

所以我不必手动添加方法!

我搜索的内容如下:

 House.building_steps.each do |step|
   define_house_method_with_name( step[1] ) 
     in this method do
       check_process(step[0], step[1])
     end
 end 

这样的事情可能吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用define_singleton_method执行此操作:

class Worker; end
class Truck; end

class House
  def self.building_steps
    [
      [Worker, :buy_material],
      [Worker, :blend_material],
      [Truck, :remove_ground]
    ]
  end

  def self.check_process(klass, method)
    "executing #{method}"
  end

 building_steps.each do |klass, method|
   define_singleton_method(method) do
      check_process(klass, method)
    end
  end
end

puts House.buy_material #=> executing buy_material