Created
December 3, 2012 20:08
-
-
Save maxidr/4197630 to your computer and use it in GitHub Desktop.
hook method_added in Module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Module | |
def method_added(name) | |
unless @_admin_only.nil? or @_proxy_method | |
@_proxy_method = true | |
alias_method "_admin_#{name}", name | |
module_eval <<-STRING | |
def #{name}(*args, &block) | |
_admin_#{name}(*args, &block) if admin? | |
end | |
STRING | |
@_proxy_method = false | |
end | |
end | |
def admin_only | |
@_admin_only = true | |
end | |
end | |
class User | |
def admin? | |
[true, false][rand(2)] | |
end | |
admin_only | |
def update_password | |
puts "password updated" | |
end | |
def restart_server | |
puts "server restarted" | |
end | |
end | |
# source: http://www.diegocarrion.com/2010/05/27/ruby-annotations/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More info in the book Pragmatic Metaprogramming in Ruby of Paolo Perrota.
Or you can see the ruby doc of Module#method_added