2012-03-22 14 views
5

Tengo el siguiente script Ruby:bloques en ERB pura/Erubis

require 'erubis' 

def listing(title, attributes={}) 
    "output" + yield + "more output" 
end 

example = %Q{<% listing "db/migrate/[date]_create_purchases.rb", :id => "ch01_292" do %> 
<![CDATA[class CreatePurchases < ActiveRecord::Migration 
    def change 
    create_table :purchases do |t| 
     t.string :name 
     t.float :cost 
     t.timestamps 
    end 
    end 
end]]> 
<% end %>} 

chapter = Erubis::Eruby.new(example) 
p chapter.result(binding) 

Estoy intentando utilizar un bloque de aquí y llegar a la salida "de salida", entonces el contenido en el bloque y luego "más salida ", pero parece que no puedo hacer que funcione.

sé que ERB utiliza para trabajar de esta manera en Rails 2.3 y ahora trabaja con <%= en Rails 3 ... pero no estoy usando los carriles en absoluto. Esto es solo puro ERB.

¿Cómo puedo obtener todo el contenido?

Respuesta

3

Jeremy McAnally me ha vinculado al this perfect description de cómo hacerlo.

Básicamente, necesita decirle a ERB que almacene el búfer de salida en una variable.

El guión termina pareciéndose a esto:

require 'erb' 

def listing(title, attributes={}) 
    concat %Q{ 
<example id='#{attributes[:id]}'> 
    <programlisting> 
    <title>#{title}</title>} 
    yield 
    concat %Q{ 
    </programlisting> 
</example> 
    } 
end 

def concat(string) 
    @output.concat(string) 
end 

example = %Q{<% listing "db/migrate/[date]_create_purchases.rb", :id => "ch01_292" do %> 
<![CDATA[class CreatePurchases < ActiveRecord::Migration 
    def change 
    create_table :purchases do |t| 
     t.string :name 
     t.float :cost 
     t.timestamps 
    end 
    end 
end]]> 
<% end %>} 

chapter = ERB.new(example, nil, nil, "@output") 
p chapter.result(binding) 
0

Grande. Recuerdo haberlo visto hace un tiempo. Jugando un poco que estaba recibiendo esto:

require 'erubis' 

def listing(title, attributes={}) 
    %Q{<%= "output #{yield} more output" %>} 
end 

example = listing "some title", :id => 50 do 
      def say_something 
       "success?" 
      end 
      say_something 
      end 


c = Erubis::Eruby.new(example) 
p c.evaluate 
# => "output success? more output"