Permalink
Browse files

Rendering Context (#5)

  • Loading branch information...
inescoelho authored and rosafaria committed Aug 19, 2015
1 parent 71148dc commit acfe3fa54a1901ca0b9f8c192559e156651ccf8e
@@ -4,17 +4,35 @@ module Mailer
#
# @since 0.1.0
module Rendering
# Render a single template with the specified format.
#
# @return [String] the output of the rendering process.
#
# @since 0.1.0
def render(format)
templates
@templates[format].render
def self.extended(base)
base.class_eval do
include InstanceMethods
end
end
module InstanceMethods
# Initialize a mailer
#
# @param locals [Hash] a set of objects available during the rendering process.
#
# @since 0.1.0
def initialize(locals = {})
@locals = locals
@scope = self
end
# Render a single template with the specified format.
#
# @param format [symbol] template's format
#
# @return [String] the output of the rendering process.
#
# @since 0.1.0
def render(format)
self.class.templates
self.class.templates[format].render @scope, @locals
end
end
end
end
end
@@ -12,16 +12,15 @@ def initialize(template)
# Render the template within the context of the given scope.
#
# @param scope [Lotus::Mailer::Scope] the rendering scope
# @param scope [Class] the rendering scope
# @param locals [Hash] set of objects passed to the constructor
#
# @return [String] the output of the rendering process
#
# @api private
# @since 0.1.0
#
# @see Lotus::Mailer::Scope
def render
@_template.render
def render(scope = Object.new, locals = {})
@_template.render(scope, locals)
end
# Get the path to the template
View
@@ -46,3 +46,19 @@ class ArrayMailer
to ["noreply1@example.com", "noreply2@example.com"]
end
class WelcomeMailer
include Lotus::Mailer
def greeting
"Ahoy"
end
end
class User
def initialize(name)
@name = name
end
attr_reader :name
end
@@ -0,0 +1 @@
Hello <%= user.name %>,
@@ -0,0 +1 @@
<%= greeting %>!
@@ -0,0 +1 @@
<%= greeting %>!
View
@@ -4,10 +4,22 @@
describe Lotus::Mailer do
describe 'render' do
it 'renders a single template with a given format' do
InvoiceMailer.render(:html).must_include %(<h1>Invoice template</h1>)
LazyMailer.render(:html).must_include %(Hello World)
LazyMailer.render(:haml).must_include %(This is a haml template)
LazyMailer.render(:txt).must_include %(This is a txt template)
InvoiceMailer.new.render(:html).must_include %(<h1>Invoice template</h1>)
LazyMailer.new.render(:html).must_include %(Hello World)
LazyMailer.new.render(:haml).must_include %(This is a haml template)
LazyMailer.new.render(:txt).must_include %(This is a txt template)
end
it 'renders a single template with context' do
WelcomeMailer.new.render(:html).must_include %(Ahoy)
WelcomeMailer.new.render(:txt).must_include %(Ahoy)
end
it 'renders a single template with locals' do
luca = User.new('Luca')
mailer = RenderMailer.new(user: luca)
mailer.render(:html).must_include %(Luca)
end
end
end

0 comments on commit acfe3fa

Please sign in to comment.