【问题标题】:Ruby refinements and hooksRuby 改进和钩子
【发布时间】:2015-11-25 18:14:13
【问题描述】:

我正在尝试使用 ruby​​ 改进来应用 rails 钩子。

我想避免猴子补丁。当猴子修补时,它会这样工作

ActiveRecord::Base.class_eval do
  after_find do 
     # do something with 
     my_method
  end

  def my_method
    # something useful
  end
end

我已经能够通过执行以下操作来获得类方法:

module ActiveRecordRefinements
  refine ActiveRecord::Base.singleton_class do
    def my_method
     #something cool
    end
  end
end

但我无法运行钩子。我尝试使用self.used(klass),但似乎无法获得恰到好处的语法。

欢迎任何帮助。

谢谢。

【问题讨论】:

  • 您不需要在ActiveRecord::Base 上调用#singleton_class,因为细化是单例的。
  • 我正在尝试添加到 AR 的 DSL。类似于 ``` class Foo
  • 猴子补丁和依赖注入之间有一条细线。通常猴子修补被定义为以不一定适用于未来版本的核心的方式重新定义核心行为。更简洁的依赖注入模型试图避免冲突并保持最小的占用空间。

标签: ruby-on-rails ruby refinements


【解决方案1】:

您不使用 ActiveSupport 回调是有原因的吗? 看这里:http://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多