Class Alias

Mar 26th — 1:24 PM

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!" 

Filed under: stunt ruby

4 comments

  • Sean Huber said
    Cool, but needs to be able to accept arguments as well: class Object def class_alias(method_id) define_method(method_id) do |*args| self.class.send method_id, *args end end end
  • RSL said
    D'oh! Updated. Thanks!
  • blj said
    Is it not mapping , than doing an alias job? Am confused about the name here.
  • RSL said
    The name is more of a joke, hence the "stunt ruby" tag. But it does function in the same way that alias does so I just stuck that label on it. But yes, it is just shorthand for writing a instance level wrapper for the class level method.

Leave a Comment

Lucky Sneaks is designed and managed by Lucky Sneaks
All content © Lucky Sneaks 2008
Lucky Sneaks is Lucky Sneaks