From lib/sinatra.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def use_in_file_templates! require 'stringio' templates = Hash.new templates = IO.read(caller.first.split(':').first).split('__FILE__').last data = StringIO.new(templates) current_template = nil data.each do |line| if line =~ /^@@\s?(.*)/ current_template = $1.to_sym Sinatra.application.templates[current_template] = '' elsif current_template Sinatra.application.templates[current_template] << line end end end
Refactorings
No refactoring yet !
jamesgolick
July 1, 2008, July 01, 2008 14:30, permalink
Maybe I'm missing what you're trying to do. But, why not just use built-in ERB?
1
ERB.new(File.read(path_to_template)).result(binding)
calebf
July 1, 2008, July 01, 2008 16:56, permalink
Oops, I forgot to mention that I prefer using Haml/Sass than ERB. Here's what I'm trying to accomplish.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#!/usr/bin/env ruby def use_in_file_templates! require 'stringio' templates = Hash.new templates = IO.read(caller.first.split(':').first).split('__FILE__').last data = StringIO.new(templates) current_template = nil data.each do |line| if line =~ /^@@\s?(.*)/ current_template = $1.to_sym templates[current_template] = '' elsif current_template Stemplates[current_template] << line end end end if __FILE__ == $0 File.open('index.html', 'w') do |file| puts.file Haml::Engine.new(templates[:index]).render(binding) end end __END__ @@ index %html %head $title %body % Hello, World.
elliottcable
July 1, 2008, July 01, 2008 19:51, permalink
Haven't got any code, but why use __END__? Why not just heredocs? (See below)
Also, even that way, no need to place to IO.read(caller.first.split(':').first).split('__FILE__').last - the global constant 'DATA' is set to whatever is after __END__ in a script.
1 2 3 4 5 6 7 8
templates = <<END @@ index %html %head $title %body % Hello, World. END
This method was taken from Sinatra.
http://github.com/bmizerany/sinatra/tree/master/lib/sinatra.rb#L1368
I'm wanting to use templates in a one-file script I'm working on so I can generate HTML/CSS. Does anyone have any tips on how to make it faster/slimmer/better?