8

我在所有课程中都使用 ga logger。我希望每个味精都以类名和方法名开头,如下所示:

Class_name::Method_name

这就是我现在正在做的事情:

class FOO

 def initialize
 end

 def bar
   msg_prefix = "#{self.class}::#{__method__}"
   ... some code ...
   @logeer = "#{msg_prefix} msg ..."
 end

 def bar2
   msg_prefix = "#{self.class}::#{__method__}"
   ... some code 2 ...
   @logeer = "#{msg_prefix} msg2 ..."
 end

end

我想在 rails 中使用 before_filter 来防止重复,我正在使用sinatra但这些类是普通的旧ruby 1.9.3

想法??

4

2 回答 2

8

您可以在使用Module#method_added创建的任何方法上获取回调,为旧方法设置别名,然后定义一个首先调用 before_filter 方法的新方法。这是我(非常)粗略的第一个概念:

module Filter
  def before_filter name
    @@filter = name
  end

  def method_added name
    return if @filtering # Don't add filters to original_ methods
    return if @@filter == name # Don't filter filters
    return if name == :initialize

    @filtering = true

    alias_method :"original_#{name}", name
    define_method name do |*args|
      self.send @@filter, name
      self.send :"original_#{name}", *args
    end
    @filtering = false
  end
end

class FilterTest
  extend Filter
  before_filter :prepare_logs

  def baz
    puts "#{@msg_prefix} message goes here"
  end

  def prepare_logs name
    @msg_prefix = "#{self.class}::#{name}"
  end
end

ft = FilterTest.new
ft.baz

通过使用__method__like you were in create_prefix,您将获得过滤器方法的名称,而不是原始方法,因此您必须传入方法名称。可能还有其他解决方案可以使其更清晰。

于 2013-02-23T21:19:14.863 回答
2

您可以使用ActiveModel::Callbacks在普通的 Ruby 类中获得before_filter类似行为(尽管在您的情况下,仅执行一行可能有点过分了):

require 'active_model'

class FOO
  extend ActiveModel::Callbacks

  define_model_callbacks :baz, only: :before

  before_baz :create_prefix

  def initialize
  end

  def bar
    run_callbacks :baz do
      ... some code ...
      @logeer = "#{@msg_prefix} msg ..."
    end
  end

  def bar2
    run_callbacks :baz do
      ... some code 2 ...
      @logeer = "#{@msg_prefix} msg2 ..."
    end
  end

  private

    def create_prefix
      @msg_prefix = "#{self.class}::#{__method__}"
    end
end
于 2013-02-23T02:47:52.503 回答