Sha256: 5f9f60a82220bc48e7f3442a82fe702fd49738d713217d1b8690767cd368e368

Contents?: true

Size: 1.52 KB

Versions: 52

Compression:

Stored size: 1.52 KB

Contents

require "uri"

class Nori
  module CoreExt
    module Hash

      # @param key<Object> The key for the param.
      # @param value<Object> The value for the param.
      #
      # @return <String> This key value pair as a param
      #
      # @example normalize_param(:name, "Bob Jones") #=> "name=Bob%20Jones"
      def normalize_param(key, value)
        if value.is_a?(Array)
          normalize_array_params(key, value)
        elsif value.is_a?(Hash)
          normalize_hash_params(key, value)
        else
          normalize_simple_type_params(key, value)
        end
      end

      # @return <String> The hash as attributes for an XML tag.
      #
      # @example
      #   { :one => 1, "two"=>"TWO" }.to_xml_attributes
      #     #=> 'one="1" two="TWO"'
      def to_xml_attributes
        map do |k, v|
          %{#{k.to_s.snakecase.sub(/^(.{1,1})/) { |m| m.downcase }}="#{v}"}
        end.join(' ')
      end

      private

      def normalize_simple_type_params(key, value)
        ["#{key}=#{encode_simple_value(value)}"]
      end

      def normalize_array_params(key, array)
        array.map do |element|
          normalize_param("#{key}[]", element)
        end
      end

      def normalize_hash_params(key, hash)
        hash.map do |nested_key, element|
          normalize_param("#{key}[#{nested_key}]", element)
        end
      end

      def encode_simple_value(value)
        URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
      end

    end
  end
end

Hash.send :include, Nori::CoreExt::Hash

Version data entries

52 entries across 44 versions & 6 rubygems

Version Path
vagrant-compose-yaml-0.1.2 vendor/bundle/ruby/2.2.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-compose-yaml-0.1.1 vendor/bundle/ruby/2.2.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-compose-yaml-0.1.0 vendor/bundle/ruby/2.2.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-unbundled-1.8.5.2 vendor/bundle/ruby/2.3.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-unbundled-1.8.5.1 vendor/bundle/ruby/2.3.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-unbundled-1.8.4.2 vendor/bundle/ruby/2.3.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-unbundled-1.8.4.1 vendor/bundle/ruby/2.3.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-unbundled-1.8.1.1 vendor/bundle/ruby/2.3.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-cloudstack-1.2.0 vendor/bundle/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
vagrant-cloudstack-1.1.0 vendor/bundle/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
nori-2.6.0 lib/nori/core_ext/hash.rb
nori-2.5.0 lib/nori/core_ext/hash.rb