Sha256: 891d76c97b34add4d12344b7ac96843bfe1ef39355d7989d00d995e185bb100d

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

module Representable
  module JSON
    class Binding
      attr_reader :definition
      delegate :required?, :array?, :accessor, :wrapper, :name, :to => :definition

      def initialize(definition)
        @definition = definition
      end
      
      def value_in(hash)
        value_from_hash(hash) or default
      end
      
    private
      def default
        ""
      end
      
      def collect_for(hash)
        nodes = hash[name.to_s] or return
        nodes = [nodes] unless nodes.is_a?(Array)
        
        vals  = nodes.collect { |node| yield node }
        
        array? ? vals : vals.first
      end
    end
    
    # Represents plain key-value.
    class TextBinding < Binding
      def update_json(hash, value)
        hash[name] = 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
      delegate :sought_type, :to => :definition
      
      def update_json(hash, value)
        if array?
          hash.merge! ({accessor => value.collect {|v| v.to_hash(:wrap => false)}}) # hier name=> wech.
        else
          hash.merge! value.to_hash
        end
      end

    private
      def default
        []
      end
      
      def value_from_hash(xml)
        collect_for(xml) do |node|
          sought_type.from_json(node, :wrap => false) # hier name=> wech.
        end
      end
      
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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