Module: Livery::Controller
- Defined in:
- lib/livery/controller.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#present(hsh) ⇒ Object
Pass presenters to the view.
Class Method Details
.included(base) ⇒ Object
3 4 5 |
# File 'lib/livery/controller.rb', line 3 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#present(hsh) ⇒ Object
Pass presenters to the view. Must be used with the class method use_presenters!
.
hsh
A hash whose keys define the names of variables used in the view, and values the objects that will be presented. Each object must either be a presenter, or have a corresponding presenter class; e.g., a Post
model should have a PostPresenter
class. If an enumerable is passed, each object within is mapped over. An exception is raised otherwise.
Examples
present
will wrap non-presenter objects with their presenter classes. Here, the Post
object is wrapped with a PostPresenter
:
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
include Livery::Controller
use_presenters!
def show
post = Post.find(params[:id])
present(post: post)
end
end
This is equivalent to (without using use_presenters!
):
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def show
post = Post.find(params[:id])
@post = PostPresenter.new(post)
end
end
It can handle enumerables:
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
include Livery::Controller
use_presenters!
def index
posts = Post.all
# Equivalent to:
# @posts = posts.map { |post| PostPresenter.new(post) }
present(posts: posts)
end
end
And presenter objects will not be re-wrapped:
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
include Livery::Controller
use_presenters!
def show
post_presenter = PostPresenter.new(current_user.post)
# Equivalent to:
# @post = post_presenter
present(post: post_presenter)
end
end
Presenter classes are found via a simple naming convention; an object of some class Model
will be wrapped with a ModelPresenter
. If a corresponding presenter class is not found, an error is raised.
113 114 115 116 117 118 |
# File 'lib/livery/controller.rb', line 113 def present(hsh) @_presenters ||= {} hsh.each_with_object(@_presenters) do |(k, v), acc| acc[k] = Livery::Presenter.to_presenter(v) end end |