Created
April 26, 2012 20:06
-
-
Save karledurante/2502669 to your computer and use it in GitHub Desktop.
ruby alias method chain in ruby
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
# 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 |
I will give these a look, thanks.
…On Apr 26, 2012, at 4:29 PM, Justin ***@***.*** wrote:
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](http://en.wikipedia.org/wiki/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](http://aquarium.rubyforge.org/) ranks high on Google.
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2502669
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.