2008-12-08 25 views
14

我需要將字節的整數表示格式化爲友好的東西,並且我希望在Ruby或Rails中有一個實用程序函數來爲我進行格式設置(以延長我的懶惰,當然)Rails中的友好字節格式

我在尋找的東西看起來像:

format_bytes(1024)  -> "1 KB" 
format_bytes(1048576) -> "1 MB" 

看起來有一些東西在的ActiveSupport這樣做的其他方式,但我還沒有找到一種方法做它在這個方向。

如果沒有一個存在,是否有人有一個特別優雅的解決方案?

回答

37

Number to human size是你在找什麼。

require 'action_view' 
include ActionView::Helpers::NumberHelper 
number_to_human_size(123)           # => 123 Bytes 
number_to_human_size(1234)           # => 1.2 KB 
number_to_human_size(12345)          # => 12.1 KB 
number_to_human_size(1234567)          # => 1.2 MB 
number_to_human_size(1234567890)         # => 1.1 GB 
number_to_human_size(1234567890123)        # => 1.1 TB 
number_to_human_size(1234567, :precision => 2)      # => 1.18 MB 
number_to_human_size(483989, :precision => 0)      # => 473 KB 
number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,18 MB 
+2

謝謝!我正在尋找這個確切的解決方案。 – CalebHC 2009-11-10 05:47:03

1

接受的答案仍然有效,但在新版rails中需要actionpack而不是actionview。

require 'actionpack' 
1

接受的答案它是完美的,但我並不需要前兩行。 我只把:

number_to_human_size(123)           # => 123 Bytes 
number_to_human_size(1234)           # => 1.2 KB 
number_to_human_size(12345)          # => 12.1 KB 
number_to_human_size(1234567)          # => 1.2 MB 
number_to_human_size(1234567890)         # => 1.1 GB 
number_to_human_size(1234567890123)        # => 1.1 TB 
number_to_human_size(1234567, :precision => 2)      # => 1.18 MB 
number_to_human_size(483989, :precision => 0)      # => 473 KB 
number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,18 MB 

和作品像魅力。