James Gray
12/10/2005 3:17:00 AM
On Dec 9, 2005, at 8:58 PM, Larry White wrote:
> i want to do a series of replacements on a file in two passes - one at
> 'compile time', one at runtime. For a simple example, if i'm
> creating 2 copies of a dynamic web page - one for each of two tables -
> i would replace references to the table at 'compile time' and display
> the particular values of a record from the table at runtime.It might
> look like this
>
> <body>
> <% for column in #{table_name}.display_columns %>
> <th class="th1"><%= column.name %></th>
> <% end %>
> </body>
>
> So i want to replace #{table_name} in the first pass and the rest of
> the stuff in the second pass. Since there could be a large number of
> replacements at either time, I thought a solution using erb with
> different tag sets might be reasonably maintainable.
My example pretty much works for that, with minor tweaks:
>> template = <<'END'
<body>
<% for column in #{table_name}.display_columns %>
<th class="th1"><%= column.name %></th>
<% end %>
</body>
END
=> "<body>\n <% for column in \#{table_name}.display_columns %>\n
<th class=\"th1\"><%= column.name %></th>\n <% end %>\n</body>\n"
>> table = Object.new
=> #<Object:0x321188>
>> class << table
>> def display_columns
>> names = %w{col_one col_two col_three}
>> end
>> end
=> nil
>> class String
>> def name; self end
>> end
=> nil
>> table_name = "table"
=> "table"
>> template = eval(%Q{"#{template.gsub('"', '\\"')}"}, binding)
=> "<body>\n <% for column in table.display_columns %>\n <th
class=\"th1\"><%= column.name %></th>\n <% end %>\n</body>\n"
>> require "erb"
=> true
>> ERB.new(template).result(binding)
=> "<body>\n \n <th class=\"th1\">col_one</th>\n \n <th class=
\"th1\">col_two</th>\n \n <th class=\"th1\">col_three</th>\n \n</
body>\n"
I wouldn't do it though. What's the harm of sticking the table name
in a variable each tim before you run the template through ERb?
Heck, run the templates like this:
ERB.new(template).result(table.instance_eval { binding })
And then just call display_columns directly.
Hope the helps.
James Edward Gray II