lib/finix/resources/resource.rb in finix-0.15 vs lib/finix/resources/resource.rb in finix-0.16
- old
+ new
@@ -1,31 +1,41 @@
-require File.expand_path('../../pagination', __FILE__)
-require File.expand_path('../../utils', __FILE__)
-require File.expand_path('../../hal_resource', __FILE__)
require 'addressable/template'
+require_relative '../utils'
+require_relative '../hal_resource'
+require_relative '../pagination'
+require_relative '../indifferent_hash'
+
module Finix
module Resource
include HalResource
- def initialize(attributes = {}, href = nil)
- @attributes = Utils.indifferent_read_access attributes
+ def initialize(*args)
+ opts = args.slice!(0) || {}
+ href = opts.delete(:href)
+ @attributes = Finix::Utils.indifferent_read_access opts
- @hyperlinks = {}
+ @hyperlinks = Finix::Utils.eval_class(self, IndifferentHash).new
@hyperlinks[:self] = href if href =~ URI::regexp
end
+ alias links hyperlinks
+
def hydrate(links)
links.each do |key, link|
property = key.sub(/.*?\./, '')
+ href = link[:href]
if property == 'self'
- @hyperlinks[:self] = link[:href]
+ @hyperlinks[:self] = href
else
- @hyperlinks[property] = Finix::Utils.callable(Finix::Utils.eval_class(self, 'Pagination').new link[:href], {})
+ split_uri = Finix.split_the_href(href).reverse!
+ cls = Finix.find_resource_cls split_uri[0]
+ cls = cls.nil? ? Finix.from_hypermedia_registry(href) : Finix::Utils.eval_class(self, Pagination)
+ @hyperlinks[property] = Finix::Utils.callable(cls.new :href => href)
end
end
end
def fetch(*arguments)
@@ -94,36 +104,47 @@
base.extend ClassMethods
end
module ClassMethods
+ # this is class method, not callable from instance
def construct_from_response(payload)
payload = Finix::Utils.indifferent_read_access payload
-
links = payload.delete('_links') || {}
instance = self.new payload
instance.hydrate(links)
instance
end
def fetch(*arguments)
if arguments.nil? or arguments.empty? or arguments[0].nil? or arguments[0].to_s.empty?
href = Finix.hypermedia_registry.key(self)
- return Finix::Utils.eval_class(self, 'Pagination').new href
+ return Finix::Utils.eval_class(self, Pagination).new :href => href
end
options = arguments.slice!(0) or {}
if options.is_a? String and options =~ URI::regexp
href = options
else
- href = Finix.hypermedia_registry.key(self) or Finix.hypermedia_registry.key(self.class)
- id = options if options.is_a? String
- id = options.delete(:id) if options.is_a? Hash
+ href = Finix.get_href(self) or Finix.get_href(self.class)
+ if options.is_a? Hash
+ options = Finix::Utils.indifferent_read_access options
+ id = options.delete('id')
+ elsif options.is_a? String
+ id = options
+ end
href = "#{href}/#{id}" unless id.nil?
end
response = Finix.get href
construct_from_response response.body
+ end
+
+ def pagination(*args)
+ href = Finix.hypermedia_registry.key(self)
+ opts = args.slice!(0) || {}
+ opts[:href] = href
+ Finix::Utils.eval_class(self, Pagination).new opts
end
alias find fetch
alias retrieve fetch
end