JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.

Posts tagged with "pagination"

April 25, 2011

Parsing and Pluralizing Model Names in Rails

Recently working with Kaminari, I wanted to have text display next to the pagination links like

283 Items - Page 3/15

I wanted the Items text to be dynamic according to the model the paginated collection was representing. Looking over my model names I found converting each to a human readable version would work great in all cases I needed a paginator. Simply using pluralize (I use singular form for my models) will not work in all cases.

  • User would become Users - great!
  • Page would become Pages - great!
  • ConversationMessage would become ConversationMessages - yuck!

For the ConversationMessage model, I really only wanted to display the items in the collection to the user as Messages, not ConversationMessages or even Conversation Messages. I found this was common for my other models on the many side of a one-to-many relationship too (ie. for my UserComplaint model, I wanted the pagination text to say simply Complaints).

The following works beautifully for all models I currently have in place

@collection.first.class.name.underscore.humanize.pluralize.titleize[/\s?([^\s]+)$/, 1]

With models having their default names (in the plural form), the .pluralize call can be removed.

4 notes Tags: ruby ruby on rails rails RoR code tips Kaminari pagination paginator