Sha256: c0e772124c04349e8e76e3f21fb8288d248b9be6e6636e35b978365f21bad197

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

require 'cgi'
class Rack::App::Params

  def to_hash
    if @request_env[::Rack::App::Constants::PARSED_PARAMS]
      @request_env[::Rack::App::Constants::PARSED_PARAMS]
    else
      query_params.merge(request_path_params)
    end
  end

  protected

  def initialize(request_env)
    @request_env = request_env
  end

  def query_params
    raw_cgi_params.reduce({}) do |params_collection, (k, v)|

      if single_paramter_value?(v)
        params_collection[k]= v[0]

      else
        k = k.sub(/\[\]$/, '')
        params_collection[k]= v

      end

      params_collection

    end
  end

  def single_paramter_value?(v)
    v.is_a?(Array) and v.length === 1
  end

  def raw_cgi_params
    CGI.parse(@request_env[::Rack::QUERY_STRING].to_s)
  end

  def request_path_params
    path_params = {}
    path_params.merge!(extract_path_params) unless path_params_matcher.empty?
    path_params
  end

  def extract_path_params
    request_path_parts.each.with_index.reduce({}) do |params_col, (path_part, index)|
      params_col[path_params_matcher[index]]= path_part if path_params_matcher[index]
      params_col
    end
  end

  def request_path_parts
    @request_env[::Rack::PATH_INFO].split('/')
  end

  def path_params_matcher
    @request_env[::Rack::App::Constants::PATH_PARAMS_MATCHER] || {}
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rack-app-5.0.0.rc1 lib/rack/app/params.rb
rack-app-4.0.1 lib/rack/app/params.rb