2016-07-24 52 views
0

我試圖找出處理時間字段的最佳方法。我爲烹飪應用程序的時間和準備時間做了很多工作,如果我可以允許用戶在文本字段中基本寫入,然後將其轉換爲持續時間以存儲並使用導軌distance_of_time_in_words函數來顯示它。還沒有能夠找到任何點我在正確的方向爲這如何處理在rails應用程序中輸入時間

編輯:所以我嘗試使用下面的Minutizer但我不斷收到

未定義的方法`minutize」慢性:模塊

我創建了下面的代碼創建一個新模塊chronic.rb和我的應用程序保存它/ libs文件夾

然後,我已經包括在我的模型慢性,但我不能得到上述

擺脫錯誤的
+0

[在Rails模型中使用的持續時間字段(http://stackoverflow.com/questions/1051465/using-a-duration-field-in-a-rails-model) –

回答

1

嘗試在慢性寶石本拉入請求 - https://github.com/mojombo/chronic/pull/231

它能夠處理下列期限:

  • 一個半鍾
  • 半小時
  • 1.5小時
  • &更多

粘貼代碼(由https://github.com/TalkativeTree PR)在這裏,因爲它可能會被刪除:

class Minutizer 

    def minutize(text) 
     text = pre_normalize(text) 
     extract_time(text) 
    end 

    def pre_normalize(text) 
     text.gsub!(/half an/, 'a half') 
     text.gsub!(/half a/, 'a half') 
     text = Numerizer.numerize(text.downcase) 
     text.gsub!(/an hour/, '1 hour') 
     text.gsub!(/a hour/, '1 hour') 
     text.gsub!(/a day/, '1 minute') 
     text.gsub!(/a minute/, '1 day') 
     text.gsub!(/a week/, '1 week') 
     # used to catch halves not covered by Numerizer. Use for the conversion of 'an hour and a half' Previous gsubs will have changed it to '1 hour and haAlf' by this point. 
     text.gsub!(/(\d+)\s?\w+?\s?and haAlf/) do |m| 
     m.gsub!(/\A\d+/, ($1.to_f + 0.5).to_s) 
     end 
     text.gsub!(/\s?and haAlf/, '') 
     text.gsub!(/haAlf/, "0.5") 
     text.gsub!(/(seconds|secnds|second|secnd|secs)/, 'sec') 
     text.gsub!(/(minutes|minute|mintues|mintes|mintue|minte)/, 'min') 
     text.gsub!(/(horus|hours|huors|huor|hrs|hr)/, 'hour') 
     text.gsub!(/(days|day|dy)/, 'day') 
     text.gsub!(/(weeks|wks|wk)/, 'week') 
     text 
    end 

    def extract_time(text) 
     minutes = extract(text, 'week') 
     minutes += extract(text, 'day') 
     minutes += extract(text, 'hour') 
     minutes += extract(text, 'min') 
     minutes += extract(text, 'sec') 
    end 

    def extract(text, option) 
     total = text.match(/(\d+.\d+|\d+)\s?(#{option})/) 

     return 0 unless total 
     digitize_time(total[1], option) 
    end 

    def digitize_time(time, option) 
     case option 
     when 'week' 
     multiplier = 7 * 24 * 60 
     when 'day' 
     multiplier = 24 * 60 
     when 'hour' 
     multiplier = 60 
     when 'min' 
     multiplier = 1 
     when 'sec' 
     multiplier = 1.to_f/60 
     end 

     return multiplier * time.to_f 
    end 
    end 

只是保存在某個地方上面的文件,並嘗試下面這樣:

您還需要安裝minutizer工作「numerizer」寶石。

☁ Documents irb 
2.3.0 :001 > require './minutizer.rb' 
=> true 
2.3.0 :002 > require 'numerizer' 
=> true 
2.3.0 :003 > Minutizer.new.minutize('1.5 hours') 
=> 90.0 
2.3.0 :004 > 
+0

Im的可能的複製有一個非常困難的時間搞清楚如何得到這個工作...我從你的github安裝了慢性寶石,但它似乎也沒有minutizer。我怎樣才能覆蓋它並將其添加進來。你能否給我快速的步驟,以便我需要在模型文件中調用它。謝謝 – DRing

+0

@DRing更新了答案。你不需要慢性寶石,但你需要的數字寶石 – emaillenin

+0

好,所以下面的工作在我的軌道控制檯爲我的應用程序。現在我試着將它整合到我的表格中,以便在保存前改變輸入 – DRing

相關問題