2017-03-22 67 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