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
Another way to do it would be to split the string:
>> duration, method = '1.hour'.split('.')
=> ["1", "hour"]
>> duration.to_i.send(method)
=> 3600 seconds
Of course, you'd definitely want to protect this in some way:
if duration_string =~ /^\d+\.(hour|minute|second)s?$/
# ...
end
You can do this with the eval
keyword.
e.g. Time.now + eval("1.hour")
Edit: As has been pointed out many times, while you can do this, you shouldn't.
精彩评论