Class: Restfolia::Resource
- Inherits:
-
Object
- Object
- Restfolia::Resource
- Defined in:
- lib/restfolia/resource.rb
Overview
Public: Resource is the representation of JSON response. It transforms all JSON attributes in attributes and provides a “links” method, to help with hypermedia navigation.
Examples
resource = Resource.new(:attr_test => "test")
resource.attr_test # => "test"
resource.links # => []
resource = Resource.new(:attr_test => "test",
:links => {:href => "http://service.com",
:rel => "self",
:type => "application/json"})
resource.attr_test # => "test"
resource.links # => [#<Restfolia::EntryPoint ...>]
By default, “links” method, expects from JSON to be the following formats:
# Array de Links
"links" : [{ "href" : "http://fakeurl.com/some/service",
"rel" : "self",
"type" : "application/json"
}]
# OR 'single' Links
"links" : { "href" : "http://fakeurl.com/some/service",
"rel" : "self",
"type" : "application/json"
}
# OR node 'Link', that can be Array or single too
"link" : { "href" : "http://fakeurl.com/some/service",
"rel" : "self",
"type" : "application/json"
}
Instance Attribute Summary collapse
-
#_json ⇒ Object
readonly
Public: Returns the Hash that represents parsed JSON.
Instance Method Summary collapse
-
#initialize(json) ⇒ Resource
constructor
Public: Initialize a Resource.
-
#links(rel = nil) ⇒ Object
Public: Read links from Resource.
Constructor Details
#initialize(json) ⇒ Resource
Public: Initialize a Resource.
json - Hash that represents parsed JSON.
Raises ArgumentError if json parameter is not a Hash object.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/restfolia/resource.rb', line 50 def initialize(json) unless json.is_a?(Hash) raise(ArgumentError, "json parameter have to be a Hash object", caller) end @_json = json #Add json keys as methods of Resource #http://blog.jayfields.com/2008/02/ruby-replace-methodmissing-with-dynamic.html @_json.each do |method, value| next if self.respond_to?(method) #avoid method already defined (class << self; self; end).class_eval do define_method(method) do |*args| value end end end end |
Instance Attribute Details
#_json ⇒ Object (readonly)
Public: Returns the Hash that represents parsed JSON.
43 44 45 |
# File 'lib/restfolia/resource.rb', line 43 def _json @_json end |
Instance Method Details
#links(rel = nil) ⇒ Object
Public: Read links from Resource. Links are optional. See Resource root doc for details.
rel - Optional String parameter. Filter links by rel attribute.
Returns Empty Array or Array of EntryPoints, if “rel” is informed it returns nil or an instance of EntryPoint.
76 77 78 79 80 81 82 83 |
# File 'lib/restfolia/resource.rb', line 76 def links(rel = nil) @links ||= parse_links(@_json) return nil if @links.empty? && !rel.nil? return @links if @links.empty? || rel.nil? @links.detect { |ep| ep.rel == rel } end |