gpt4 book ai didi

ruby-on-rails - ruby rails : Calling class method from concern

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:54 27 4
gpt4 key购买 nike

在 Rails 中,是否可以在关注点本身中调用包含关注点的类的方法?即:

class Foo < ApplicationRecord
include Encryptable

def self.encrypted_attributes
%i[attr_1 attr_2]
end
end

module Encryptable
extend ActiveSupport::Concern

included do
self.encrypted_attributes do |attr|
define_method("#{attr}=") do |arg|
# do some stuff
end

define_method("#{attr}") do
# do some stuff
end
end
end
end

问题是,当我尝试这样做时,出现如下错误:

*** NoMethodError Exception: undefined method 'encrypted_attributes' for #<Class:0x00005648d71c2430>

而且,在关注点内部调试时,我得到这样的结果:

(byebug) self
Foo (call 'Foo' to establish a connection)
(byebug) self.class
Class

最佳答案

Ruby 是一种脚本语言,顺序很重要。可以执行以下操作:

class Foo < ApplicationRecord
def self.encrypted_attributes
%i[attr_1 attr_2]
end

# OK, now we have self.encrypted_attributes defined
include Encryptable
end

更多信息:ActiveSupport::Concern#included .

关于ruby-on-rails - ruby rails : Calling class method from concern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48903863/

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