Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do a before_action in Ruby (like in Rails)?

Tags:

ruby

Is it possible to call a before_action before some specified method like in rails?

class Calculator
  before_action { raise Exception, "calculator is empty" if @numbers.nil? }, 
                 only: [:plus, :minus, :divide, :times]

  def push number
    @numbers ||= [] 
    @numbers << number
  end

  def plus
    # ... 
  end

  def minus
    # ... 
  end

  def divide
    # ... 
  end

  def times
    # ... 
  end

    # ... 
end
like image 311
MrPizzaFace Avatar asked May 03 '14 13:05

MrPizzaFace


1 Answers

It can be done with pure Ruby! One way to go is to use method aliasing

class Foo
  def bar
    #true bar
  end

  alias_method :original_bar, :bar

  def bar
    before_stuff
    original_bar
    after_stuff
  end
end

but for a more general approach you could read this thread.

An example for your code can be:

class Calculator

    def plus
      # ...
    end

    def end
      # ...
    end

    def divide
      # ...
    end

    def times
      # ...
    end

    [:plus, :minus, :divide, :times].each do |m|
      alias_method "original_#{m.to_s}".to_sym, m

      define_method m do
        check_numbers
        send("original_#{m.to_s}".to_sym)
      end
    end

    private

    def check_numbers
      raise Exception, "calculator is empty" if @numbers.nil? 
    end
end
like image 57
xlembouras Avatar answered Nov 15 '22 07:11

xlembouras