2017-03-22 79 views
0

我想定义多个自定义方法来为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, ...]),但它不是动态的,每次字段更改,添加或删除时都必须更改它。

+1

我没有看到一切都在这里定义的'get_attrs'方法,但你可以只使用'attr_accessor * get_custom_attr'这将创建虚拟属性对于定义的键(因为你在帖子中说你想设置的值,你的代码建议检索。 – engineersmnky

+0

这是一个错字。修正了它,它应该是'get_custom_attrs'。 – abpetkov

回答

0

get_custom_attrs正在类级别执行,而def get_custom_attrs定义了实例级别的方法。您需要get_custom_attrs存在,作为一个类的方法,所以你要像

class MyAwesomeClass 
    class << self 
    private 
    def get_custom_attrs 
     [:a1,:a2,:a3] # or whatever 
    end 
    end 
    get_custom_attrs.each do |attr| 
    # Some stuff happens here 
    end 
end 
+0

如何保留原来的想法, get_custom_attrs'方法私有? – abpetkov

+0

@abpetkov,请参阅编辑 – ymbirtt

+0

如果我想在类级别和实例级别上使用它,我需要在另一种方法中使用它,并且它不起作用 – abpetkov