Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intercept method call in ruby?

Tags:

ruby

I currently have a superclass which has a function that I want all the subclass to call within each of its function. The function is supposed to behave like a before_filter function in rails but I am not sure on how to go about implementing before_filter. Here is an example

class Superclass
  def before_each_method
    puts "Before Method" #this is supposed to be invoked by each extending class' method
  end
end

class Subclass < Superclass
  def my_method
    #when this method is called, before_each_method method is supposed to get invoked
  end
end
like image 507
denniss Avatar asked Aug 21 '11 08:08

denniss


People also ask

What happens when you call a method in Ruby?

A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function.

How do you call a method in Ruby?

We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.

Does method order matter in Ruby?

You could define method in any order, the order doesn't matter anything.


1 Answers

class BalanceChart < BalanceFind
  include ExecutionHooks

  attr_reader :options

  def initialize(options = {})
    @options = options
    @begin_at = @options[:begin_at]
  end

  def months_used
   range.map{|date| I18n.l date, format: :month_year}.uniq!
  end

  before_hook :months_data, :months_used, :debits_amount
end

module ExecutionHooks

  def self.included(base)
   base.send :extend, ClassMethods
  end

  module ClassMethods

    def before
      @hooks.each do |name|
        m = instance_method(name)
        define_method(name) do |*args, &block|  

          return if @begin_at.blank? ## the code you can execute before methods

          m.bind(self).(*args, &block) ## your old code in the method of the class
        end
      end
    end

    def before_hook(*method_name)
      @hooks = method_name
      before
    end

    def hooks
      @hooks ||= []
    end
  end
end
like image 166
Breno Perucchi Avatar answered Oct 08 '22 15:10

Breno Perucchi