Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert "1.hour" to 1.hour

Is it possible to convert "1.hour" string to 1.hour and "2.hours" to 2.hours in ruby? Actually I am getting this value from a dropdown in a form. I want to add it to Time.now by something like this

time = Time.now + get_method(params[:hours_or_days])

where params[:days_or_hours] may be "2.hours" or "1.hour" or "1.day". I want to get the method conversion of these strings. Is it possible? (by some method like send)

like image 266
rubyprince Avatar asked Mar 09 '11 10:03

rubyprince


1 Answers

You shouldn't do this with eval because then someone using your website could send any string of Ruby code for you to execute, which would be a bad security hole for your site. You could validate the string using a Regexp or a whitelist but that would be messy.

I think you should be evaluating the 1.hour and 2.hours and so on when rendering your form. Something like this:

<%= select_tag(:days_or_hours, options_for_select({ "1 hour" => 1.hour, "2 hours" => 2.hours })) %>

This generates HTML like this:

<select name="days_or_hours">
  <option value="3600">1 hour</option>
  <option value="7200">2 hours</option>
</select>

Now the number of seconds will be passed when the form is submitted, and you don't have to worry about whether the user chose hours or days. Your code simply becomes:

time = Time.now + params[:days_or_hours].to_i
like image 87
Paige Ruten Avatar answered Nov 15 '22 04:11

Paige Ruten