Cross Domain RESTful AJAX with jQuery and Rails 2.2.2

Flinn Mueller aka actsasflinn wrote an blog post Cross domain RESTful JSON-P with Rails back in July. There he showed how to monkeypatch Rails to allow json-p to do all the REST verbs even when going across domains. He also showed how to make the json-p calls with jquery. A very nice solution that we take advantage of in one of our apps. The only problem we had was that it stopped working when we upgraded to Rails 2.2.2.

There are other issues using this technique. To quote Flinn:

Achtung! Monkey patching with the above will expose your create method without using an actual post. Imho no big deal, others might be more cautious (CAPTCHAis always an option), ymmv.

See his original article for details on how to use it generally. 

The problem with the monkeypatch that he wrote up is that Rails 2.2.2 changed the function that was monkeypatched so the patch stopped working. Below is code that will work on both pre and post 2.2.2 Rails:

module ActionController
  class AbstractRequest

    def request_method

      if Rails::VERSION::STRING < "2.2.2"

        @request_method ||= begin

          method = (parameters[:_method].blank? ? @env['REQUEST_METHOD'] : parameters[:_method].to_s).downcase

          if ACCEPTED_HTTP_METHODS.include?(method)

            method.to_sym

          else

            raise UnknownHttpMethod, "#{method}, accepted HTTP methods are #{ACCEPTED_HTTP_METHODS.to_a.to_sentence}"

          end

        end

      else

        method = @env['REQUEST_METHOD']

        method = parameters[:_method] unless parameters[:_method].blank?

        HTTP_METHOD_LOOKUP[method] || raise(UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence}")
      end

    end

  end
end
Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • LinkedIn
  • Slashdot
  • Suggest to Techmeme via Twitter

1 comment to Cross Domain RESTful AJAX with jQuery and Rails 2.2.2

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>