2015-08-30 10 views
2

我試圖創建一個表,其中顯示一個zip文件中像這樣的內容:如何直接在ruby文件中使用循環創建haml表?

Name  Size 
asdf1.jpg 100KB 
asdf2.jpg 200KB 
asdf3.jpg 300KB 

我的代碼是在這裏(實際上,我從ZipRuby的README複製它):

#myapp.rb 
post 'checkfile/?' do 
    Zip::Archive.open('zip_file.zip') do |ar| 
     n = ar.num_files 

     n.times do |i| 
      entry_name = ar.get_name(i) # get entry name from archive 

      # open entry 
      ar.fopen(entry_name) do |f| # or ar.fopen(i) do |f| 
       $name = f.name   # name of the file 
       $size = f.size   # size of file (uncompressed) 
       $comp_size = f.comp_size # size of file (compressed) 
       content = f.read # read entry content 
      end 
     end 
     # Zip::Archive includes Enumerable 
     entry_names = ar.map do |f| 
      f.name 
     end 
    end 
    haml :checkresult 
end 

而我的哈姆碼:

-# checkresult.haml 
%table 
%thead 
    %tr 
     %th Name 
     %th Size 
%tbody 
    %tr 
     -# I want to show files in zip here 

對不起,英文不好,標題不好。 (使用Sinatra v1.4.6(使用Puma。))

+0

你確定你使用的是'的Ruby on Rails'?你能確認你正在使用的Web框架嗎? –

+0

使用Sinatra v1.4.6(與彪馬。)感謝您的意見! :) – Dogdriip

回答

1

您可以通過將值分配給Sinatra應用程序中的實例變量來傳遞haml呈現的數據。請通過this tutorial

您需要對myapp.rb進行一些更改,如下所示。我們定義@result陣列收集結果

# myapp.rb 
post 'checkfile/?' do 

    @result = [] # this will hold results. 

    Zip::Archive.open('zip_file.zip') do |ar| 
     ar.each do |f| 
      @result << [f.name, f.size, f.comp_size] 
     end 
    end 

    haml :checkresult 
end 

你需要更新你的HAML文件看起來像下面 - table標籤添加,迭代器添加到遍歷結果併發出td

-# checkresult.haml 
%table 
%thead 
    %tr 
     %th Name 
     %th Size 
     %th Compressed size 
%tbody 
    %table 
     - @result.each do |i| 
      %tr 
       %td= i[0] 
       %td= i[1] 
       %td= i[2] 

PS:我可以不要在我的Windows機器上安裝ZipRuby,以便上面的代碼的一部分是基於documentation的猜測工作 - 希望您瞭解必須完成的工作。

+0

它運作良好!謝謝! :> – Dogdriip