Skip to content

Instantly share code, notes, and snippets.

@maxidr
Created December 3, 2012 20:08
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 maxidr/4197630 to your computer and use it in GitHub Desktop.
Save maxidr/4197630 to your computer and use it in GitHub Desktop.
hook method_added in Module
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/
@maxidr
Copy link
Author

maxidr commented Dec 3, 2012

More info in the book Pragmatic Metaprogramming in Ruby of Paolo Perrota.
Or you can see the ruby doc of Module#method_added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment