2013-04-11 75 views
17

我有我保存常量關注中:Rails的:包括以恆定的一個值得關注的一個關注

module Group::Constants 
    extend ActiveSupport::Concern 

    MEMBERSHIP_STATUSES = %w(accepted invited requested 
    rejected_by_group rejected_group) 
end 

而且我希望使用這些常量另一個問題:不幸的是

module User::Groupable 
    extend ActiveSupport::Concern 
    include Group::Constants 

    MEMBERSHIP_STATUSES.each do |status_name| 
    define_method "#{status_name}_groups" do 
     groups.where(:user_memberships => {:status => status_name}) 
    end 
    end 
end 

,這會導致路由錯誤:

uninitialized constant User::Groupable::MEMBERSHIP_STATUSES 

它看起來像第一關心的是不正確加載第二個問題。如果是這樣的話,我能做些什麼呢?

+0

你打電話來得到這個錯誤的代碼是什麼?或者當'User :: Groupable'模塊被加載時發生? – PinnyM 2013-04-11 16:18:16

+0

加載'User :: Groupable'時發生。 – nullnullnull 2013-04-11 16:20:59

回答

27

看起來這種行爲是通過設計的,正如here很好地解釋的那樣。

你需要在這種情況下,做的是沒有Group::ConstantsActiveSupport::Concern延伸,因爲這將與其它ActiveSupport::Concern擴展模塊共享的(儘管將在包括第二模塊類最終被共享阻止其實施):

module A 
    TEST_A = 'foo' 
end 

module B 
    extend ActiveSupport::Concern 
    TEST_B = 'bar' 
end 

module C 
    extend ActiveSupport::Concern 
    include A 
    include B 
end 

C::TEST_A 
=> 'foo' 
C::TEST_B 
=> uninitialized constant C::TEST_B 

class D 
    include C 
end 

D::TEST_A 
=> 'foo' 
D::TEST_B 
=> 'bar' 

總之,你需要做Group::Constants一個標準模塊,然後一切都會好起來。

+0

優秀的迴應和很好的參考。謝謝! – nullnullnull 2013-04-12 00:35:51

+1

難道你不能把常量包含在一個'included do'塊中,並用'self ::'作爲前綴嗎? – 2016-02-29 22:26:38

+0

@EddiePrislac不,不會這樣做。 'included'被ActiveSupport模塊劫持,並且在標準(非ActiveSupport)類或模塊包含它們之前不會實際觸發代碼。 – PinnyM 2016-03-01 18:20:22