我担心存储常量的位置:
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
看起来第一个问题在第二个问题中没有正确加载。如果是这样,我该怎么办?
最佳答案
看来这种行为是设计使然,正如 here 中所解释的那样.
在这种情况下,您需要做的不是 Group::Constants
延伸自 ActiveSupport::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
一个标准模块,然后一切都会好起来的。
关于ruby-on-rails - rails : Including a Concern with a constant within a Concern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15953332/