357da3f3ee71d2fb88495f239e8b5b22

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?

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 !

F6eddf2f983d23c2d031e407852625e9

jamesgolick

July 1, 2008, July 01, 2008 14:30, permalink

No rating. Login to rate!

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)
357da3f3ee71d2fb88495f239e8b5b22

calebf

July 1, 2008, July 01, 2008 16:56, permalink

No rating. Login to rate!

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.
F22c48808ddcb56564889bb39f755717

elliottcable

July 1, 2008, July 01, 2008 19:51, permalink

No rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel