Reputation: 5182
Given the following :
Curl.post(…)
Curl.get(…)
Curl.put(…)
Curl.delete(…)
I'm having a bunch of headers, so specifying those all over the place tends to make the code quite verbose in the end. A shared method like the following would be super useful :
def query(verb, endpoint, params)
Curl.send(verb, endpoint, params) { etc … }
end
But currently getting the following error :
Traceback (most recent call last):
2: from (irb):5
1: from app/lib/query.rb:12:in `run'
NoMethodError (undefined method `map' for nil:NilClass)
Obviously a syntax problem. Can it be done somehow ? Should another library be used for such need ?
Upvotes: 0
Views: 74
Reputation: 5182
Ok so just found out, params
can't be nil with such syntax; so a default empty hash is to be passed:
def query(token, verb, endpoint, params = {})
http = Curl.send(verb, endpoint, params) do |http|
http.headers['Accept-Encoding'] = 'gzip,deflate'
http.headers['Authorization'] = "Bearer #{token}"
end
http.body_str
end
Now :
ClassName.query('xxx', 'get', 'http://...')
ClassName.query('xxx', 'post', 'http://...', {some: :data})
ClassName.query('xxx', 'put', 'http://...', {some: :data})
ClassName.query('xxx', 'delete', 'http://...')
Works
Upvotes: 1