Posts Tagged ‘erb’

Markup, CSS and Helper cataloging (Part deux)

Monday, June 25th, 2007

I should be using ERB instead of eval. But because you can’t use <% inside a string block in your view (that I can figure out; <<EOF didn’t seem to be working in a template). And if you don’t want to specify the code string in your controller you can use [% ... %]. Here is the source I am using for our code helper now:

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
  def erb_code(code) 
    ERB.new(code).result(binding)    
  end
  
  def render_code(code, options = {}) 
    %{ <pre class="helper">\n<code class="ruby">\n#{h(code)}\n</code>\n</pre> }
  end
  
  def render_markup(html)
    doc = REXML::Document.new(html)
    markup = ""
    doc.write(markup, 2)
    
    %{ <pre class="markup">\n<code class="html">\n#{h(markup)}\n</code>\n</pre>\n }    
  end
  
  def render_eval(html)
    %{ <div class="eval">#{html}</div> }
  end
    
  def code_helper(code)
    code.gsub!(/\[%/, "<%").gsub!(/%\]/, "%>")    
    html = erb_code(code)
    render_code(code) + render_markup(html) + render_eval(html)
  end

Then you can do things like:


  <%= code_helper %{ [%= rating_field(:rating, :effectiveness) %] } %>

and you could also dump it in a helper:

1
2
3
4
5
6
7
8
9
def code_rating_form_field 
  <<-EOF
   <% form_for :rating, @rating2 do |f| %>
     <%= f.rating_field(:effectiveness) %>
   <% end %>
  EOF
end

  // And in your view: <%= code_helper(code_rating_form_field) %>