Class: CollectionPresenter

Inherits:
Object
  • Object
show all
Defined in:
lib/collection_presenter.rb

Direct Known Subclasses

Renalware::Letters::ContactsPresenter

Instance Method Summary collapse

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, *options)
  @original_collection = original_collection
  presenter_class, view_context = parse_options(options, 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

Returns:

  • (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_aObject



34
35
36
# File 'lib/collection_presenter.rb', line 34

def to_a
  @decorated_collection.to_a
end

#to_aryObject



30
31
32
# File 'lib/collection_presenter.rb', line 30

def to_ary
  @decorated_collection.to_a
end

#to_json(*_args) ⇒ Object



40
41
42
# File 'lib/collection_presenter.rb', line 40

def to_json(*_args)
  @decorated_collection.map(&:to_hash).to_json
end