【问题标题】:Simplify Rails Method and nested variable简化 Rails 方法和嵌套变量
【发布时间】:2020-09-20 07:27:49
【问题描述】:

我有两种方法,如下所示:

def post(type, params=nil)
    if params
    @animalCategory.post(type, params:params[:params], header:{...}) 
    else 
      @animalCategory.post(type, header:{...}) 
    end
  end

  def put(route, params=nil)
    if params
      @animalCategory.put(type, params:params[:params], header:{...})  
    else
      @animalCategory.put(type, header:{...})  
    end
  end

它是这样调用的:

 animal_category.put '/cat', params: data

我有上面两个函数的包装器。他们基本上做同样的事情,除了一个叫一个帖子,另一个叫一个看跌。我想知道是否有办法合并/简化它。另外,有没有建议的方法来简化 params:params[:params] 的提取?

【问题讨论】:

  • 定义一个函数,除了其他参数外,还可以查看一个动作。如果发布或放置,则通过简单的函数内部。请让我知道你的想法

标签: ruby-on-rails ruby methods


【解决方案1】:
def put_or_post(http_method, type, params=nil)
  if params
    @animalCategory.send(http_method, type, params:params[:params], header:{...}) 
  else 
    @animalCategory.send(http_method, type, header:{...}) 
  end
end

使用Object#send从变量中调用方法

然后您可以重构其他方法来调用它:

def put(*args)
  put_or_post :put, *args
end

def post(*args)
  put_or_post :post, *args
end

并保持原来的通话签名 (animal_category.put) 不变

【讨论】:

  • 我认为 object.send 是我正在寻找的。这是否意味着我可以保持原样?例如。 animal_category.put '/cat', params: 数据可以保持不变?
  • 顺便说一句,您没有将params 定义为关键字参数,因此params: data 不起作用,您只需将data 作为第二个参数传递,删除params:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2021-08-27
  • 2023-04-04
  • 2015-01-15
相关资源
最近更新 更多