Sha256: 16d956624772c0bd6d0bc526197f3cbc0d0bdbafc24cbb5bce09624d808d99b4

Contents?: true

Size: 1.79 KB

Versions: 6

Compression:

Stored size: 1.79 KB

Contents

require 'representable/binding'

module Representable
  module JSON
    module ObjectBinding
      # TODO: provide a base ObjectBinding for XML/JSON/MP.
      include Binding::Extend  # provides #serialize/#deserialize with extend.
      
      def serialize(object)
        super(object).to_hash(:wrap => false)
      end
      
      def deserialize(hash)
        super(create_object).from_hash(hash)
      end
      
      def create_object
        definition.sought_type.new
      end
    end
    
    
    class JSONBinding < Representable::Binding
      def initialize(definition) # FIXME. make generic.
        super
        extend ObjectBinding if definition.typed?
      end
      
      def read(hash)
        fragment = hash[definition.from]
        deserialize_from(fragment)
      end
      
      def write(hash, value)
        hash[definition.from] = serialize_for(value)
      end
    end
    
    
    class PropertyBinding < JSONBinding
      def serialize_for(value)
        serialize(value)
      end
      
      def deserialize_from(fragment)
        deserialize(fragment)
      end
    end
    
    
    class CollectionBinding < JSONBinding
      def serialize_for(value)
        value.collect { |obj| serialize(obj) }
      end
      
      def deserialize_from(fragment)
        fragment ||= {}
        fragment.collect { |item_fragment| deserialize(item_fragment) }
      end
    end
    
    
    class HashBinding < JSONBinding
      def serialize_for(value)
        # requires value to respond to #each with two block parameters.
        {}.tap do |hash|
          value.each { |key, obj| hash[key] = serialize(obj) }
        end
      end
      
      def deserialize_from(fragment)
        fragment.each { |key, item_fragment| fragment[key] = deserialize(item_fragment) }
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
representable-1.2.0 lib/representable/bindings/json_bindings.rb
representable-1.1.7 lib/representable/bindings/json_bindings.rb
representable-1.1.6 lib/representable/bindings/json_bindings.rb
representable-1.1.5 lib/representable/bindings/json_bindings.rb
representable-1.1.4 lib/representable/bindings/json_bindings.rb
representable-1.1.3 lib/representable/bindings/json_bindings.rb