Sha256: 812dd0cb06e11bdf229f05f652bff2103049c9db84f82540b92ff4cfdddfe18b

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

module Representable
  module JSON
    class Binding
      attr_reader :definition

      def initialize(definition)
        @definition = definition
      end
      
      def read(hash)
        value_from_hash(hash) or default
      end
      
    private
      def default
        ""
      end
      
      def collect_for(hash)
        nodes = hash[definition.from] or return
        nodes = [nodes] unless nodes.is_a?(Array)
        
        vals  = nodes.collect { |node| yield node }
        
        definition.array? ? vals : vals.first
      end
    end
    
    # Represents plain key-value.
    class TextBinding < Binding
      def write(hash, value)
        hash[definition.from] = value
      end

    private
      def value_from_hash(hash)
        collect_for(hash) do |value|
          value
        end
      end
    end
  
    # Represents a tag with object binding.
    class ObjectBinding < Binding
      def write(hash, value)
        if definition.array?
          hash.merge!({definition.from => value.collect {|v| v.to_hash(:wrap => false)}})
        else
          hash.merge! value.to_hash
        end
      end

    private
      def default
        []
      end
      
      def value_from_hash(hash)
        collect_for(hash) do |node|
          definition.sought_type.from_hash(node)  # call #from_hash as it's already deserialized.
        end
      end
      
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
representable-0.9.3 lib/representable/bindings/json_bindings.rb