On Jun 19, 2009, at 11:51 AM, djolley wrote: > > Thanks so much for your kind explanation. Unfortunately, it still > doesn't make sense to me. > > The documentation for the ERB class tells us: > > <% Ruby code -- inline with output %> > <%= Ruby expression -- replace with result %> > > That makes perfect sense. The documentation even alludes to the > capability in question in an example; but, it really isn't discussed. > In discussing <% %>, the Agile Rails book makes the observation, > "Interestingly, this kind of processing can be intermixed with non- > ruby code." Then they give a minor example and launch into a > discussion dealing with extraneous new line characters. > > Am I alone in thinking that this is a monumental capability that > deserves a better understanding? > > Anyway, thanks very much for the response. I'm sorry that it didn't > quite bridge the gap for me. I guess that I either have a mental > block or am just super dense. Thanks again. > > ... doug
Ok, I oversimplified it. This discussion really belongs on the ruby- talk ML, but here is the longer explanation. Assuming you have the code: require 'rubygems' require 'erb' template =<<EOD This is plain text And the time is <%= Time.now %> <% if true %> it was true <% else %> it wasn't true <% end %> EOD puts ERB.new(template).result Then after compiling it, ERB creates: "_erbout = ''; _erbout.concat \"This is plain text\\n \"\n_erbout.concat \"And the time is \"; _erbout.concat(( Time.now ).to_s); _erbout.concat \"\\n\"\n if true ; _erbout.concat \"\\n\"\n_erbout.concat \" it was true\\n\"\n else ; _erbout.concat \"\\n\"\n_erbout.concat \" it wasn't true\\n\"\n end ; _erbout.concat \"\\n\"\n_erbout" Without getting into the details of how ERB scans and tokenizes the text, the point I want to make is that what you thought was HTML is nothing more than a bunch of strings to ERB. These strings are passed to eval, which evaluates and runs them as Ruby code. So check it out. I just reformatted the code above: "_erbout = '' _erbout.concat \"This is plain text\\n\"\n_erbout.concat \"And the time is \" _erbout.concat(( Time.now ).to_s) _erbout.concat \"\\n\"\n if true _erbout.concat \"\\n\"\n_erbout.concat \" it was true\\n\"\n else _erbout.concat \"\\n\"\n_erbout.concat \" it wasn't true\\n\"\n end _erbout.concat \"\\n\"\n_erbout" And you can see how the if and else affect what strings are output. For a more in-depth example, just do what I did: Create the ERB, punch it into rdebug, and step through it. Ain't it cool to have source? Steve --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---

