View Source for Ruby Code

10:15 AM EDT Tuesday, May 6 2008

One thing that all web developers do at some is view the HTML source of the page your application has generated. The reason why is because what your web application does is dynamically generate HTML and you want to see what HTML it generated. You can think of Ruby, as a metaprogramming language, as a language that dynamically generates code. If you are doing Rails, you see this all of the time with association methods like has_and_belongs_to_many. What has_and_belongs_to_many does is generate methods on your class. For example, if you have an Product class that has_and_belongs_to_many categories, it will add a category_ids= method to your class. This all happens at runtime, so you can't see the method, but if you use Ruby2Ruby, you can. sudo gem install ruby2ruby and then run script/console at the root of your Rails app. Then just run these simple commands:

>> require 'ruby2ruby'
>> puts Ruby2Ruby.translate(Article)

The output will be the ruby code that your class now has. Somewhere in that code you will see:

def category_ids=(new_value)
  ids = (new_value or []).reject { |nid| nid.blank? }
  send("#{reflection.name}=", reflection.class_name.constantize.find(ids))
end

Which is the category_ids= method that was generated by has_and_belongs_to_many.

Posted in  | Tags Ruby2Ruby, Rails, Ruby

Comments Feed

Add a Comment