Sha256: 0f0e4138a75fe73ee904c30627329c9d544acb1f27b085b0cbb26a584d87ec5e

Contents?: true

Size: 1.97 KB

Versions: 4

Compression:

Stored size: 1.97 KB

Contents

require 'cgi'
require 'forwardable'

module Webmachine
  # Request represents a single HTTP request sent from a client. It
  # should be instantiated by {Adapters} when a request is received
  class Request
    extend Forwardable
    attr_reader :method, :uri, :headers, :body
    attr_accessor :disp_path, :path_info, :path_tokens

    # @param [String] method the HTTP request method
    # @param [URI] uri the requested URI, including host, scheme and
    #   port
    # @param [Headers] headers the HTTP request headers
    # @param [String,#to_s,#each,nil] body the entity included in the
    #   request, if present
    def initialize(method, uri, headers, body)
      @method, @uri, @headers, @body = method, uri, headers, body
    end

    def_delegators :headers, :[]

    # Enables quicker access to request headers by using a
    # lowercased-underscored version of the header name, e.g.
    # `if_unmodified_since`.
    def method_missing(m, *args, &block)
      if m.to_s =~ /^(?:[a-z0-9])+(?:_[a-z0-9]+)*$/i
        # Access headers more easily as underscored methods.
        self[m.to_s.tr('_', '-')]
      else
        super
      end
    end

    # @return[true, false] Whether the request body is present.
    def has_body?
      !(body.nil? || body.empty?)
    end
    
    # The root URI for the request, ignoring path and query. This is
    # useful for calculating relative paths to resources.
    # @return [URI]
    def base_uri
      @base_uri ||= uri.dup.tap do |u|
        u.path = "/"
        u.query = nil
      end
    end

    # Returns a hash of query parameters (they come after the ? in the
    # URI). Note that this does NOT work in the same way as Rails,
    # i.e. it does not support nested arrays and hashes.
    # @return [Hash] query parameters
    def query
      unless @query
        @query = {}
        uri.query.split(/&/).each do |kv|
          k, v = CGI.unescape(kv).split(/=/)
          @query[k] = v if k && v
        end
      end
      @query
    end
  end
end

Version data entries

4 entries across 3 versions & 1 rubygems

Version Path
webmachine-0.4.1 pkg/webmachine-0.3.0/lib/webmachine/request.rb
webmachine-0.4.1 pkg/webmachine-0.4.0/pkg/webmachine-0.3.0/lib/webmachine/request.rb
webmachine-0.4.0 pkg/webmachine-0.3.0/lib/webmachine/request.rb
webmachine-0.3.0 lib/webmachine/request.rb