sharing experiences

Dynamically Defining Methods with define_method

| Comments

If you have been hacking ruby for a while you should have heard that “Everything is an object”. To understand this concept knowing what a singleton class is important. Yehuda Katz’s post is a good source for it.

My ruby version 1.9.2.

First I’m going to show you how to add methods to instances by using define_method.

You can also write an instance method to create instance methods. send must be used because define_method is private.

Write a singleton method to create instance methods.

Now it is time to add singleton methods. When we call define_method, it creates an instance method. What we have to do is call define_method on class’ singleton class.

Getting singleton class of a class:

First defining singleton method to create singleton methods.

Then defining instance method to create singleton methods.

Nested Object Forms with has_one Relation

| Comments

Rails 2.3 has a good solution for multi model forms. But there is not much examples of  how to use accepts_nested_attributes_for with has_one relation.

Assume that we have a Book model which has one Author.

Controller :


No special action is needed for create method of BooksController,  attr_accessible is not necessary for Book model. Just don’t forget to add the second parameter (@book) of form_for and build your nested object (@book.build_author).

Tidbit: Converting Strings with Line Feed to Array

| Comments

If you have trouble when converting string to array, check if your string includes any line feed (\n). Check how Array("string") behaves:

irb(main):001:0> Array("izzet emre \nkutlu")
=> ["izzet emre \n", "kutlu"]

This output is not what most of the people expected. Be careful!

Rails 2.2 & Inflector

| Comments

If you have recently updated to Rails 2.2.2, you may encounter this error when you want to start your application:

`load_missing_constant': uninitialized constant Inflector (NameError)

As I learned from Paul’s post usage of Inflector class is changed a bit. You can see the difference when you compare the inflections.rb files. Path of the file is yourApp/config/initializers/inflections.rb

inflections.rb (Rails 2.1.0)

 Inflector.inflections do |inflect|

inflections.rb (Rails 2.2.2)

 ActiveSupport::Inflector.inflections do |inflect|

In my situation changing Inflector to ActiveSupport::Inflector was enough to solve the problem.