gpt4 book ai didi

ruby-on-rails - rails : Including a Concern with a constant within a Concern

转载 作者:行者123 更新时间:2023-12-03 11:39:28 26 4
gpt4 key购买 nike

我担心存储常量的位置:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com