Created
August 12, 2015 17:22
-
-
Save gotar/4f1d2dfcf8fb2750bc25 to your computer and use it in GitHub Desktop.
Mapping raw tuple to jsonapi using rom-mapper and yaks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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