开发者

Ruby global prototyping like Object.prototype in Javascript?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜