Reputation: 53
I am currently using the script
<?php $name = $_GET ["id"]; ?>
to pull the parameter from a URL like www.example.com?id=john
and then using
<?php echo $name ?>
when I need the variable in the code.
I now need to use Ruby instead of PHP to accomplish this task. Are there any comparable methods in Ruby on Rails?
Upvotes: 0
Views: 2016
Reputation: 160631
Rails has all the functionality needed, but it's a steep learning curve, so maybe Sinatra would be better for what you need. In particular, Sinatra, like Rails, makes it easy to get at the parameters in a URL. See Sinatra's "Routes" documentation if you want to go that way.
Here's code to extract the parameters from a URL using Ruby and its bundled URI class:
require 'uri'
uri = URI.parse('http://www.example.com?id=john')
uri.query # => "id=john"
Hash[URI.decode_www_form(uri.query)] # => {"id"=>"john"}
You can assign the result of the last line to a variable, then use it to access any of the parameter's values via its name:
params = Hash[URI.decode_www_form(uri.query)]
params['id'] # => "john"
Upvotes: 1