简体   繁体   English

Rails - 包含一个模块而不使用包含这个词

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

I noticed in the audited gem you can do this:我在审核的 gem 中注意到你可以这样做:

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我试图复制这种行为但运气不佳,我在这里使用说明来扩展我的模块: https://stackoverflow.com/a/9200191/312342

here is my class:这是我的 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.我得到的错误(仅在第一次加载时,然后错误停止,但模块仍然没有 output。

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

Your module is included into ActiveRecord::Base only when the file is executed.只有在执行文件时,您的模块才会包含在ActiveRecord::Base中。 Assuming you're using rails autoloading, it's only executed when Audited is called.假设您正在使用 rails 自动加载,它仅在调用Audited时执行。

You'll need to require the file or execute ::ActiveRecord::Base.send(:include, Audited) somewhere in your load process (initializer).您需要在加载过程(初始化程序)的某处要求该文件或执行::ActiveRecord::Base.send(:include, Audited) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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