I have a Model like this:
class MyModel
attr_accessor :size
end
Now i want to display the size in a human readable format. I could do this by adding the following code:
class MyModel
attr_accessor :size
def size_hr(bytes = nil, counter = -1)
counter += 1
bytes ||= size
if bytes < 1024
return "#{bytes.round(2)} #{unit_for(counter)}"
else
size_hr bytes/1024, counter
end
end
def unit_for(counter)
case counter
when 0 then "B"
when 1 then "KiB"
when 2 then "MiB"
when 3 then "GiB"
end
end
end
But I feel somehow bad about this as I would mix view stuff into the model. I’m looking for a design pattern which would be the right approach to do this. I read about decorator and presenter, but I don’t think they fit in here. What would be the right approach for this?
You can use Rails View Helpers, which is the simple and straight forward way. IMHO the Helpers tend to end up as junk drawer for all sorts of things. Thus, we prefer do work with the Deocrator Pattern. A good gem to do this would be draper.