Last active
August 29, 2015 13:57
-
-
Save jodosha/9601524 to your computer and use it in GitHub Desktop.
A Lotus::View sneak peek: Lotus::Presenter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Lotus | |
module Presenter | |
def initialize(object) | |
@object = object | |
end | |
protected | |
def method_missing(m, *args, &blk) | |
if @object.respond_to?(m) | |
@object.__send__ m, *args, &blk | |
else | |
super | |
end | |
end | |
end | |
end | |
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"]> |
@ cheapRoc The way I use presenters are to instantiate them in the view.
require 'lotus/view'
module Dashboard
class Index
include Lotus::View
def map
MapPresenter.new(...)
end
end
end
and use in the template:
<p><%= map.location_names %></p>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Beautiful! You've actually built the project I've never gotten to finish, a Ruby MVP framework of OO purity.
I'm hoping you're doing what I'd do, only allow presenter objects to be locally accessible to template rendering scope which would remove Rails ugly Controller "helper" mismatch. If only my current project was built with this. :drool: