Sha256: fd02e6af94c5b40b046568fb4df81c9afb633138107ebf8c2585b61e2a8c13ff

Contents?: true

Size: 1.04 KB

Versions: 2

Compression:

Stored size: 1.04 KB

Contents

require 'multi_json'
require 'representable/hash'

module Representable
  # Brings #to_json and #from_json to your object.
  module JSON
    extend Hash::ClassMethods
    include Hash

    def self.included(base)
      base.class_eval do
        include Representable # either in Hero or HeroRepresentation.
        extend ClassMethods # DISCUSS: do that only for classes?
        extend Representable::Hash::ClassMethods  # DISCUSS: this is only for .from_hash, remove in 2.3?
      end
    end


    module ClassMethods
      # Creates a new object from the passed JSON document.
      def from_json(*args, &block)
        create_represented(*args, &block).from_json(*args)
      end

    private
      def representer_engine
        Representable::JSON
      end
    end


    # Parses the body as JSON and delegates to #from_hash.
    def from_json(data, *args)
      data = MultiJson.load(data)
      from_hash(data, *args)
    end

    # Returns a JSON string representing this object.
    def to_json(*args)
      MultiJson.dump to_hash(*args)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
representable-1.8.5 lib/representable/json.rb
representable-1.8.4 lib/representable/json.rb