简体   繁体   中英

Rails - include a module without using the word include

I noticed in the audited gem you can do this:

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

  # Single field
  # audited only: :name

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

I'm trying to replicate this behaviour with not much luck, I'm using instructions here to extend my module: https://stackoverflow.com/a/9200191/312342

here is my class:

class Thing < ApplicationRecord
  audited only: :name
end

My module:

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)

Error I'm getting (only on the first load, then error stops, but module still does not output.

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

Your module is included into ActiveRecord::Base only when the file is executed. Assuming you're using rails autoloading, it's only executed when Audited is called.

You'll need to require the file or execute ::ActiveRecord::Base.send(:include, Audited) somewhere in your load process (initializer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM