Reputation: 29
In Ruby I want to use an input parameter for REST verb (like 'Post') in a call to Net::HTTP new but I can't work out how to embed the parameter in the statement. I have the param called restVerb which prints fine in puts "Verb is #{restVerb}"
but not in request = Net::HTTP::#{restVerb}.new(uri)
- I get undefined method
request' for Net::HTTP:Class (NoMethodError)` so it clearly doesn't recognise the parameter's value in the statement. I could use a case statement but wanted to make it more generic. What am I doing wrong?
I've tried the above syntax and a few others like request = Net::HTTP::restVerb.new(uri)
or request = Net::HTTP::$restVerb.new(uri)
I'm new to Ruby so be gentle with me please.
Upvotes: 1
Views: 35
Reputation: 10526
Use Object.const_get
to convert a string to an actual constant:
klass = Object.const_get("Net::HTTP::#{restVerb}")
=> Net::HTTP::Post
klass.new(uri)
=> #<Net::HTTP::Post POST>
Upvotes: 1