My objective is to convert form input, like "100 megabytes" or "1 gigabyte", and converts it to a filesize in kilobytes I can store in the database. Currently, I 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 a multiple ("gigabytes", but not "gigabyte") and seems insanely unsafe due to the use of eval
. So, functional, but I won't sleep well tonight.
Any guidance?
EDIT: ------
All right. For some reason, the regex with (.*?) isn't working correctly on my setup, but I've worked around it with Rails stuff. Also, I've 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
This catches "1 megabyte", "1.5 megabytes", and most other things (I hope). It then makes it the singular version regardless. Then it does the multiplication and spits out magic answers.
Is this legit?
EDIT AGAIN: See answer below. Much cleaner than my nonsense.
You can use Rails ActiveHelper number_to_human_size.
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
?
for optional plural in the regex. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With