These are two Rails helpers that could be very useful when injecting new instance methods in a class.

underscore

Converts from a class name to a underscore attribute.


>> 'MyClassName'.underscore => my_class_name

classify

Inverse method from underscore.


  >> "cool_articles".classify
=> "CoolArticles"

>> "comment".classify
=> "Comment"

Both, combined with singularize and pluralize, allows us to handle parent/child methods in a very handy way. For example:


elements_in_ = self.send(parent).send(self.class.to_s.pluralize.underscore)

or things like


Kernel.const_get(table_model.to_s.classify).find(:all) #Kernel.const_get gets an string and retrieves the class.

One Response to “Underscore and classify”

  1. Hanna said

    Hi,
    I am new in this technology but its really nice article about at the moment i have just read this nice set of Ruby FAQs

    Thanks

Leave a Reply