So I’m taking my first step into using Presenters for my rails app and I’m just looking at a refactoring of some of my code. I have several fields which display phone numbers (i.e. phone, cell and fax) nicely formatted or show “none given”. Obviously I originally had this in the view but moved the logic into my presenter. Once there I noticed it was all the same so refactored it into a private method which uses the method name and the send function:
class CustomerPresenter < BasePresenter
presents :customer
def phone
format_number(__method__)
end
def cell
format_number(__method__)
end
def fax
format_number(__method__)
end
private
def format_number(method)
hande_none customer.send(method) do
h.number_to_phone(customer.send(method), :area_code => true)
end
end
end
and yet this code still doesn’t seem DRY. Because format_number uses the method name it seems that I have to define three seperate methods. I was curious if there was something more I could do here.
p.s. hande_none simply returns the block if there is something there or returns “none given”
I generally avoid to mix actual getter/method/attributes names with the methods used to format them.
That’s why I’d use
*_formattedsuffix: with a general suffix, you can have a simplemethod_missingwhich would lead you to something like:Basically, I’ve this in my BasePresenter for
*_currency_format