1

I have been using the excellent number_to_human_size ActionView::Helper and I was wondering if there is any way to change the output unit notation:

The default behavior is to output the units in Bytes, KB, MB, etc while I would like to see Bit, Kb, Mb etc.

The number conversion is correct, I only want to change the unit name. I have figured out that using locales could be a solution and have added this in my en.yml:

en:
  storage_units:
    format: "%n %u"
    units:
      byte:
        one: "b/s"
        other: "b/s"
      kb: "Kb/s"
      mb: "Mb/s"
      gb: "Gb/s"
      tb: "Tb/s"

...but doesn't seem to work.

Has anybody ever dealt with this challenge?

Thanks in advance,

Petros

Cacofonix
  • 465
  • 11
  • 19

1 Answers1

1

With Rails' number_to_human_size you can just do a gsub to replace values in the suffix.

number_to_human_size(1234567890).gsub(/(Bytes?|B$)/,'b/s')
# => "1.15 Gb/s"
jstim
  • 2,432
  • 1
  • 21
  • 28
  • Yes indeed, but I am interested in ```human_to_number_size``` which deals with file sizes (1024 instead of 1000). Apparently the above does not apply to this specific helper: `irb(main):003:0> number_to_human(123456789000, units: {unit: "b/s", thousand: "Kb/s", million: "Mb/s", billion: "Gb/s", trillion: "Tb/s"})` => "123 Gb/s" `irb(main):004:0> number_to_human_size(123456789000, units: {unit: "b/s", thousand: "Kb/s", million: "Mb/s", billion: "Gb/s", trillion: "Tb/s"})` => "115 GB" – Cacofonix Feb 13 '14 at 09:08
  • yea, I looked at number_to_human_size but it doesnt allow you to specify custom suffixes. Now that I think about it, what about doing a gsub? – jstim Feb 13 '14 at 17:50
  • Very well performed! Even though a bit out of context, what is the functionality of :? and ?, which are wrapping ```Bytes```? – Cacofonix Feb 15 '14 at 00:32
  • Check out http://rubular.com/. Those symbols are part of a regular expression. The second ? says to match zero or one `s`, so it matches `Byte` or `Bytes`. The `:?` is a mistake. I meant it to be a non-capturing group `?:`, but that doesn't really matter for `gsub`. Removing it. – jstim Feb 15 '14 at 01:36