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