Last active
February 26, 2016 10:23
-
-
Save damaon/183d099ec11e95bf622e to your computer and use it in GitHub Desktop.
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
| 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