Skip to content

Instantly share code, notes, and snippets.

@karledurante
Created April 26, 2012 20:06
Show Gist options
  • Select an option

  • Save karledurante/2502669 to your computer and use it in GitHub Desktop.

Select an option

Save karledurante/2502669 to your computer and use it in GitHub Desktop.
ruby alias method chain in ruby
# The intention is to reduce boiler plate code by globally adding
# behavior to any of the defined CLASS LEVEL methods.
#
# Chained.foo => "first I was like: base foo, but then I was: chained foo
# Chained.foo_bar => "first I was like: base foo_bar, but then I was: chained foo_bar
#
# This is useful for, say, finder methods that you want to add global behavior
# too. Like if you want to always decorate a result set.
#
# This seems a bit crazy...ideas for improvement??
class Chained
module Base
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def foo
"base foo"
end
def foo_bar
"base foo_bar"
end
end
end
module PostExtension
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def self.extended(base)
base.methods.grep(/foo/).each do |method_name|
puts "found method: #{method_name}"
self.send(:define_method, method_name) do
"first I was like: #{super}, but then I was: chained #{method_name}"
end
end
end
end
end
include Base
include PostExtension
end
@hellojustin
Copy link
Copy Markdown

I don't have any particularly insightful input on how you could make this specific code better, but I wonder if the concept you're going for is already captured under the Aspect-Oriented Programming (AOP) umbrella. If you haven't already, I would look into AOP frameworks for ruby. I can't vouch for any in particular, but Aquarium ranks high on Google.

@karledurante
Copy link
Copy Markdown
Author

karledurante commented Apr 26, 2012 via email

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