【问题标题】:Rails: Concern with before_filter type of methodRails:关注 before_filter 类型的方法
【发布时间】:2015-09-08 20:41:45
【问题描述】:

我刚刚开始接触 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。 我做错了什么?

感谢您的帮助!

【问题讨论】:

  • 五年后,不知道您是否注意到您在方法set_log_field 中拼错了@feild

标签: ruby-on-rails activerecord activesupport-concern


【解决方案1】:

你可能是这个意思(顺便说一句,为什么不是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

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

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

【讨论】:

  • 太好了,行得通!你能解释一下 include do ... end 中定义的方法和每个块之外(当然是在模块内)的方法有什么区别吗?
  • @DanielArnreich 我已经用很棒的链接更新了我的答案,他们有很好的例子来说明你所询问的差异。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多