Question

I need to call a method before every static method called in rails.

is it possible

Example:

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

when I call A.b then the output should be:

==========

bunch of statements before every static method and

code related to b

==========

Thanks in advance

Was it helpful?

Solution 4

Try this

class A

 def self.hello
   print "how are"

 end

 def self.before_stuff
  print "you"
 end

 begin
  print "hello,"
 end
end

 A.hello

OTHER TIPS

To answer your question (though I'd first consider what you're trying to do and if there is a better way), here's how I'd approach. I wouldn't try to quietly hook into static method calls. Be explicit:

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

Usage: A.debug_call_static('b')

I don't know what you are up to, but yield is mostly used to solve this kind of problem

==========

bunch of statements before every static method and

code related to b

==========

What you can do is

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

Output

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 > 

you could use the self.extended callback on a module and override your class methods

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top