我担心在其中存储常量:

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设为标准模块,然后一切都会好起来。

08-06 22:30