Module: Lotus::Presenter

Included in:
View::Escape::Presenter
Defined in:
lib/lotus/presenter.rb

Overview

Presenter pattern implementation

It delegates to the wrapped object the missing method invocations.

The output of concrete and delegated methods is escaped as XSS prevention.

Examples:

Basic usage

require 'lotus/view'

class Map
  attr_reader :locations

  def initialize(locations)
    @locations = locations
  end

  def location_names
    @locations.join(', ')
  end
end

class MapPresenter
  include Lotus::Presenter

  def count
    locations.count
  end

  def location_names
    super.upcase
  end

  def inspect_object
    @object.inspect
  end
end

map = Map.new(['Rome', 'Boston'])
presenter = MapPresenter.new(map)

# access a map method
puts presenter.locations # => ['Rome', 'Boston']

# access presenter concrete methods
puts presenter.count # => 1

# uses super to access original object implementation
puts presenter.location_names # => 'ROME, BOSTON'

# it has private access to the original object
puts presenter.inspect_object # => #<Map:0x007fdeada0b2f0 @locations=["Rome", "Boston"]>

Escape

require 'lotus/view'

User = Struct.new(:first_name, :last_name)

class UserPresenter
  include Lotus::Presenter

  def full_name
    [first_name, last_name].join(' ')
  end

  def raw_first_name
    _raw first_name
  end
end

first_name = '<script>alert('xss')</script>'

user = User.new(first_name, nil)
presenter = UserPresenter.new(user)

presenter.full_name
  # => "&lt;script&gt;alert(&apos;xss&apos;)&lt;&#x2F;script&gt;"

presenter.raw_full_name
   # => "<script>alert('xss')</script>"

Since:

  • 0.1.0

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &blk) ⇒ Object (protected)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Override Ruby’s method_missing

Since:

  • 0.1.0



110
111
112
113
114
115
116
# File 'lib/lotus/presenter.rb', line 110

def method_missing(m, *args, &blk)
  if @object.respond_to?(m)
    ::Lotus::View::Escape.html(@object.__send__(m, *args, &blk))
  else
    super
  end
end

Class Method Details

.included(base) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Inject escape logic into the given class.

See Also:

Since:

  • 0.4.0



92
93
94
# File 'lib/lotus/presenter.rb', line 92

def self.included(base)
  base.extend ::Lotus::View::Escape
end

Instance Method Details

#initialize(object) ⇒ Object

Initialize the presenter

Parameters:

  • object (Object)

    the object to present

Since:

  • 0.1.0



101
102
103
# File 'lib/lotus/presenter.rb', line 101

def initialize(object)
  @object = object
end