Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 自动创建方法_Ruby On Rails_Ruby_Ruby On Rails 3_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 自动创建方法

Ruby on rails 自动创建方法,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 4,假设我有一个家庭课: 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 c

假设我有一个家庭课:

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\u 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 
这样的事情可能吗?谢谢

您可以使用以下方法执行此操作:


嗯,好问题…-)回答得好。你不需要最后两个
self.
。@CarySwoveland抓得好!
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