Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Pull this out into a class

boy was there a lot of complexity in that single method
  • Loading branch information...
commit dd29c8e40ef584d6f59ead1009d67c3a64067c9c 1 parent 617f354
Lucas Parry authored
5 lib/flickr_offline_gallery.rb
View
@@ -53,11 +53,6 @@ def self.render_photo_page(photo)
::FlickrOfflineGallery.verbose_puts "Rendered #{photo.local_html_path}"
end
- def self.render_erb(template, locals)
- full_template_path = File.expand_path("../../erb/#{template}.html.erb",__FILE__)
- raise "unknown template: #{full_template_path}" unless File.exist?(full_template_path)
- ERB.new(File.read(full_template_path)).result(OpenStruct.new(locals).instance_eval { binding })
- end
def self.verbose_puts(string)
::FlickrOfflineGallery.verbose_puts(string) if ENV["VERBOSE"]
24 lib/flickr_offline_gallery/template_renderer.rb
View
@@ -0,0 +1,24 @@
+module FlickrOfflineGallery
+ class TemplateRenderer
+ def initialize(template)
+ @template = template
+ end
+
+ def template_path
+ File.expand_path("../../../erb/#{@template}.html.erb",__FILE__)
+ end
+
+ def template_directory
+ File.expand_path("../../../erb/", __FILE__)
+ end
+
+ def template_contents
+ raise "Unknown template: #{template_path}" unless File.exist?(template_path)
+ @template_content ||= File.read(template_path)
+ end
+
+ def render(locals)
+ ERB.new(template_contents).result(OpenStruct.new(locals).instance_eval { binding })
+ end
+ end
+end
40 spec/flickr_offline_gallery/template_renderer_spec.rb
View
@@ -0,0 +1,40 @@
+require 'spec_helper'
+module FlickrOfflineGallery
+ describe TemplateRenderer do
+ subject(:renderer) { described_class.new(template_name) }
+ let(:template_name) { "cool_template" }
+ let(:template_contents) do <<-ERB
+ This is <%= variable %>!
+ ERB
+ end
+
+ it "should know where templates live" do
+ renderer.template_directory.should == File.join(GEM_ROOT, "erb")
+ end
+
+ it "should know what template to render" do
+ renderer.template_path.should == File.join(renderer.template_directory, "#{template_name}.html.erb")
+ end
+
+ it "should raise an error if the template is missing" do
+ File.should_receive(:exist?).and_return(false)
+ expect {
+ renderer.template_contents
+ }.to raise_error("Unknown template: #{renderer.template_path}")
+ end
+
+ it "should read in the correct template" do
+ File.stub(:exist? => true)
+ File.stub(:read => template_contents)
+ renderer.template_contents.should == template_contents
+ end
+
+ it "should render the template with the local variables" do
+ File.stub(:exist? => true)
+ File.stub(:read => template_contents)
+
+ renderer.render(:variable => "awesome").strip.should == "This is awesome!"
+ renderer.render(:variable => "crappy").strip.should == "This is crappy!"
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.