Skip to content

Instantly share code, notes, and snippets.

@plexus
Created October 23, 2014 15:19
Show Gist options
  • Save plexus/14e71beff57b080de455 to your computer and use it in GitHub Desktop.
Save plexus/14e71beff57b080de455 to your computer and use it in GitHub Desktop.
%w[yaks morpher ast].each do |lib|
$:.unshift("/home/arne/github/#{lib}/lib")
$:.unshift("/home/arne/github/#{lib}/#{lib}/lib")
require lib
end
require 'pp'
r=Yaks::Resource.new(
attributes: {name: "Plain grass", type: "grass"},
links: [
Yaks::Resource::Link.new(rel: :self, uri: 'http://api.example.com/plants/7/plain_grass')
]
)
include Morpher::NodeHelpers
ast = s(:block,
s(:dump_attribute_hash, s(:param, Yaks::Resource)),
s(:key_fetch, :attributes))
evaluator = Morpher.compile(ast)
result = evaluator.call(r) # => {:name=>"Plain grass", :type=>"grass"}
# So far so good, but now I need to transform r.links into a specific
# format, and put it under the :_links key. How would I do that with
# Morpher?
link_hash = r.links.reduce({}) do |hsh, l|
hsh[l.rel] = { href: l.uri }
end
result = result.merge(_links: link_hash)
pp result
# >> {:name=>"Plain grass",
# >> :type=>"grass",
# >> :_links=>{:href=>"http://api.example.com/plants/7/plain_grass"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment