views:

24

answers:

1

Hi, everyone.

In my rails application my models have a to_html method. This method is called in one of the views so the model's attributes can be displayed properly regardless of their classes (because all of my classes implement that method)

That is a neat solution, but one thing bugs me. I need to write this html code inside the double quotes (as strings) and eventually escape the other double quotes that I use in my html code manually.

I'd like to be able to work with rhtml files instead: read them, evaluate the eventual ruby code in it and return the result as a string with the necessary escaped characters. I'll give you an example:

The following code:

<label for="blabla"> <%= ruby_variable.name %> </label>

when processed should return me:

"<label for=\"blabla\"> name </label>"

Does anyone know something that already does that or could point me in the good direction? I was thinking of writing a piece of code that does that myself. But if something is already out there working, I'd me happy to use it.

Thanks

A: 

You can use ERB directly outside of your views if you want. For example:

require 'erb'
v = 'testing123'
output = ERB.new('<label><%= v %></label>').result(binding)

will return

<label>testing123</label>

That said, I'm not entirely sure why you'd want a to_html method in your model classes as it breaks the separation between model, view and controller that Rails so nicely provides. I'll leave that down to you though!

Shadwell
Thanks, Shadwell. And with the following structure:ERB.new <<-EOF <label for="blabla"><%= v %></label>EOFI don't even need to escape the double quotes when I have one.I use the to_html to avoid ifs on my controllers and/or views when displaying the models. It keeps the code clean.
Renan