Sha256: 77745f92c7548740f1cccae60d4b0183f298cf6718a87be0c5869aad02e2f1b8

Contents?: true

Size: 1.02 KB

Versions: 4

Compression:

Stored size: 1.02 KB

Contents

require 'multi_json'

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

4 entries across 4 versions & 1 rubygems

Version Path
representable-1.8.3 lib/representable/json.rb
representable-1.8.2 lib/representable/json.rb
representable-1.8.1 lib/representable/json.rb
representable-1.8.0 lib/representable/json.rb