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 " (). . .
?
: . . , .