Class: Curlybars::Presenter

Inherits:
Object
  • Object
show all
Extended by:
MethodWhitelist
Defined in:
lib/curlybars/presenter.rb

Overview

A base class that can be subclassed by concrete presenters.

A Curlybars presenter is responsible for delivering data to templates, in the form of simple strings. Each public instance method on the presenter class can be referenced in a template. When a template is evaluated with a presenter, the referenced methods will be called with no arguments, and the returned strings inserted in place of the components in the template.

Note that strings that are not HTML safe will be escaped.

A presenter is always instantiated with a context to which it delegates unknown messages, usually an instance of ActionView::Base provided by Rails. See Curlybars::TemplateHandler for a typical use.

Examples

class BlogPresenter < Curlybars::Presenter
  presents :post
  allow_methods :title, :body, :author

  def title
    @post.title
  end

  def body
    markdown(@post.body)
  end

  def author
    @post.author.full_name
  end
end

presenter = BlogPresenter.new(context, post: post)
presenter.author #=> "Jackie Chan"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from MethodWhitelist

allow_methods, extended

Constructor Details

#initialize(context, options = {}) ⇒ Presenter

Initializes the presenter with the given context and options.

context - An ActionView::Base context. options - A Hash of options given to the presenter.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/curlybars/presenter.rb', line 48

def initialize(context, options = {})
  @_context = context
  options.stringify_keys!

  self.class.presented_names.each do |name|
    value = options.fetch(name) do
      default_values.fetch(name) do
        block = default_blocks.fetch(name) do
          raise ArgumentError.new("required identifier `#{name}` missing")
        end

        instance_exec(name, &block)
      end
    end

    instance_variable_set("@#{name}", value)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, **kwargs, &block) ⇒ Object (private)

Delegates private method calls to the current view context.

The view context, an instance of ActionView::Base, is set by Rails.



279
280
281
# File 'lib/curlybars/presenter.rb', line 279

def method_missing(method, *args, **kwargs, &block)
  @_context.public_send(method, *args, **kwargs, &block)
end

Class Method Details

.cache_keyObject

The cache key for the presenter class. Includes all dependencies as well.

Returns a String cache key.



216
217
218
# File 'lib/curlybars/presenter.rb', line 216

def cache_key
  @cache_key ||= compute_cache_key
end

.dependenciesObject

The set of view paths that the presenter depends on.

Examples

class Posts::ShowPresenter < Curlybars::Presenter
  version 2
  depends_on 'posts/comment', 'posts/comment_form'
end

Posts::ShowPresenter.dependencies
#=> ['posts/comment', 'posts/comment_form']

Returns a Set of String view paths.



183
184
185
186
187
188
189
# File 'lib/curlybars/presenter.rb', line 183

def dependencies
  # The base presenter doesn't have any dependencies.
  return SortedSet.new if self == Curlybars::Presenter

  @dependencies ||= SortedSet.new
  @dependencies.union(superclass.dependencies)
end

.depends_on(*dependencies) ⇒ Object

Indicate that the presenter depends a list of other views.

deps - A list of String view paths that the presenter depends on.

Returns nothing.



196
197
198
199
# File 'lib/curlybars/presenter.rb', line 196

def depends_on(*dependencies)
  @dependencies ||= SortedSet.new
  @dependencies.merge(dependencies)
end

.presenter_for_path(path) ⇒ Object

Returns the presenter class for the given path.

path - The String path of a template.

Returns the Class or nil if the constant cannot be found.



159
160
161
162
163
164
165
166
167
168
# File 'lib/curlybars/presenter.rb', line 159

def presenter_for_path(path)
  name_space = Curlybars.configuration.presenters_namespace
  name_spaced_path = File.join(name_space, path)
  full_class_name = presenter_name_for_path(name_spaced_path)
  begin
    full_class_name.constantize
  rescue NameError
    nil
  end
end

.presenter_name_for_path(path) ⇒ Object

The name of the presenter class for a given view path.

path - The String path of a view.

Examples

Curlybars::TemplateHandler.presenter_name_for_path("foo/bar")
#=> "Foo::BarPresenter"

Returns the String name of the matching presenter class.



150
151
152
# File 'lib/curlybars/presenter.rb', line 150

def presenter_name_for_path(path)
  "#{path}_presenter".camelize
end

.version(version = nil) ⇒ Object

Get or set the version of the presenter.

version - The Integer version that should be set. If nil, no version

is set.

Returns the current Integer version of the presenter.



207
208
209
210
# File 'lib/curlybars/presenter.rb', line 207

def version(version = nil)
  @version = version if version.present?
  @version || 0
end

Instance Method Details

#cache_durationObject

The duration that the view should be cached for. Only relevant if ‘#cache_key` returns a non nil value.

If nil, the view will not have an expiration time set. See also ‘#cache_options` for a more flexible way to set cache options.

Examples

def cache_duration
  10.minutes
end

Returns the Fixnum duration of the cache item, in seconds, or nil if no

duration should be set.


135
136
137
# File 'lib/curlybars/presenter.rb', line 135

def cache_duration
  nil
end

#cache_keyObject

The key that should be used to cache the view.

Unless ‘#cache_key` returns nil, the result of rendering the template that the presenter supports will be cached. The return value will be part of the final cache key, along with a digest of the template itself.

Any object can be used as a cache key, so long as it

  • is a String,

  • responds to #cache_key itself, or

  • is an Array or a Hash whose items themselves fit either of these criteria.

Returns the cache key Object or nil if no caching should be performed.



102
103
104
# File 'lib/curlybars/presenter.rb', line 102

def cache_key
  nil
end

#cache_optionsObject

The options that should be passed to the cache backend when caching the view. The exact options may vary depending on the backend you’re using.

The most common option is ‘:expires_in`, which controls the duration of time that the cached view should be considered fresh. Because it’s so common, you can set that option simply by defining ‘#cache_duration`.

Note: if you set the ‘:expires_in` option through this method, the `#cache_duration` value will be ignored.

Returns a Hash.



117
118
119
# File 'lib/curlybars/presenter.rb', line 117

def cache_options
  {}
end

#setup!Object

Sets up the view.

Override this method in your presenter in order to do setup before the template is rendered. One use case is to call ‘content_for` in order to inject content into other templates, e.g. a layout.

Examples

class Posts::ShowPresenter < Curlybars::Presenter
  presents :post

  def setup!
    content_for :page_title, @post.title
  end
end

Returns nothing.



84
85
86
# File 'lib/curlybars/presenter.rb', line 84

def setup!
  # Does nothing.
end