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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With