0.01
No commit activity in last 3 years
No release in over 3 years
A simple Presenter for use with arbitrary templating languages
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.1.0
>= 0
~> 1.8.3
~> 3.12
 Project Readme

A modest presenter¶ ↑

modest_presenter is a base class for objects that you want to act as a Presenter for an arbitrary templating language. It should be fairly templating language agnostic–though the supplied example works in ERB.

I extracted this from a couple of projects where I’ve found myself writing this very same thing.

Example¶ ↑

Person = Struct.new(:first_name, :last_name, :age)
InsanePerson = Class.new(Person)
Nerd = Class.new(Person)

evan = Nerd.new("Evan", "Light", 38)
ed = Nerd.new("Ed", "Kim", 27)
# Seems a bit generous calling this guy a Person
w = InsanePerson.new("George W.", "Bush", 66)

class PersonPresenter < ModestPresenters::ModestPresenter
  def name
    "#{first_name} #{last_name}"
  end

  def title
  end
end

class NerdPresenter < PersonPresenter
  def name
    "#{super} is a nerd."
  end
end

class InsanePersonPresenter < PersonPresenter
  def name
    "#{super} wastes oxygen better used by nerds."
  end

  def title
    "President "
  end
end

def present(model, context, &block)
  Object.const_get("#{model.class}Presenter")
        .new(model, context)
        .present(&block)
end

people = [evan, ed, w]

ERB_TEMPLATE = <<-ERB
  <ul>
    <% people.each do |person| %>
      <% present(person, self) do %>
        <li>
          <%= title %><%= name %>
        </li>
      <% end %>
    <% end %>
  </ul>
  <p>Yes, only insane people are President</p>
ERB

require 'erb'
puts ERB.new(ERB_TEMPLATE).result(binding)

# OUTPUTS:
# <ul>
#   <li>
#     Evan Light is a nerd.
#   </li>
#   <li>
#     Ed Kim is a nerd.
#   </li>
#   <li>
#     President George W. Bush wastes oxygen better used by nerds.
#   </li>
# </ul>
# <p>Yes, only insane people are President</p>

Copyright © 2012 Evan Light. MIT Licensed.