Sha256: 02de7d129e9e00706176f123172227712b89b7c2541357e234672747d71f3414

Contents?: true

Size: 1.3 KB

Versions: 14

Compression:

Stored size: 1.3 KB

Contents

class Roda
  module RodaPlugins
    # The indifferent_params plugin adds a +params+ instance
    # method which returns a copy of the request params hash
    # that will automatically convert symbols to strings.
    # Example:
    #
    #   plugin :indifferent_params
    #
    #   route do |r|
    #     params[:foo]
    #   end
    #
    # The params hash is initialized lazily, so you only pay
    # the penalty of copying the request params if you call
    # the +params+ method.
    module IndifferentParams
      module InstanceMethods
        # A copy of the request params that will automatically
        # convert symbols to strings.
        def params
          @_params ||= indifferent_params(request.params)
        end

        private

        # Recursively process the request params and convert
        # hashes to support indifferent access, leaving
        # other values alone.
        def indifferent_params(params)
          case params 
          when Hash
            h = Hash.new{|h, k| h[k.to_s] if Symbol === k}
            params.each{|k, v| h[k] = indifferent_params(v)}
            h
          when Array
            params.map{|x| indifferent_params(x)}
          else
            params
          end
        end
      end  
    end

    register_plugin(:indifferent_params, IndifferentParams)
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
roda-cj-1.0.5 lib/roda/plugins/indifferent_params.rb
roda-cj-1.0.4 lib/roda/plugins/indifferent_params.rb
roda-cj-1.0.3 lib/roda/plugins/indifferent_params.rb
roda-cj-1.0.2 lib/roda/plugins/indifferent_params.rb
roda-cj-1.0.1 lib/roda/plugins/indifferent_params.rb
roda-cj-1.0.0 lib/roda/plugins/indifferent_params.rb
roda-1.0.0 lib/roda/plugins/indifferent_params.rb
roda-cj-0.9.6 lib/roda/plugins/indifferent_params.rb
roda-cj-0.9.5 lib/roda/plugins/indifferent_params.rb
roda-cj-0.9.4 lib/roda/plugins/indifferent_params.rb
roda-cj-0.9.3 lib/roda/plugins/indifferent_params.rb
roda-cj-0.9.2 lib/roda/plugins/indifferent_params.rb
roda-cj-0.9.1 lib/roda/plugins/indifferent_params.rb
roda-0.9.0 lib/roda/plugins/indifferent_params.rb