Sha256: e62bd2206ca351cb2123b078f511c7ccb7d82be371c7bed4fe9b51022cb45eac

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 KB

Contents

module Rack
  class RestfulSubmit < MethodOverride

    REWRITE_KEYWORD = '__rewrite'.freeze
    REWRITE_MAP = '__map'.freeze

    def initialize(app)
      @app = app
    end

    def call(env)
      if env["REQUEST_METHOD"] == "POST"
        req = Request.new(env)

        if req.params[REWRITE_KEYWORD] && req.params[REWRITE_MAP]
          action = req.params[REWRITE_KEYWORD].keys.first # Should be always just one.
          mapping = req.params[REWRITE_MAP][action]

          if mapping && mapping['url'] && mapping['method']
            rewrite(env, mapping['url'], mapping['method'])
          else
            return super(env)
          end
        else
          return super(env)
        end
      end

      @app.call(env)
    end

    private

    def rewrite(env, url, method)
      rewrite_request(env, url)
      rewrite_method(env, method)
    end

    def rewrite_request(env, prefixed_uri)
      # rails 3 expects that relative_url_root is not part of
      # requested uri, this fix also expects that mapping['url']
      # contains only path (not full url)
      uri = prefixed_uri.sub(/^#{Regexp.escape(env['SCRIPT_NAME'].to_s)}\//, '/')

      env['REQUEST_URI'] = uri
      env['PATH_INFO'],env['QUERYSTRING']=uri,'' unless uri.index('?')
      env['PATH_INFO'],env['QUERYSTRING']=uri.split('?',2) if uri.index('?')
    end

    def rewrite_method(env, method)
      if HTTP_METHODS.include?(method)
        env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
        env["REQUEST_METHOD"] = method
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rack-restful_submit-1.2.2 lib/rack/rack-restful_submit.rb
rack-restful_submit-1.2.1 lib/rack/rack-restful_submit.rb