自动创建方法

Create automatically methods

假设我有这个房子class:

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 列表中自动定义 class 方法。

这样我就不必手动添加方法了!

我搜索类似的东西:

 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 

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

您可以使用 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