Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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