Sha256: 63c5ea1aab8f7588c74ced203b289a0c6ca23ef451a33a37c1846f9685d7ff21

Contents?: true

Size: 1.46 KB

Versions: 2

Compression:

Stored size: 1.46 KB

Contents

require 'hyperclient/discoverer'

module Hyperclient
  # Public: This class is responsible for parsing a representation from the API
  # and exposing some methods to access its values.
  #
  # It is mainly used by Hyperclient::Resource.
  class Representation
    # Public: Initializes a Representation.
    #
    # representation - A Hash containing a representation from the API. If the
    # representation is not a Hash it will try to parse it as JSON.
    def initialize(representation)
      begin
        representation = JSON.parse(representation) unless representation.is_a? Hash
      rescue JSON::ParserError
        warn 'WARNING Hyperclient::Representation: JSON representation was not valid:'
        puts representation
        representation = {}
      end
      @representation = representation
    end

    # Public: Returns a Discoverer for the _links section of the representation. It
    # can be used later to use the resources from this section.
    def links
      @links ||= Discoverer.new(@representation['_links'])
    end

    # Public: Returns a Discoverer for the _embedded section of the representation.
    # It can be used later to use the resources from this section.
    def embedded
      @embedded ||= Discoverer.new(@representation['_embedded'])
    end

    # Public: Returns a Hash with the attributes of the resource.
    def attributes
      @attributes ||= @representation.dup.delete_if {|key, value| key =~ /^_/}
    end
  end
end

require 'json'

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hyperclient-0.0.8 lib/hyperclient/representation.rb
hyperclient-0.0.7 lib/hyperclient/representation.rb