Ruby On Rails:从关注中调用类方法

Sam*_*imi 2 ruby ruby-on-rails

在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
Run Code Online (Sandbox Code Playgroud)

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

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

并且,当在关注内部进行调试时,我得到这样的事情:

(byebug) self
Foo (call 'Foo' to establish a connection)
(byebug) self.class
Class
Run Code Online (Sandbox Code Playgroud)

Ale*_*kin 5

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
Run Code Online (Sandbox Code Playgroud)

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