neezer
neezer

Reputation: 20560

Ruby: How to DRY up similar model attribute calls

I have a User model with a number of very similar properties that I want to list without typing each on in individually.

So, rather than:

"eye color: #{@user.his_eye_color}"
"hair color: #{@user.his_hair_color}"
"height: #{@user.his_height}"
"weight: #{@user.his_weight}"
...

"eye color: #{@user.her_eye_color}"
"hair color: #{@user.her_hair_color}"
"height: #{@user.her_height}"
"weight: #{@user.her_weight}"
...

I'd like to do a block or something (Proc? Lambda? Still a touch unclear what those are...):

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.her_(stat.underscore)}"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.his_(stat.underscore)}"
end

I know that what I just wrote above is mystical, magical, and wholly and completely WRONG (the @user.his_(stat.underscore) part), but what could I do that's like this? I basically need to call my Model's attributes dynamically, but I'm unsure how to do this...

Any help would be really appreciated!

Upvotes: 2

Views: 141

Answers (2)

MBO
MBO

Reputation: 30995

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"her_#{stat.tr(" ","_")}") }"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"his_#{stat.tr(" ","_")}") }"
end

This should work. You can always use send to call method on object, and generate that method name on the fly as string

Upvotes: 5

Farrel
Farrel

Reputation: 2381

If you're using ActiveRecord in Rails you can also use the Object#[] method to get the values of attributes dynamically

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user[ "her_#{ stat.underscore }"]}"
end

Upvotes: 2

Related Questions