Sha256: fa35757873b5680509caeca22cbe4d1a465055f61cd3c3bd7f3dd078ded0af13

Contents?: true

Size: 1.81 KB

Versions: 6

Compression:

Stored size: 1.81 KB

Contents

require 'representable'
require 'representable/bindings/hash_bindings'

module Representable
  # The generic representer. Brings #to_hash and #from_hash to your object.
  # If you plan to write your own representer for a new media type, try to use this module (e.g., check how JSON reuses Hash's internal
  # architecture).
  module Hash
    def self.included(base)
      base.class_eval do
        include Representable # either in Hero or HeroRepresentation.
        extend ClassMethods # DISCUSS: do that only for classes?
      end
    end


    module ClassMethods
      def from_hash(*args, &block)
        create_represented(*args, &block).from_hash(*args)
      end

    private
      def representer_engine
        Representable::Hash
      end
    end


    # Note: `#from_hash` still does _not_ stringify incoming hashes. This is per design: Representable is not made for hashes, only,
    # but for any arbitrary data structure. A generic `key.to_s` with non-hash data would result in weird issues.
    # I decided it's more predictable to require the user to provide stringified keys.
    def from_hash(data, options={}, binding_builder=PropertyBinding)
      data = filter_wrap(data, options)

      update_properties_from(data, options, binding_builder)
    end

    def to_hash(options={}, binding_builder=PropertyBinding)
      hash = create_representation_with({}, options, binding_builder)

      return hash unless wrap = options[:wrap] || representation_wrap(options)

      {wrap => hash}
    end

  private
    def filter_wrap(data, options)
      return data unless wrap = options[:wrap] || representation_wrap(options)
      filter_wrap_for(data, wrap)
    end

    def filter_wrap_for(data, wrap)
      data[wrap.to_s] || {} # DISCUSS: don't initialize this more than once. # TODO: this should be done with #read.
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
representable-1.8.5 lib/representable/hash.rb
representable-1.8.4 lib/representable/hash.rb
representable-1.8.3 lib/representable/hash.rb
representable-1.8.2 lib/representable/hash.rb
representable-1.8.1 lib/representable/hash.rb
representable-1.8.0 lib/representable/hash.rb