Sha256: 0ef802e5cdb368a7892a2e5ca2c54cac50c41e264bfa331183a2ca9c81592301

Contents?: true

Size: 1.85 KB

Versions: 1

Compression:

Stored size: 1.85 KB

Contents

module GoogleAjax
  # The Result classes are initialized with a hash.
  # Filters can be included to modify this hash.
  module Filters

    # The Recursive filter converts all Hash values to GoogleAjax::Base (recursively)
    # This will also make any other filters included in GoogleAjax::Base be called
    module Recursive
      
      # A utility method to inspect value and convert Hash to base_klass, even when inside arrays
      def self.remap(value, base_klass = Base)
        case value
        when ::Hash
          base_klass.new(value)
        when Array
          value.map{|e| remap(e)}
        else
          value
        end
      end

      def initialize(h)
        h.each{|key, value| h[key] = Recursive.remap(value)}
        super(h)
      end
    end

    # The SymbolizeKeys filter converts the Javascript style keys ("someKey")
    # to ruby-style keys (:some_key)
    module SymbolizeKeys
      def initialize(h)
        h= ::Hash[
          h.map do |key, value|
            [key.underscore.to_sym, value]
          end
        ]
        super(h)
      end
    end

    # The ConvertValues filter converts the string values
    # to ruby-style values (e.g. Integers, Floats, true, false or Strings)
    module ConvertValues
      TRUE_OR_FALSE = /^true|(false)$/i
      INTEGER = /^\d+$/
      FLOAT = /^\d+\.\d+$/
      def initialize(h)
        h.each do |key, value|
          # Won't use Integer.try_convert for 1.8.6 & 7 compatibility
          case value
          when INTEGER
            h[key] = value.to_i
          when FLOAT
            h[key] = value.to_f
          when TRUE_OR_FALSE
            h[key] = Regexp.last_match[1].nil?
          end
        end
        super(h)
      end
    end

    # By default, all filters are applied
    module Default
      include ConvertValues
      include SymbolizeKeys
      include Recursive
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
googleajax-1.0.0 lib/googleajax/filters.rb