class Halibut::Adapter::JSON::ResourceExtractor
ResourceExtractor
is responsible for deserializing an HAL resource from the JSON
representation.
extractor = ResourceExtractor.new({}) # => #<Halibut::Adapter::JSON::ResourceExtractor:0x007f8adb92f2a8 extractor.resource # => #<Halibut::HAL::Resource:0x007f8add058fb0
Public Class Methods
new(json)
click to toggle source
Straight-forward, just pass in the JSON
string you want to extract the resource from.
json = '{"_links":{"self":{"href":"http://example.com"}}}' ResourceExtractor.new('{}')
# File lib/halibut/adapter/json.rb, line 65 def initialize(json) @halibut = Halibut::Core::Resource.new @json = MultiJson.load(json) extract_properties extract_links extract_embedded_resources end
Public Instance Methods
resource()
click to toggle source
This method should be called when the the resource extracted is needed
# File lib/halibut/adapter/json.rb, line 75 def resource @halibut end
Private Instance Methods
extract_embedded_resources()
click to toggle source
# File lib/halibut/adapter/json.rb, line 102 def extract_embedded_resources resources = @json.fetch('_embedded', []) resources.each do |relation,values| embeds = ([] << values).flatten embeds.map {|embed| MultiJson.dump embed } .map {|embed| Halibut::Adapter::JSON.parse embed } .each {|embed| @halibut.embed_resource(relation, embed) } end end
extract_links()
click to toggle source
# File lib/halibut/adapter/json.rb, line 89 def extract_links links = @json.fetch('_links', []) links.each do |relation,values| link = ([] << values).flatten link.each do |attrs| href = attrs.delete 'href' @halibut.add_link(relation, href, attrs) end end end
extract_properties()
click to toggle source
# File lib/halibut/adapter/json.rb, line 80 def extract_properties properties = @json.reject {|k,v| k == '_links' } .reject {|k,v| k == '_embedded' } properties.each_pair do |property, value| @halibut.set_property(property, value) end end