Skip to content

Instantly share code, notes, and snippets.

@pricees
Created January 9, 2018 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pricees/48543326f682db19aaa3e43e69459472 to your computer and use it in GitHub Desktop.
Save pricees/48543326f682db19aaa3e43e69459472 to your computer and use it in GitHub Desktop.
Using ActiveModel::Callbacks
# ./Gemfile
# $ bundle
source "https://rubygems.org"
gem "activemodel"
###############################################
# foo.rb
# $ bundle exec ruby foo.rb
require 'active_model'
class Foo
extend ActiveModel::Callbacks
define_model_callbacks :my_method
def my_method(raise_zomg = false)
run_callbacks(:my_method) do
puts "this is :my_method!"
raise("ZOMG") if raise_zomg
end
end
before_my_method :before_my_method
around_my_method :around_my_method
after_my_method :after_my_method
def around_my_method
puts "around_my_method (prepend)"
begin
yield
rescue RuntimeError => e
puts "Caught that RuntimeError '#{e.message}'"
end
puts "around_my_method (append)"
end
def after_my_method
puts "after_my_method"
end
def before_my_method
puts "before_my_method"
end
end
foo = Foo.new
# foo.my_method
# Output:
#
# before_my_method
# around_my_method (prepend)
# this is :my_method!
# around_my_method (append)
# after_my_method
# Exceptions are reraised!
foo.my_method(:raise_zomg)
# Output:
#
# before_my_method
# around_my_method (prepend)
# this is :my_method!
# Caught that RuntimeError 'ZOMG'
# around_my_method (append)
# after_my_method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment