【问题标题】:Combining two methods into one将两种方法合二为一
【发布时间】:2017-07-19 16:24:04
【问题描述】:

我有两种方法。

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)

你怎么看?

【问题讨论】:

  • stackoverflow 专门针对技术问题(错误、未按预期执行的代码等)。如果您正在寻找有关组织代码的最佳方式的意见,您应该尝试codereview stackexchange
  • 话虽如此,看来您的方向是正确的。尝试为包含 one_call_center 的每种类型的对象创建不同的函数无法扩展。

标签: ruby-on-rails ruby ruby-on-rails-5


【解决方案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

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

我强烈建议您重新审视代码中使用的名称,因为它们过于冗长。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多