Skip to content

Instantly share code, notes, and snippets.

@rogerleite
Created April 24, 2012 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogerleite/2483054 to your computer and use it in GitHub Desktop.
Save rogerleite/2483054 to your computer and use it in GitHub Desktop.
Restfolia: Support to HAL
# Run this sample from root project:
# $ ruby samples/support_to_HAL.rb
require "rubygems"
$LOAD_PATH << "lib"
require "restfolia"
# HAL from http://stateless.co/hal_specification.html
json_hal = <<-JSON
{
"_links": {
"self": { "href": "/orders" },
"next": { "href": "/orders?page=2" },
"search": { "href": "/orders?id={order_id}" }
},
"_embedded": {
"order": [
{
"_links": {
"self": { "href": "/orders/123" },
"customer": { "href": "/customer/bob", "title": "Bob Jones <bob@jones.com>" }
},
"total": 30.00,
"currency": "USD",
"status": "shipped",
"placed": "2011-01-16",
"_embedded": {
"basket": {
"_links": {
"self": { "href": "/orders/123/basket" }
},
"items": [
{
"sku": "ABC123",
"quantity": 2,
"price": 9.50
},{
"sku": "GFZ111",
"quantity": 1,
"price": 11
}
]
}
}
},{
"_links": {
"self": { "href": "/orders/124" },
"customer": { "href": "/customer/jen", "title": "Jen Harris <jen@internet.com>" }
},
"total": 20.00,
"currency": "USD",
"status": "processing",
"placed": "2011-01-16",
"_embedded": {
"basket": {
"_links": {
"self": { "href": "/orders/124/basket" }
},
"items": [
{
"sku": "KLM222",
"quantity": 1,
"price": 9.00
},{
"sku": "HHI50",
"quantity": 1,
"price": 11.00
}
]
}
}
}
]
}
}
JSON
json_hal = MultiJson.load(json_hal, :symbolize_keys => true)
resource = Restfolia::Resource.new(json_hal)
puts resource.links.inspect # => []
# Now let's change the way Resource parses links
class Restfolia::Resource
def parse_links(json)
links = json[:_links]
return [] if links.nil?
parsed_links = []
links.each do |rel, link_hash|
href = link_hash[:href]
if rel.nil? || href.nil?
msg = "Invalid hash link, rel: #{rel}, href: #{href}"
raise(RuntimeError, msg, caller)
end
parsed_links << Restfolia::EntryPoint.new(href, rel)
end
parsed_links
end
alias :look_for_resource_original :look_for_resource
def look_for_resource(value)
if value.is_a?(Hash)
embedded = value.delete(:_embedded)
value.merge(embedded) if embedded
end
look_for_resource_original(value)
end
end
resource = Restfolia::Resource.new(json_hal)
puts resource.links.inspect # => [#<Restfolia::EntryPoint ...>]
puts resource.order.inspect
puts "TODO: Support URI Template (http://www.rfc-editor.org/rfc/rfc6570.txt)"
puts "Something like \"resource.links('search', :order => '123').get\""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment