Craig W. wrote:
I guess the thing I don’t understand is…why would this go into a
model
or a helper? What is the criteria? (other than arbitrary)…btw, this
code runs from my ‘reports’ controller.
my 2 cents:
It belongs in a model if:
- It can provide data to other code in a way that will not change if
the underlying representation changes. Other code should never
have
intimate knowledge of underlying representation.
It belongs in a helper if:
- It needs to be shared amongst more than 1 controller
(authorization
and authentication comes to mind)
- It relates to view code
As an example: Imagine we have a model that has a column, :type, and
that
column can contain ‘M’, ‘C’, or ‘A’, which represent MasterCard,
Visa, and
Amex, respectively.
Nothing outside the model should ever know about ‘M’, ‘C’, and ‘A’!
Instead, in the model:
def is_mastercard?
type == ‘M’
end
def is_visa?
type == ‘V’
end
def is_amex?
type == ‘A’
end
And a helper:
def card_name_for(card)
return “MasterCard” if card.is_mastercard?
return “Visa” if card.is_visa?
return “Priceless :-)” if card.is_amex?
end
And in the view:
<% for card in @cards -%>
Type: <%= card_name_for(card) %>
<% end -%>
This gives you a great deal of isolation, and some useful
methods on the model that make the helper and (no doubt)
other code more readable, and allows for a complete
refactor of Card.type in the future without changing
anything else.
For instance, why store card type at all when it can be
derived from the card number itself? If you’ve written it
this way, you can drop the column, add the card number
differentiation logic to the is_*? model methods, and you’re
done.
–
– Tom M.