Sha256: b46ec5172eea75860539feaae667be8cda003408b1a5b0e8b90ca7e0ac2f2545

Contents?: true

Size: 994 Bytes

Versions: 7

Compression:

Stored size: 994 Bytes

Contents

require 'representable/hash'
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
    end
    
    
    # Parses the body as JSON and delegates to #from_hash.
    def from_json(data, *args)
      data = ::JSON[data]
      from_hash(data, *args)
    end
    
    # Returns a JSON string representing this object.
    def to_json(*args)
      to_hash(*args).to_json
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
representable-1.5.1 lib/representable/json.rb
representable-1.5.0 lib/representable/json.rb
representable-1.4.2 lib/representable/json.rb
representable-1.4.1 lib/representable/json.rb
representable-1.4.0 lib/representable/json.rb
representable-1.3.5 lib/representable/json.rb
representable-1.3.4 lib/representable/json.rb