문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top