Making Static Methods a First Class Citizen

Static methods are the syntactic vinegar of Ruby, they need some extra Syntax to declare and are cumbersome to call. Yet they are the best one can do to get reusable and testable components. Magic to the rescue!

class SomeKindOfClass
  def normal
    self.class.static_normal
  end

  def self.static_normal
  end
end

#self.class.static_normal is not very nice...
#but we could do klass.static_method or static.static_method with:
class Object
  def klass
    self.class
  end
end

#Or go extreme and allow class methods to be called like instance methods
#SomeKindOfClass.new.static_normal
class Object
  def method_missing name, *args
    return self.class.send(name, *args) if self.class.respond_to? name
    super
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s