Convert "1.hour" to 1.hour

Is it possible to convert the string "1.hour" to 1.hour and "2.hours" to 2.hours in ruby? In fact, I get this value from the drop-down list in the form. I want to add it to Time.now with something like this

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

where params[:days_or_hours] can be "2.hours" or "1.hour" or "1.day". I want to get a method for converting these strings. Is it possible? (in some way, for example send )

+4
source share
3 answers

You should not do this with eval , because then someone using your site can send any line of Ruby code for you, which would be a bad security hole for your site. You can check the string with regexp or whitelist, but that would be dirty.

I think you should rate 1.hour and 2.hours , etc. when rendering your form. Something like that:

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

This generates HTML as follows:

 <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 transmitted when the form is submitted, and you do not need to worry about whether the user has selected hours or days. Your code will simply be:

 time = Time.now + params[:days_or_hours].to_i 
+9
source

Another way to do this is to break the line:

 >> duration, method = '1.hour'.split('.') => ["1", "hour"] >> duration.to_i.send(method) => 3600 seconds 

Of course, you definitely want to somehow protect this:

 if duration_string =~ /^\d+\.(hour|minute|second)s?$/ # ... end 
+3
source

You can do this with the eval keyword.

eg. Time.now + eval("1.hour")

Edit: As stated many times, while you can do this, you shouldn't.

-2
source

Source: https://habr.com/ru/post/1342972/


All Articles