Skip to content

Instantly share code, notes, and snippets.

@cflipse
Last active February 4, 2017 10:29
Show Gist options
  • Save cflipse/d7d727e7985de84fef2d to your computer and use it in GitHub Desktop.
Save cflipse/d7d727e7985de84fef2d to your computer and use it in GitHub Desktop.
require 'rom/memory'
class BlenderRelation < ROM::Relation[:memory]
repository :memory
register_as :blender
forward :join
end
class PostWithTagsMapper < ROM::Mapper
relation :blender
register_as :with_tags
model PostWithTag
end
class TagRelation < ROM::Relation[:sql]
dataset :tags
one_to_many :taggings, key: :tag_id
def for_posts
association_join(:taggings)
.where(taggings__taggable_type: 'Post',
taggings__taggable_id: Array(announcements).map{|a| a[:id] })
.select(:name, :taggable_id)
end
end
class TagListMapper < ROM::Mapper
attribute :id, from: :taggable_id
group :tags do
attribute :name
end
end
class TagBlender
attr_reader :rom
def initialize(rom = ROM.env)
@rom = rom
end
def with_tags(posts, tag_list)
rom.relation(:blender).join(posts.to_a, (posts >> tag_list).to_a)
end
end
blender = TagBlender.new(ROM.env)
posts = ROM.env.relation(:posts).page(2)
tags = ROM.env.relation(:tags).as(:tag_list)
blender.with_tags(posts, tags).as(:with_tag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment