Rails在每个静态方法之前调用方法之前回调

时间:2013-12-13 03:57:52

标签: ruby-on-rails ruby-on-rails-2

我需要在rails中调用的每个静态方法之前调用一个方法。

是否可能

示例:

Class A

 #Here a bunch of statements before every static method

 def self.b
  # some code related to b
 end

  def self.a
  # some code related to a
 end
end

当我打电话给A.b时,输出应为:

==========

每个静态方法和

之前的一堆语句

与b

相关的代码

==========

提前致谢

4 个答案:

答案 0 :(得分:1)

要回答你的问题(虽然我首先考虑你要做的事情以及是否有更好的方法),但这就是我的方法。我不会试图悄悄地挂钩静态方法调用。明确:

def self.debug_call_static(name)
  # run/call bunch of statements
  self.send(name) if self.respond_to?(name)
end

用法:A.debug_call_static('b')

答案 1 :(得分:0)

您可以在模块上使用self.extended回调并覆盖您的类方法

class A
  def self.before_stuff
  end

  module ClassMethods
    def a
    end

    def b
    end

    def self.extended(base)
      self.instance_methods.each do |name|
        base.instance_eval do
          alias "handle_#{name}" name
          define_method name do |*args, &block|
            before_stuff
            __send__ "handle_#{name}", *args, &block
          end
        end
      end
    end
  end

  extend ClassMethods
end

答案 2 :(得分:0)

我不知道你在做什么,但yield主要是用来解决这类问题

==========

bunch of statements before every static method and

code related to b

==========

你能做的是

class A

 def self.exec
   p "Here a bunch of statements before every static method"
   yield
 end

 def self.b
  A.exec do
   p " some code related to b"
  end
 end

  def self.a
   A.exec do
    p " some code related to a "
   end
 end

end

<强>输出

1.9.3p448 :043 > A.b
"Here a bunch of statements before every static method"
" some code related to b"
 => " some code related to b" 
1.9.3p448 :044 > 

答案 3 :(得分:-1)

试试这个

class A

 def self.hello
   print "how are"

 end

 def self.before_stuff
  print "you"
 end

 begin
  print "hello,"
 end
end

 A.hello