Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@znz
Created September 4, 2019 11:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save znz/755b1caefce2664cc2d0d80fdd759930 to your computer and use it in GitHub Desktop.
Save znz/755b1caefce2664cc2d0d80fdd759930 to your computer and use it in GitHub Desktop.
最低限の before_action っぽいもの
class Foo
def self.before_action(hook, only:)
actions = Array(only)
self.prepend Module.new {
actions.each do |action|
class_eval <<-RUBY, __FILE__, __LINE__+1
def #{action}
#{hook}
super
end
RUBY
end
}
end
before_action :foo, only: :show
before_action :hook, only: %i[show save]
def save
p :save
end
def show
p :show
end
def foo
p :foo
end
def hook
p :hook
end
end
Foo.new.show # => :hook, :foo, :show
Foo.new.save # => :hook, :save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment