Cookie in rest-client Ruby - ruby

Is it possible to add cookie like
key[index]=value
Here is my code
options[:headers][:cookies] = {:cookie_key => 'cookie_value'}
resource[options[:path]].get(options[:headers])
This code works fine but when I try something like
options[:headers][:cookies] = {:cookie_key => {} }
I get /../../util.rb:16:in 'unescape': undefined method 'tr' for #<Hash:0x0000000195f7d0> (NoMethodError)

Cookies basically can only store strings (for each first-level key).
In order to store hash in cookies values, you need serialize/deserialize the data, for example, with JSON
cookies[:i_need_to_store_hash] = hsh.to_json
and than
i_need_to_get_my_hash_back = JSON.parse(cookies[:i_need_to_store_hash])
but remember that cookies very limited in size (4096 bytes)

Related

Ruby URI: build URI with "param[]=value" for array params

I'm trying to query an API (lichess API). And I can't get the params to be correctly taken into account, because URI formats the URL not in the expected format for array params.
The expected format is this one: curl https://explorer.lichess.ovh/lichess?ratings[]=2200&ratings[]=2500. So the ratings params is an Array of values, and the url should be using ratings[]=value.
I'm currently generating my URI like this, as per the doc:
base = "https://explorer.lichess.ovh/master"
params = {
ratings: [1600, 1800]
}
uri = URI(base)
uri.query = URI.encode_www_form(params)
But this generate the URL like this: https://explorer.lichess.ovh/master?ratings=1600&ratings=1800... which is not the expected format, and is not understood by Lichess API.
Does Ruby provide any built-in way to generate the params in the expected format, or will I need to build the URL manually (which feels like revinventing the wheel)?
Rails/ActiveSupport has a to_query method which will do what you want.
2.1.5 :010 > params.to_query
=> "ratings%5B%5D=1600&ratings%5B%5D=1800"
Also, have a look at this comment which explains why URI.encode_www_form doesn't return square brackets.

OLA Money API Hash Code Error

While integrating OLA Money API, when I hit url with all parameter am getting error
"Hash Code mismatched"
The main problem is when we send generated hash code through url, then last 2 characters of hash key == are changed into %3D%3D. Could you please give me solution of this.
Both Hash key are given below:
Generated Hash Key before URL-------------------------------------------------------------------------
eyJjb21tYW5kIjoiZGViaXQiLCJhY2Nlc3NUb2tlbiI6IjN1NDFwODJ1VDEiLCJ1bmlxdWVJZCI6IjEyMzQ1Nk9MNTY0Nzg4OSIsImNvbW1lbnRzIjoib2RldFgiLCJ1ZGYiOiI4dkJkZiIsImhhc2giOiJjODkzZTFjMWViZTQ1MTliMTUzOGE1NTEyNTUzMzRjNGRlNjZiNWRiNDQ4OWI1MTdlN2MxN2RhYzM4YWMwNTA3MGY1ZDQ3MDBiNjRlMTUyMTUyYzg5NWVlYzFhMDYyMGYzMTFlNzkyMDYzNzk5OThjZDQ2ZGE0ZDkxMzRiYzEzZSIsInJldHVyblVybCI6Imh0dHA6Ly93d3cucnVwbGVlZGV2bG9wbWVudC5jb20vc2VydmljZS93ZWJzZXJ2aWNlc192MDMvb2xhbW9uZXkvb2xhUmVzcG9uc2UucGhwIiwibm90aWZpY2F0aW9uVXJsIjoiaHR0cDovL3d3dy5ydXBsZWVkZXZsb3BtZW50LmNvbS9zZXJ2aWNlL3dlYnNlcnZpY2VzX3YwMy9vbGFtb25leS9vbGFOb3RpZnkucGhwIiwiYW1vdW50IjoxLCJjdXJyZW5jeSI6IklOUiIsImNvdXBvbkNvZGUiOiIifQ==
Generated Hash Key in URL--------------------------------------------------------------------------------
eyJjb21tYW5kIjoiZGViaXQiLCJhY2Nlc3NUb2tlbiI6IjN1NDFwODJ1VDEiLCJ1bmlxdWVJZCI6IjEyMzQ1Nk9MNTY0Nzg4OSIsImNvbW1lbnRzIjoib2RldFgiLCJ1ZGYiOiI4dkJkZiIsImhhc2giOiJjODkzZTFjMWViZTQ1MTliMTUzOGE1NTEyNTUzMzRjNGRlNjZiNWRiNDQ4OWI1MTdlN2MxN2RhYzM4YWMwNTA3MGY1ZDQ3MDBiNjRlMTUyMTUyYzg5NWVlYzFhMDYyMGYzMTFlNzkyMDYzNzk5OThjZDQ2ZGE0ZDkxMzRiYzEzZSIsInJldHVyblVybCI6Imh0dHA6Ly93d3cucnVwbGVlZGV2bG9wbWVudC5jb20vc2VydmljZS93ZWJzZXJ2aWNlc192MDMvb2xhbW9uZXkvb2xhUmVzcG9uc2UucGhwIiwibm90aWZpY2F0aW9uVXJsIjoiaHR0cDovL3d3dy5ydXBsZWVkZXZsb3BtZW50LmNvbS9zZXJ2aWNlL3dlYnNlcnZpY2VzX3YwMy9vbGFtb25leS9vbGFOb3RpZnkucGhwIiwiYW1vdW50IjoxLCJjdXJyZW5jeSI6IklOUiIsImNvdXBvbkNvZGUiOiIifQ%3D%3D
I look forward to solution from you,
Issue here is - one of the Hash is getting URL encoded. Easiest way is to URL decode both the strings and then match. Here:
require 'uri'
h1 = "eyJjb21tYW5kIjoiZGViaXQiLCJhY2Nlc3NUb2tlbiI6IjN1NDFwODJ1VDEiLCJ1bmlxdWVJZCI6IjEyMzQ1Nk9MNTY0Nzg4OSIsImNvbW1lbnRzIjoib2RldFgiLCJ1ZGYiOiI4dkJkZiIsImhhc2giOiJjODkzZTFjMWViZTQ1MTliMTUzOGE1NTEyNTUzMzRjNGRlNjZiNWRiNDQ4OWI1MTdlN2MxN2RhYzM4YWMwNTA3MGY1ZDQ3MDBiNjRlMTUyMTUyYzg5NWVlYzFhMDYyMGYzMTFlNzkyMDYzNzk5OThjZDQ2ZGE0ZDkxMzRiYzEzZSIsInJldHVyblVybCI6Imh0dHA6Ly93d3cucnVwbGVlZGV2bG9wbWVudC5jb20vc2VydmljZS93ZWJzZXJ2aWNlc192MDMvb2xhbW9uZXkvb2xhUmVzcG9uc2UucGhwIiwibm90aWZpY2F0aW9uVXJsIjoiaHR0cDovL3d3dy5ydXBsZWVkZXZsb3BtZW50LmNvbS9zZXJ2aWNlL3dlYnNlcnZpY2VzX3YwMy9vbGFtb25leS9vbGFOb3RpZnkucGhwIiwiYW1vdW50IjoxLCJjdXJyZW5jeSI6IklOUiIsImNvdXBvbkNvZGUiOiIifQ=="
h2 = "eyJjb21tYW5kIjoiZGViaXQiLCJhY2Nlc3NUb2tlbiI6IjN1NDFwODJ1VDEiLCJ1bmlxdWVJZCI6IjEyMzQ1Nk9MNTY0Nzg4OSIsImNvbW1lbnRzIjoib2RldFgiLCJ1ZGYiOiI4dkJkZiIsImhhc2giOiJjODkzZTFjMWViZTQ1MTliMTUzOGE1NTEyNTUzMzRjNGRlNjZiNWRiNDQ4OWI1MTdlN2MxN2RhYzM4YWMwNTA3MGY1ZDQ3MDBiNjRlMTUyMTUyYzg5NWVlYzFhMDYyMGYzMTFlNzkyMDYzNzk5OThjZDQ2ZGE0ZDkxMzRiYzEzZSIsInJldHVyblVybCI6Imh0dHA6Ly93d3cucnVwbGVlZGV2bG9wbWVudC5jb20vc2VydmljZS93ZWJzZXJ2aWNlc192MDMvb2xhbW9uZXkvb2xhUmVzcG9uc2UucGhwIiwibm90aWZpY2F0aW9uVXJsIjoiaHR0cDovL3d3dy5ydXBsZWVkZXZsb3BtZW50LmNvbS9zZXJ2aWNlL3dlYnNlcnZpY2VzX3YwMy9vbGFtb25leS9vbGFOb3RpZnkucGhwIiwiYW1vdW50IjoxLCJjdXJyZW5jeSI6IklOUiIsImNvdXBvbkNvZGUiOiIifQ%3D%3D"
h1 == h2
# => false
URI.unescape(h1) == URI.unescape(h2)
# => true

Ruby Sinatra and JSON objects from toodledo API 2.0

I have a small problem with receiving JSON objects. I'm using Ruby 1.9.3 and my goal is to receive my tasks from an API via RestClient and print them more or less pretty onto the page.
I created a route /test:
get '/test' do
json_ip_url = "http://api.toodledo.com/2/tasks/get.php?key=198196ae24792467eec09ac2191*****;modafter=1234567890;fields=folder,star,priority"
ip_details = RestClient.get(json_ip_url)
test = JSON.pretty_generate(ip_details) # => throws exception
end
The JSON#pretty_generate line throws an error, "only generation of JSON objects or arrays allowed". What am I doing wrong here?
Update:
I'am now able to output via pretty_generate, but what do I have to do, to get the elements of it. Here is the JSON Data, it seems to me its an Array with Objects inside of it?
[{"num":"18","total":"18"},{"id":"11980343","title":"Add some items to your todo list","modified":1391670256,"completed":0,"folder":"0","star":"0"},{"id":"11980345","title":"Visit the Settings section and configure your account","modified":1391670256,"completed":0,"folder":"0","star":"0"},{"id":"11980347","title":"Watch our tutorial videos in the Help section","modified":1391670256,"completed":0,"folder":"0","star":"1"},{"id":"12607789","title":"test","modified":1392285802,"completed":0,"folder":"0","star":"0"},{"id":"12636039","title":"My Task","modified":1392308705,"completed":0,"folder":"0","star":"0"},{"id":"12636041","title":"Another","modified":1392308705,"completed":0,"folder":"0","star":"1"},{"id":"12636143","title":"My Task","modified":1392308789,"completed":0,"folder":"0","star":"0"},{"id":"12636145","title":"Another","modified":1392308789,"completed":0,"folder":"0","star":"1"},{"id":"12636449","title":"My Task","modified":1392308950,"completed":0,"folder":"0","star":"0"},{"id":"12636451","title":"Another","modified":1392308950,"completed":0,"folder":"0","star":"1"},{"id":"12636621","title":"My Task","modified":1392309061,"completed":0,"folder":"0","star":"0"},{"id":"12636623","title":"Another","modified":1392309061,"completed":0,"folder":"0","star":"1"},{"id":"12636665","title":"My Task","modified":1392309085,"completed":0,"folder":"0","star":"0"},{"id":"12636667","title":"Another","modified":1392309085,"completed":0,"folder":"0","star":"1"},{"id":"12636733","title":"My Task","modified":1392309137,"completed":0,"folder":"0","star":"0"},{"id":"12636735","title":"Another","modified":1392309137,"completed":0,"folder":"0","star":"1"},{"id":"12637135","title":"My Task","modified":1392309501,"completed":0,"folder":"0","star":"0"},{"id":"12637137","title":"Another","modified":1392309501,"completed":0,"folder":"0","star":"1"}]
The Code I used for pretty_generate:
get '/save' do
jdata = params[:data]
response = RestClient.get 'http://api.toodledo.com/2/tasks/get.php?key=da21e24e2a00ba9d45008974aed00***;modafter=1234567890;fields=folder,star,priority', {:accept => :json}
test = JSON.parse(response)
test.to_json
output = JSON.pretty_generate(test)
puts output
RestClient#get returns the raw response as a string (and not a hash or array) when called without a block, so ip_details isn't a structure that JSON#pretty_generate knows how to handle. You need to use JSON#parse to turn the response into a hash or array first.

how to find a hash key with one of the predefined names?

I have a hash with an arbitrary key:
{'GET': [1,2,3]}
or
{'POST': ['my data 0', 'my data 1']}
The hash is generated from JSON which is sent in the request body. There is just one key, or rather, I ignore any keys but one.
I want to find which key it is, and this is the code that I wrote:
items = data['GET'] || data['get'] || data['POST'] || data['post']
this does not look neat. If the number of keys that I want to process grows the expression will be long. I want it to be short. I am new to Ruby, is there a better way?
If you think it might grow, you may want to separate the HTTP methods from the finding of that method in the data:
methods = [:get, :post]
def find_method(data)
keys = methods.map{|m| [m.to_s.upcase, m.to_s]}.flatten
data.values_at(keys).first
end
You could just get the first value (assuming there's only one) like this:
item = data.values.first
You could use the Hash#values_at method.
http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-values_at
data.values_at('GET','get', 'POST','post').first

Post nested params (hash) using HTTPClient

I needed a to have a multipart http post from one app to another that included a file attachment and a nested params hash. I tried using HTTPClient which worked for the file attachment, however I could not get params to send in a nested format.
data_params = Hash.new
data_params[:params] = Hash.new
data_params[:params][:f] = Hash.new
data_params[:params][:d] = Hash.new
data_params[:params][:d][:name] = "Mich"
data_params[:params][:d][:city] = "Ostin"
data_params[:params][:f][:event] = "Sundance"
http_client = HTTPClient.new
body = data_params[:params]
response = http_client.post('http://localhost:3030/receiver/receive_test_data/', body)
with the receiver app seeing the params as {"d"=>"nameMichcityOstin","f"=>"eventSundance"} (with the hash collapsed into strings on the nested level)
I wonder if this is a limitation on http posts or am I simply doing something wrong. I have worked with JSON before, which I know supports a nested structure, but there I have no idea how to add file attachments. I appreciate any suggestions or alternative methods that would comply with 'best practices' on doing something like this.
If using Rails:
> {:a=>53,:b=>{:c=>7}}.to_query
=> "a=53&b[c]=7"
http://apidock.com/rails/ActiveSupport/CoreExtensions/Hash/to_query
I'm not sure which HTTPClient library you're using so I haven't been able to try this, but what if you use keys like this
data_params[:params]['d[name]'] = "Mich"
data_params[:params]['d[city]'] = "Ostin"
i.e. data_params[:params] is just a one level hash.
and then the receiving application will unpack this into the nested hash that you expect.

Resources