Class: CollectionPresenter
- Inherits:
-
Object
- Object
- CollectionPresenter
- Defined in:
- lib/collection_presenter.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#initialize(original_collection, *options) ⇒ CollectionPresenter
constructor
Initialises an enumerable collection of initialised presenters for the corresponding original_collection of objects, for example a collection of Letter objects.
- #method_missing(method, *args, &block) ⇒ Object
- #respond_to?(method) ⇒ Boolean
- #to_a ⇒ Object
- #to_ary ⇒ Object
- #to_json ⇒ Object
Constructor Details
#initialize(original_collection, *options) ⇒ CollectionPresenter
Initialises an enumerable collection of initialised presenters for the corresponding original_collection of objects, for example a collection of Letter objects.
The *options catches:
-
presenter_class, optional
-
view_context, optional
It is written this way because I needed to add an optional view_context (which some Presenters may need) without breaking existing usage.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/collection_presenter.rb', line 14 def initialize(original_collection, *) @original_collection = original_collection presenter_class, view_context = (, block_given?) @decorated_collection ||= Enumerator.new do |yielder| original_collection.each do |element| presenter = if block_given? yield(element) else build_presenter(presenter_class, element, view_context) end yielder.yield(presenter) end end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/collection_presenter.rb', line 44 def method_missing(method, *args, &block) if @decorated_collection.respond_to?(method) @decorated_collection.public_send(method, *args, &block) else @original_collection.public_send(method, *args, &block) end end |
Instance Method Details
#respond_to?(method) ⇒ Boolean
52 53 54 |
# File 'lib/collection_presenter.rb', line 52 def respond_to?(method) @decorated_collection.respond_to?(method) || @original_collection.respond_to?(method) end |
#to_a ⇒ Object
34 35 36 |
# File 'lib/collection_presenter.rb', line 34 def to_a @decorated_collection.to_a end |
#to_ary ⇒ Object
30 31 32 |
# File 'lib/collection_presenter.rb', line 30 def to_ary @decorated_collection.to_a end |
#to_json ⇒ Object
40 41 42 |
# File 'lib/collection_presenter.rb', line 40 def to_json @decorated_collection.map(&:to_hash).to_json end |