ActiveModel::Name - Convenient String Conversion from Class

  • Feb 16

From time to time, we need to generate string from a class. For example, if you want to get a singular variable name from a class, you might convert class into string via .to_s and use inflector from ActiveSuuport. If there is a namespace, things become complicated.

Now, Rails provides a convenient way to get all commons string from class: ActiveModel::Name. If you have a class Store::Bookmark, you can get:

> mn = Store::Bookmark.model_name
> mn.name # => "Store::Bookmark"
> mn.klass # => Store::Bookmark (call 'Bits::Hyperlink.connection' to establish a connection)
> mn.singular # => "store_bookmark"
> mn.plural # => "store_bookmarks"
> mn.element # => "bookmark"
> mn.human # => "Boomark"
> mn.collection # => "store/bookmarks"
> mn.param_key # => "store_boomark"
> mn.i18n_key # => "store/bookmark"
> mn.route_key # => "store_bookmarks"
> mn.singular_route_key # => "store_bookmark"