Skip to content

Instantly share code, notes, and snippets.

@damaon
Last active February 26, 2016 10:23
Show Gist options
  • Save damaon/183d099ec11e95bf622e to your computer and use it in GitHub Desktop.
Save damaon/183d099ec11e95bf622e to your computer and use it in GitHub Desktop.
class LazyRepresenter
def initialize
@getters = []
end
def call(object)
@getters.reduce({}) do |hash, getter|
hash.merge(getter.call(object))
end
end
def represent(&getter)
fail "No getter block provided!" unless block_given?
@getters << getter
end
end
# Przyklady:
id_and_name_representer = LazyRepresenter.new
.represent do |object|
{ id: object.id }
end
.represent do |object|
{ name: object.name }
end
lr.call(User.first)
lr.call(Event.first)
simple_tags_representation = lr.new.represent do |tag|
{id: tag.id, name: tag.name}
end
some_group_presenter =
V3::GroupRepresenter.new
.basic
.with_tags(simple_tags_representation)
.with_participants
.with_participants_count
group_presenter.call(some_group)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment