【问题标题】:Setting of "respond_to" outside of action在行动之外设置“respond_to”
【发布时间】:2015-02-25 12:06:37
【问题描述】:

我想在动作之外设置“respond_to”动作的一部分。

这是一个应该如何工作的示例:

def index
  ...
end

def show
  ...
end

response_for :index, :show do
  format.html do
     if empty_records?
       redirect_to root_path
     end
  end

  format.json do
    ...
  end
end

之前我为此使用了response_for gem,但它不再受支持。您可以建议哪些解决方案?我使用 Rails 4.2。

【问题讨论】:

  • 1.大部分遗留代码都是这样写的 2. DRY 原则

标签: ruby-on-rails ruby-on-rails-4 actionpack


【解决方案1】:

这个怎么样?

def index
  ...
  return respond
end

def show
  ...
  return respond
end

private

def respond
  respond_to do |format|
    ...
  end
end

我使用类似的模式通过我的 JSON API 构建共享的成功和失败响应。

【讨论】:

  • 这是一个很好的解决方案,但与问题中描述的代码相比,它更复杂。另外我想指出,我有一个大型遗留项目,其中描述的模式经常使用,所以它会更容易实现“response_for”方法。
猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 2011-07-15
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多