Sha256: 76b66848c1ffa3231dd0822bbcd2c26d1599144587e9d64d50460454fee60d93

Contents?: true

Size: 1.67 KB

Versions: 2

Compression:

Stored size: 1.67 KB

Contents

module Finix
  module HalResource

    attr_accessor :hyperlinks
    attr_accessor :attributes

    def method_missing(method, *args, &block)
      attributes = [@attributes]
      attributes << @attributes['page'] unless @attributes['page'].nil?
      attributes.each do |attrs|
        if attrs.has_key?(method.to_s)
          return attrs[method.to_s]
        end
      end

      if @attributes.empty? or (@attributes.has_key?('page') and not @attributes.has_key?('items'))
        self.refresh if self.respond_to? :refresh
        return self.send :method_missing, method, *args, &block
      end

      case method.to_s
        when /(.+)=$/ # support setting
          attr = method.to_s.chop
          @attributes[attr] = args.slice(0)
        else
          @hyperlinks.send :method_missing, method, *args, &block
      end
    end

    def load_page_from_response!(response)
      body = Finix::Utils.indifferent_read_access response.body

      hash_class = Finix::Utils.eval_class(self, IndifferentHash)
      @hyperlinks = hash_class.new
      links = body.delete('_links')
      links.each { |key, link| @hyperlinks[key.to_sym] = link[:href] } unless links.nil?

      page = body.delete('page')
      @attributes = {'items' => [], 'page' => hash_class.new(page)} # clear attributes
      if body.has_key? '_embedded'
        resource_name, resources = body.delete('_embedded').first
        @resource_class = Finix.from_hypermedia_registry resource_name
        @attributes['items'] = resources.map do |attrs|
          cls = Finix.from_hypermedia_registry resource_name, attrs
          cls.construct_from_response attrs
        end
      end

      @attributes.merge! body
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
finix-1.0.1 lib/finix/hal_resource.rb
finix-1.0.0 lib/finix/hal_resource.rb