2012-03-22 18 views
5

Aşağıdaki Yakut komut dosyası vardır:Blokları/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) 

ben "daha sonra burada bir blok kullanmak ve çıkış "çıktı", bloğunda sonra içeriğe bunu elde etmeye çalışma ve am çıktı ", ama işe almak için görünmüyor olabilir.

ERB'nin Rails 2.3'te bu şekilde çalıştığını biliyorum ve şimdi Rails 3'te <%= ile çalışıyor ... ama hiç Ray kullanmıyorum. Bu sadece saf ERB.

Tüm içeriği çıkarmak için nasıl alabilirim?

cevap

3

Jeremy McAnally, nasıl yapılacağı konusunda beni this perfect description'a bağladı.

Temel olarak, ERB'ye çıktı arabelleğini bir değişkende saklamasını söylemeniz gerekir.

senaryo bu gibi bakarak biter:

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

harika. Bunu bir süre önce gördüğümü hatırlıyorum. Biraz Oynuyordum:

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"