2012-07-27 60 views
0

因此,我正在采取我的第一步使用Presenters for rails应用程序,而我只是在重构一些代码。我有几个显示电话号码(即电话号码,手机号码和传真号码)格式良好或显示“没有给定”的字段。很明显,我原本是这样认为的,但把逻辑转移到我的主持人身上。一旦那里我发现这一切都是一样的,所以它重构到它使用的方法名称和发送功能的私有方法:依赖于__method__的重构方法

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 

,但这段代码似乎仍然没有干。由于format_number使用方法名,所以我必须定义三个独立的方法。我很好奇,如果在这里我还能做更多的事情。

p.s. hande_none只是返回块,如果有什么或返回“没有给出”

回答

0

我通常避免混合实际的getter /方法/属性名称与用于格式化它们的方法。

这就是为什么我会用*_formatted后缀:与一般的后缀,你可以有一个简单的method_missing这将导致你喜欢的东西:

class CustomerPresenter < BasePresenter 
    presents :customer 

    private 

    def format_number(method) 
    hande_none customer.send(method) do 
     h.number_to_phone(customer.send(method), :area_code => true) 
    end 
    end 

    def method_missing(method_name, *args, &block) 
    case method_name 
    when /(.*)_formatted$/ 
     #here you could create the method on the fly to avoid method missing next time 
     return format_number($1) 
    end  
    super(method_name, *args, &block) 
    end 
end 

基本上,我在BasePresenter为*_currency_format这已经