2

I notice that some gems like Pry, Yaml and others seem to prototype every object (including string objects) and I would love to do the same thing for a HAML extension I made so that I can on the fly convert partials. Basically I want my own "%time".HAML_partial_render, any ideas on how I can do this?

3
  • can you explain what you mean when you say Pry seems to 'prototype every object' ? Commented Aug 30, 2011 at 9:40
  • @banister Well as you already know, everything is an object in Ruby, so... From an outsiders PoV (having not looked at the source...yet) it looks as if Pry prototypes (to some monkey patches) the object Object with the method pry which then follows suite down the line because of course Object is inherited by all Objects... so I can do "string".pry Commented Aug 30, 2011 at 21:21
  • ah ok, yeah it puts it on Object. Commented Aug 31, 2011 at 0:43

1 Answer 1

4

Ruby has open classes, so the quickest way to get what you want is something like:

class String
  def HAML_partial_render
    # your code
  end
end

If you want to keep it a bit cleaner, you could create a module, then mix that into string:

module HamlRendering
  def HAML_partial_render
    # your code
  end
end

class String
  include HamlRendering
end

This would also give you the ability to do on-the-fly extension as needed instead of polluting the entire object space:

"foo".extend(HamlRendering).HAML_partial_render

but that would get cluttered if you needed to use it everywhere.

There is a proposal for a concept known as Refinements under consideration that should clean this up for Ruby 2.0, but for now, I think opening the class in one of the above ways is your best bet.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.