簡體   English   中英

Rails - 包含一個模塊而不使用包含這個詞

[英]Rails - include a module without using the word include

我在審核的 gem 中注意到你可以這樣做:

class User < ActiveRecord::Base
  # All fields
  # audited

  # Single field
  # audited only: :name

  # Multiple fields
  # audited only: [:name, :address]

我試圖復制這種行為但運氣不佳,我在這里使用說明來擴展我的模塊: https://stackoverflow.com/a/9200191/312342

這是我的 class:

class Thing < ApplicationRecord
  audited only: :name
end

我的模塊:

module Audited
  extend ActiveSupport::Concern
    
    def ClassMethods
      def audited(options = {})
        class_attribute :audited_options
        self.audited_options = options
        after_save :audit
      end
    end

    def audit
      puts self.changed_attributes
      puts self.audited_options
    end
end

::ActiveRecord::Base.send(:include, Audited)

我得到的錯誤(僅在第一次加載時,然后錯誤停止,但模塊仍然沒有 output。

NoMethodError (undefined method `audited' for #<Class:0x00007fae51b15ab0>):

只有在執行文件時,您的模塊才會包含在ActiveRecord::Base中。 假設您正在使用 rails 自動加載,它僅在調用Audited時執行。

您需要在加載過程(初始化程序)的某處要求該文件或執行::ActiveRecord::Base.send(:include, Audited) )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM