Archives For June

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) %>

At work, we have a catalog of markup and CSS and any ruby helpers. I wrote this helper for it which takes a code string and spits it out, evals it, and provides the eval’ed html wrapped and indented. The code-highligher does all the highlighting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def code_helper(code) 
   help_block = %{ <pre class="helper">n<code class="ruby">n<%= #{h(code)} %>n</code>n</pre> }
    
    result = instance_eval code, "generated code (#{__FILE__}:#{__LINE__})"
    result_block = %{ <div class="eval">#{result}</div> }
    
    doc = REXML::Document.new(result)
    markup = ""
    doc.write(markup, 2)
    
    markup_block = %{ <pre class="markup">n<code class="html">n#{h(markup)}n</code>n</pre>n }
    
    %{ #{help_block} #{markup_block} #{result_block} }
end

And usage:


<%= code_helper %{ will_paginate(@count, @per_page, @page_num, { :extra_param => "extra1" }) } %>

would display the code, the (escaped) markup that it generates, and then the straight up html.

I was looking at the NetworkFacade api, (check it out at network-facade.rubyforge.org) and noticed:

1
2
3
  # Or declate the Foo class and set an uri
  class Foo < NetworkFacade::Client 'nf://localhost:5042'
  end

where the uri is defined with the Foo declaration. Foo descends from the class returned by the Client class method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module NetworkFacade

    def self.Client(uri = nil)
        TCP::Client.uri = uri
        TCP::Client
    end

    class Client < TCP::Client
    end


    class Server < TCP::Server
    end

end

That is cool.