Class Alias
I’m working on a new plugin and found myself having to access a class variable and class method from the instance level and wasn’t too happy with how it was looking:
def instance_foo(args)
self.class.method(self.class.accessor[args]))
end
Sure, I could solve this by writing more code and adding even more complexity but, man, did I wish you could just do something like alias self.foo foo. Oh, wait! This is Ruby. Just open that baby up!
class Object
def class_alias(method_id)
define_method(method_id) do |*args|
self.class.send method_id, *args
end
end
end
class Foo
def self.bar
puts "I got called!"
end
class_alias :bar
end
# Show me the money!
Foo.bar => "I got called!"
f = Foo.new
f.bar => "I got called!"
4 comments
Leave a Comment