I’m writing an app that acts as a tailor measure form.
The customers model has a lot of attributes that are stored in the database as integers in millimeters.
Since this app will be used both in Europe and in the US I’ll use virtual attributes for showing the user a inches and a centimeter version of the data.
For example for the customer height I have this in my model:
def height_in_cm
height / 10
end
def height_in_cm=(height)
self.height = height.to_f * 10
end
def height_in_in
height * 0.039370
end
def height_in_in=(height)
self.height = height.to_f / 0.039370
end
And this in my _form view:
<% if @customer.measure_unit.eql? "imperial" %>
<%= f.input :height_in_in %></br>
<% else %>
<% if @customer.measure_unit.eql? "metric" %>
<%= f.input :height_in_cm %></br>
<% end %>
<% end %>
Since as I said I have many attributes my customer model file is becoming extremely long and very error prone.
Is there a dry way to shorten it up?
Encapsulate that logic something like this:
Then your view can just be like this:
If you are using these same conversion methods in lots of models, extract it out to a module like so:
And include it like so in the models where needed:
EDIT:
Ok, perhaps you need something more like this:
This is usually called metaprogramming. Here’s a nice concise article on different ways to do it in Rails:
http://www.trottercashion.com/2011/02/08/rubys-define_method-method_missing-and-instance_eval.html