我想定义多个自定义方法来为UserConcern中的自定义用户字段设置值,这些字段不存储在数据库中,而是从外部源获取。我想下面的代码,这会导致``':未定义的局部变量或方法get_custom_attrs' for UserConcern:Module (NameError)
定义与自定义名称有关的多个setter方法
get_custom_attrs.each do |key|
define_method(key) do
// returning the value for this key
end
end
private
def get_custom_attrs
OuterConcern::FIELDS - User.attribute_names
end
我显然不能在顶层使用此方法。如果我切换到在关注点中使用常量变量(如CUSTOM_FIELDS = [:custom1, custom2, ...]
),但它不是动态的,每次字段更改,添加或删除时都必须更改它。
我没有看到一切都在这里定义的'get_attrs'方法,但你可以只使用'attr_accessor * get_custom_attr'这将创建虚拟属性对于定义的键(因为你在帖子中说你想设置的值,你的代码建议检索。 – engineersmnky
这是一个错字。修正了它,它应该是'get_custom_attrs'。 – abpetkov