Today I Learned

hashrocket A Hashrocket project

Classify and Constantize

Metaprogramming! Today I created a variable event that calls a serializer unique to the value of event. Along the way I learned about the Rails methods classify and constantize.

classify takes a plural table name and returns a class name.

> 'some_things'.classify
=> "SomeThing"

constantize tries to find a constant with the name specified in the argument string.

> "Module".constantize
=> Module

> "Nothing".constantize
NameError: uninitialized constant Nothing

Here's a sample of how I used these methods today (on the 'Today I Learned' app itself):

# app/models/post.rb
event = 'some_important_event'

# app/workers/event_notifier.rb
"#{event.classify}Serializer".constantize.new

This will new up an instance of SomeImportantEventSerializer, if such a class exists.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.