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
)
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
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