Rails:关注 before_filter 类型的方法

Rails: Concern with before_filter type of method

我刚刚开始接触 Rails 中的问题并尝试为 ActiveRecord 类 实现一个简单的日志记录。在那里我想定义应该进入日志的字段并在保存后自动写入日志。

我有的是这个:

#logable.rb (the concern)
module Logable
  extend ActiveSupport::Concern

  @field = nil
  module ClassMethods
    def set_log_field(field)
      @feild = field
    end
  end

  def print_log
    p "LOGGING: #{self[@index.to_s]}"
  end
end


#houses.rb (the model using the concern)
class House < ActiveRecord::Base
  include Logable
  after_save :print_log
  set_log_field :id
end

不幸的是,对 set_log_field 的调用没有效果 - 或者更确切地说,给定值没有到达 print_log。 我做错了什么?

感谢您的帮助!

你可能是这个意思(顺便说一句,为什么不是 Loggable?):

# logable.rb
module Logable
  extend ActiveSupport::Concern

  # Here we define class-level methods.
  # Note, that @field, defined here cannot be referenced as @field from
  # instance (it's class level!).
  # Note also, in Ruby there is no need to declare @field in the body of a class/module.
  class_methods do
    def set_log_field(field)
      @field = field
    end

    def log_field
      @field
    end
  end

  # Here we define instance methods.
  # In order to access class level method (log_field), we use self.class.
  included do
    def print_log
      p "LOGGING: #{self.class.log_field}"
    end
  end
end

Update 您还询问了 included 块中的方法与方法主体中的方法之间的区别。

做一个简短的简历似乎没有什么区别。在非常近似的情况下,您可以认为它们相同。唯一的细微差别在于依赖管理。 ActiveSupport::Concern 文档末尾给出了很好的说明。值得一读,看看!