Convert file size to kilobyte equivalent in Rails

My goal is to convert the input of a form, such as "100 megabytes" or "1 gigabyte," and convert it to the file size in kilobytes, which I can save in the database. I currently have this:

def quota_convert
  @regex = /([0-9]+) (.*)s/
  @sizes = %w{kilobyte megabyte gigabyte}
  m = self.quota.match(@regex)
  if @sizes.include? m[2]
    eval("self.quota = #{m[1]}.#{m[2]}")
  end
end

This works, but only if the input is multiple ("gigabytes" but not "gigabytes") and seems insanely dangerous due to use eval. So functional, but today I will not sleep well.

Any directions?

EDIT: ------

Good. For some reason, the regex with (. *?) Doesn't work correctly in my setup, but I worked with it using Rails. Also, I realized that bytes would work better for me.

def quota_convert
  @regex = /^([0-9]+\.?[0-9]*?) (.*)/
  @sizes = { 'kilobyte' => 1024, 'megabyte' => 1048576, 'gigabyte' => 1073741824}
  m = self.quota.match(@regex)
  if @sizes.include? m[2].singularize
    self.quota = m[1].to_f*@sizes[m[2].singularize]
  end
end

"1 ", "1,5 " (). . .

?

: . . , .

+5
4
def quota_convert
  @regex = /([0-9]+) (.*)s?/
  @sizes = "kilobytes megabytes gigabytes"
  m = self.quota.match(@regex)
  if @sizes.include? m[2]
    m[1].to_f.send(m[2])
  end
end
  • ? .
  • @sizes .
  • m [1] ( ).
  • m [2]
+3

Rails ActiveHelper number_to_human_size.

+3

, ? eval !

+1

First of all, changing your regular expression to @regex = /([0-9]+) (.*?)s?/will fix the plural problem.? says the match is either 0 or 1 character for 's', and that calls. * to match in a non-greedy way (as few characters as possible).

As for size, you can have a hash like this:

@hash = { 'kilobyte' => 1, 'megabyte' => 1024, 'gigabyte' => 1024*1024}

and then your calculation is equal self.quota = m[1].to_i*@hash[m2]

EDIT: Changed values ​​to base 2

0
source

All Articles