Skip to content

Instantly share code, notes, and snippets.

@gotar
Created August 12, 2015 17:22
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 gotar/4f1d2dfcf8fb2750bc25 to your computer and use it in GitHub Desktop.
Save gotar/4f1d2dfcf8fb2750bc25 to your computer and use it in GitHub Desktop.
Mapping raw tuple to jsonapi using rom-mapper and yaks
require 'anima'
require 'rom-mapper'
require 'yaks'
class User
include Anima.new(:id, :first_name, :last_name, :posts)
end
class Post
include Anima.new(:id, :title)
end
class UserMapper < ROM::Mapper
reject_keys true
model User
attribute :id
attribute :first_name, from: :name
attribute :last_name
group :posts do
model Post
prefix :post
attribute :id
attribute :title
end
end
module JsonAPI
class UserMapper < Yaks::Mapper
attributes :id, :first_name, :last_name
has_many :posts
end
class PostMapper < Yaks::Mapper
attributes :id, :title
end
end
struct = [{
id: 1,
name: 'Jane',
last_name: 'Doe',
post_id: 1,
user_id: 1,
post_title: 'Foo'
}, {
id: 1,
name: 'Jane',
last_name: 'Doe',
post_id: 2,
user_id: 1,
post_title: 'Bar'
}]
yaks = Yaks.new do
# default_format :hal
default_format :json_api
mapper_namespace JsonAPI
end
print yaks.call(UserMapper.build.call(struct))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment