如何在所有操作中干掉一个相同的respond_to?

时间:2015-06-09 17:05:04

标签: ruby-on-rails ruby respond-to

我有一个服务器小部件的控制器:

class WidgetsController < ApplicationController
  def widget1
    respond_to do |format|
      format.html
      format.js { render js: js_constructor }
    end
  end

  def widget2
    respond_to do |format|
      format.html
      format.js { render js: js_constructor }
    end
  end

  private
  def js_constructor
    content = render_to_string(params[:action], layout: false)
    "document.write(#{content.to_json})"
  end
end

这个控制器会变大,所以我想避免在所有操作中重复这段代码:

respond_to do |format|
  format.html
  format.js { render js: js_constructor }
end

有什么想法吗?

编辑:只是为了给出一些背景......

路线灵活/动态:get 'widgets/:action', to: 'widgets#:action'

因此,如果我访问widgets/widget1,它将呈现视图widget1.html.erb

如果我将脚本包含在另一个服务器中,它将在那里构建widget1:

<script type='text/javascript' src='http://localhost:3000/widgets/widget1.js'></script>

2 个答案:

答案 0 :(得分:1)

答案是元编程:

class WidgetsController < ApplicationController
  [:widget1, :widget2].each do |name|
    define_method(name) do
      respond_to do |format|
        format.html
        format.js { render js: js_constructor }
      end
    end
  end

  private

  def js_constructor
    content = render_to_string(params[:action], layout: false)
    "document.write(#{content.to_json})"
  end
end

答案 1 :(得分:1)

我会写一个采取&#34;视图&#34;作为参数。您基本上正在执行呈现不同观看次数的#show操作。

get 'widgets/:template', to: 'widgets#show'

class WidgetsController < ApplicationController
  def show
    respond_to do |format|
      format.html { render params.require(:template) }
      format.js { render js: js_constructor }
    end
  end

  private
  def js_constructor
    content = render_to_string(params.require(:template), layout: false)
    "document.write(#{content.to_json})"
  end
end