Sha256: c3262502acf2ea37996a2ecb6f8d0a0e50abb0a37e1372ac90f4d6f82c8e228a

Contents?: true

Size: 1.67 KB

Versions: 8

Compression:

Stored size: 1.67 KB

Contents

# frozen-string-literal: true

#
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.
    #
    # Note that there is a rack-indifferent gem that
    # automatically makes rack use indifferent params. Using
    # rack-indifferent is faster and has some other minor
    # advantages over the indifferent_params plugin, though
    # it affects rack itself instead of just the Roda app that
    # you load the plugin into.
    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
            hash = Hash.new{|h, k| h[k.to_s] if Symbol === k}
            params.each{|k, v| hash[k] = indifferent_params(v)}
            hash
          when Array
            params.map{|x| indifferent_params(x)}
          else
            params
          end
        end
      end  
    end

    register_plugin(:indifferent_params, IndifferentParams)
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
roda-2.18.0 lib/roda/plugins/indifferent_params.rb
roda-2.17.0 lib/roda/plugins/indifferent_params.rb
roda-2.16.0 lib/roda/plugins/indifferent_params.rb
roda-2.15.0 lib/roda/plugins/indifferent_params.rb
roda-2.14.0 lib/roda/plugins/indifferent_params.rb
roda-2.13.0 lib/roda/plugins/indifferent_params.rb
roda-2.12.0 lib/roda/plugins/indifferent_params.rb
roda-2.11.0 lib/roda/plugins/indifferent_params.rb