Question

Let's say I have a User model with a name attribute. If a @user has name 'CAIO' I can call the humanize method to make it nicer:

@user.name          =======> CAIO
@user.name.humanize =======> Caio

But I'm lazy and I don't want to call humanize every time: I would like @user.name to return the humanized version.

Now, I know that I could do it with a helper method or a model one like

def h_name
  self.name.humanize
end

but doing like this then I have to change all the @user.name in my app with @user.h_name... and I'm lazy!!! :-)

Isn't there a way to declare it directly in the model, but using name to call it? Even better it would be something working for the name of all my models!

Was it helpful?

Solution

Check out draper. This gem provides decorators (much like presenters) which bundles view logic in an object oriented fashion. Also, Ryan Bates has put together an excellent RailsCast on Draper.

OTHER TIPS

You can add before_save in model.

before_save :h_name

def h_name self.name = self.name.humanize end

This similar question explains several ways to do this.

One possibility is:

class User < ActiveRecord::Base
    def name
        super().humanize
    end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top