Ruby on rails 将值绑定到ruby define_方法
在我的模型中,我尝试将数组中的对象作为顶级属性动态公开。下面是代码片段:Ruby on rails 将值绑定到ruby define_方法,ruby-on-rails,ruby,Ruby On Rails,Ruby,在我的模型中,我尝试将数组中的对象作为顶级属性动态公开。下面是代码片段: class Widget < ActiveRecord::Base # attr_accessor :name end class MyModel < ActiveRecord::Base has_many :widgets #attr_accessor :widgets after_initialize :init_widgets def init_widgets widge
class Widget < ActiveRecord::Base
# attr_accessor :name
end
class MyModel < ActiveRecord::Base
has_many :widgets
#attr_accessor :widgets
after_initialize :init_widgets
def init_widgets
widgets
widgets.each_with_index do |widget, index|
define_method(widget.name) do
widgets[index]
end
end
end
end
class小部件
我有没有办法将索引的值定义到我正在创建的新方法中,以便它与适当的索引相关联?我可能会创建一个访问器/赋值方法,使
[]
运算符过载:
class BracketOperator
def initialize
@values = (1..100).to_a
end
def [](index)
@values[index]
end
def []=(index, value)
@values[index] = value
end
end
bo = BracketOperator.new
bo[3] # => 4
bo[3] = 17
bo[3] # => 17
作为参考,这里是我的答案。显然我不太理解ruby的作用域。变量
n
在每个循环中以某种方式保持对n的引用。因此,对于我的原始问题,我可以在方法中使用index
变量,它将被映射到我期望它映射到的对象
class Test
def setup
names = [ "foo","bar" ]
names.each do |n|
self.class.send :define_method, n do
puts "method is called #{n}!"
end
end
end
end
也许有更好的方法做事情。如果您将
has\u many:widgets
称为array
,则必须更正。其次,我不会建议你的初始化后块做什么,因为初始化后到处都会被调用,初始化,活动记录的查找程序等等。你能为你的问题添加更多信息吗?默认情况下,你可以访问我的模型.widgets[0]
,我的模型.widgets[1]
,my_model.widgets.last
等-这样做有什么遗漏吗?