Class: Resubject::Presenter

Inherits:
SimpleDelegator
  • Object
show all
Extended by:
Extensions::TemplateMethods
Defined in:
lib/resubject/rails.rb,
lib/resubject/presenter.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Extensions::TemplateMethods

currency, date_format, percentage, time_ago

Constructor Details

#initialize(model, context = nil) ⇒ Presenter

Create a new presenter

Examples:


PostPresenter.new(post)
PostPresenter.new(post, view_context)

Parameters:

  • model

    any object that can be presented

  • context (defaults to: nil)

    a context of HTML helpers



21
22
23
24
# File 'lib/resubject/presenter.rb', line 21

def initialize(model, context = nil)
  @context = context
  super(model)
end

Instance Attribute Details

#contextObject (readonly) Also known as: template

the HTML helpers context



8
9
10
# File 'lib/resubject/presenter.rb', line 8

def context
  @context
end

Class Method Details

.all(collection, context = nil) ⇒ Array<Presenter>

Builds a collection of presenters given an array of objects

Examples:


boxes = [box1, box2, box3]
BoxPresenter.all boxes
# => [<BoxPresenter>, <BoxPresenter>, <BoxPresenter>]

PostPresenter.all Post.all
# => [<PostPresenter>, ...]

Parameters:

  • collection (Array<Object>)
  • context (defaults to: nil)

    the HTML helpers context

Returns:

  • (Array<Presenter>)

    instances of a presenter for each item in the collection



43
44
45
# File 'lib/resubject/presenter.rb', line 43

def self.all(collection, context = nil)
  collection.map { |c| new(c, context) }
end

.presents(attribute, *presenters) ⇒ Object

Generates a instance method with the attribute presented

Examples:


class BoxPresenter < Resubject::Presenter
  presents :name
  # or presents :name, CustomPresenter
end

BoxPresenter.new(box).name   # => <NamePresenter>

When the parent method is nil, it returns nil


box = BoxPresenter.new Box.new(name: nil)
box.name
# => nil


81
82
83
84
85
# File 'lib/resubject/presenter.rb', line 81

def self.presents(attribute, *presenters)
  define_method attribute do
    present to_model.send(attribute), *presenters
  end
end

Instance Method Details

#present(objects, *presenters) ⇒ Presenter+

Creates a presenter from object or collection of objects

Examples:


present box                          # => <BoxPresenter>
present [box, box]                   # => [<BoxPresenter>, <BoxPresenter>]
present [box, box], CustomPresenter  # => <CustomPresenter>

Parameters:

  • objects (Object, Array<Object>)

    objects to be instantiated with related presenter

  • presenters (Presenter)

    one or multiple presenters

Returns:

See Also:



60
61
62
# File 'lib/resubject/presenter.rb', line 60

def present(objects, *presenters)
  Builder.present objects, context, *presenters
end