Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to DRY up Rails 3 controllers by overriding methods like respond_with?
    text
    copied!<p>I'm trying to create a JSONP API for my Rails 3 application. Right now in my controllers, I have a lot of actions which follow this pattern:</p> <pre><code># This is from my users_controller.rb, as an example def index @users = User.all respond_with(@users, :callback =&gt; params[:callback]) end </code></pre> <p>While this works as is, I would like to DRY it up by not having to repeat the <code>:callback =&gt; params[:callback]</code> in every action's call to <code>respond_with</code>. How can I do this?</p> <p><strong>Update:</strong> One thing I've realized that is ugly about my above code is that the <code>:callback =&gt; params[:callback]</code> option will be passed for any response format, not just JSON. The following code is probably more correct:</p> <pre><code>def index @users = User.all respond_with(@users) do |format| format.json { render :json =&gt; @users, :callback =&gt; params[:callback]} end end </code></pre> <p>There are a couple ways I've considered to address this problem, but I can't figure out how to make them work:</p> <ul> <li>Override <code>render</code> (perhaps in the application controller) so that it accepts a <code>:jsonp</code> option that automatically includes the <code>:callback =&gt; params[:callback]</code> parameter. This way I could change the above code to the following, which is somewhat shorter:</li> </ul> <pre><code>def index @users = User.all respond_with(@users) do |format| format.json { render :jsonp => @users} end end</code></pre> <ul> <li>Create a responder that overrides <code>to_json</code> in order to solve my problem. That way I could leave out the block and just call <code>respond_with(@users, :responder =&gt; 'MyResponder')</code> to solve the issue. Or perhaps I could include this code in an application responder using <a href="https://github.com/plataformatec/responders" rel="noreferrer">plataformatec's responders gem</a> so that <code>respond_with(@users)</code> by itself would be sufficient.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload