Rails - Humanize attribute globally
-
27-06-2021 - |
Frage
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!
Lösung
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.
Andere Tipps
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