2017-07-19 88 views
-4

我有两种方法。将两种方法合并为一个

def response_code_description(code) 
    @response_code_description ||= current_account.one_call_center.response_codes_repository_class.new.to_api_collection 
    @response_code_description.find {|k| k['code'] == code}.try(:[], 'description') 
end 

def ticket_response_code_with_description(ticket_response) 
    @ticket_response_code_with_description ||= ticket_response.ticket.one_call_center.response_codes_repository_class.new.to_api_collection 
    @ticket_response_code_with_description.find { |k| k['code'] == ticket_response.code }.try(:[], 'description') 
end 

我想我可以合并它们。 所以。

def response_code_with_description(one_call_center, code) 
    @ticket_response_code_with_description ||= one_call_center.response_codes_repository_class.new.to_api_collection 
    @ticket_response_code_with_description.find { |k| k['code'] == code }.try(:[], 'description') 
end 

,并调用此方法,以便

response_code_with_description(current_account.one_call_center, ticket_response.code) 
response_code_with_description(ticket_response.ticket.one_call_center, code) 

你觉得呢?

+4

stackoverflow是专门针对技术问题(错误,代码没有做它应该的,等等)。如果您正在寻找关于组织代码的最佳方式的意见,那么您应该尝试[codereview stackexchange](https://codereview.stackexchange.com/) – eiko

+0

,据说它看起来像在右边跟踪。试图为包含'one_call_center'的每种类型的对象创建不同的函数不会缩放。 – eiko

回答

1

这两种方法之间的主要区别似乎是这一部分:

k['code'] == code 
k['code'] == ticket_response.code 

因此,换句话说,你可以直接比较的说法,或code方法呼吁说法。通过使参数自适应来解决该问题:

def to_description(code) 
    code = code.code if (code.respond_to?(:code)) 
    # ... Rest of code presuming `code` is the thing to compare against. 
end 

这消除了两者之间的差异。

我强烈建议您在这里重新审视您的代码中使用的名称,它们不合理地冗长。