Created
July 28, 2008 16:05
-
-
Save clemens/2907 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config | |
:number => { | |
:format => { | |
:precision => 3, | |
:separator => '.', | |
:delimiter => ',' | |
}, | |
:currency => { | |
:format => { | |
:unit => '$', | |
:precision => 2, | |
:format => '%u%n' | |
} | |
}, | |
:human => { | |
:format => { | |
:precision => 1 | |
} | |
} | |
} | |
# test | |
def test_number_to_human_size_translates_human_formats | |
I18n.expects(:translate).with(:'number.format', :locale => 'en-US').returns(@number_defaults) | |
I18n.expects(:translate).with(:'number.human.format', :locale => 'en-US').returns(@human_defaults) | |
number_to_human_size(1, :locale => 'en-US') | |
end | |
# helper | |
def number_to_human_size(size, *args) | |
options = args.extract_options! | |
options.symbolize_keys! | |
defaults = I18n.translate(:'number.format', :locale => options[:locale]) | |
defaults.merge!(I18n.translate(:'number.human.format', :locale => options[:locale])) | |
unless args.empty? | |
precision = args[0] || defaults[:precision] | |
end | |
precision ||= (options[:precision] || defaults[:precision]) | |
size = Float(size) | |
case | |
when size.to_i == 1; "1 Byte" | |
when size < 1.kilobyte; "%d Bytes" % size | |
when size < 1.megabyte; "%.#{precision}f KB" % (size / 1.0.kilobyte) | |
when size < 1.gigabyte; "%.#{precision}f MB" % (size / 1.0.megabyte) | |
when size < 1.terabyte; "%.#{precision}f GB" % (size / 1.0.gigabyte) | |
else "%.#{precision}f TB" % (size / 1.0.terabyte) | |
end.sub(/([0-9]\.\d*?)0+ /, '\1 ' ).sub(/\. /,' ') | |
rescue | |
nil | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment