Metaprogramming in Ruby (Part one)

    One of Ruby's best kept secrets is the extremely clean metaprogramming tools it carries. Ruby developers see these a lot but never really know how they work, and the amount of documentation of them is so thin it's almost nonexistent. So over the next few days I hope to post a series of helpful articles covering this topic, and I'd be more than happy to answer any questions you might have on the subject as well (feel free to post a comment, mkay?)

    So let's get started shall we? The most standout example of metaprogramming in ruby is dynamically creating methods at runtime, and not at coding time (no compile time in ruby, remember?). There are many ways you can do this, and likely the easiest is using singleton methods. But before we get started, let's create a simple class we can use in the next few examples, shall we?

# Here's a simple class with a property that is set when
# a new instance is created
class MyClass
  def initialize(name = "MyClass")
    @name = name
  end
end

    Now that we have a (admittedly not very grandiose) class to work with, let's go ahead and create a new instance of it, and define a method that returns @name.

my_object = MyClass.new
def my_object.name
  @name
end
my_object.name => "MyClass"

    Singleton methods are handy for a multitude of things, especially when you only want to modify the methods of one object that already exists at runtime. However, they are not so handy when you're manipulating a multitude of objects at the same time, especially if they're the same type.

    Anyways, that's all for today, tomorrow I will cover the tool behind ActiveRecord and DataMappers magic: class_eval.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

gucci

Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://www.oneor-more.com/

supplynflshop

thank you for sharing
http://www.supplynflshop.com

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options