restclient with ruby - ruby-on-rails

Here i am trying to pass one ID with the url, but that ID didn't append with URL...
def retrieve
url = "http://localhost:3000/branches/"
resource = RestClient::Resource.new url+$param["id"]
puts resource
end
giving ID via commend line that is
ruby newrest.rb id="22"
I have got the error like this
`+': can't convert nil into String (TypeError)
But all this working with mozilla rest client. How to rectify this problem?

Like this:
RestClient.get 'http://localhost:3000/branches', {:params => {:id => 50, 'name' => 'value'}}

You can find the command line parameters in the global ARGV array.
If ruby newrest.rb 22 will do then just
id = ARGV[0]
response = RestClient.get "http://localhost:3000/branches/#{id}"
puts response.body

Here are some examples from the documentation:
private_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'
RestClient.post 'http://example.com/resource', :param1 => 'one', :nested => { :param2 => 'two' }
Just experiment with comma-separated parameters or with hashes so see what your URL gives you.

From my point of view line puts resource seems strange,
but when we leave it as it is
I'd suggest
def retrieve
url = "http://localhost:3000/branches/"
resource = RestClient::Resource.new url
res_with_param = resource[$param["id"]]
puts res_with_param
end
I haven't tried so there may be a syntax mistakes.
I'm really newcomer in ruby.
But idea is good I hope.
Greetings,
KAcper

Related

Ruby - Unexpected Hash data structure

A simple question:
In rails I get as response an hash like this:
{"success":true,"new_id":816704027}
So, the difference from a normal structure I guess is- "new_id": -instead of- new_id:
Does anyone know how to retrieve the data labelled "new_id"?
The usual array["new_id"] doesn't work.
The response to the code:
new_customer_id = #response.body
puts new_customer_id
puts new_customer_id["new_id"]
is simply:
=> {"success":true,"new_id":816704028}
=> new_id
I come from the implementation of JSON_response. Anyway, they changed the app and I don't have anymore a JSON message, but they use the method:
return_200(additional_items: {:new_id => "#customer.id"} )
More:
If I write:
new_customer_id = #response.body
puts new_customer_id
puts new_customer_id[:new_id]
the answer printed is simply:
=> {"success":true,"new_id":816704028}
and the request for the :new_id content does not to be received.
Much more interesting is the following:
After the fact that:
puts new_customer_id["new_id"]
prints:
=> new_id
If I write:
puts new_customer_id["new_id"][0]
puts new_customer_id["new_id"][1]
puts new_customer_id["new_id"][2]
...
I obtain:
=> n
=> e
=> w
...
Also:
if I write:
puts new_customer_id["new_"]
puts new_customer_id["new_i"]
I obtain:
=> new_
=> new_i
and if I write:
puts new_customer_id["new_id_anyOtherCharacter"]
I get nothing
Luca
That's not a ruby object you are getting back. It's JSON. You can get the new_id in a variety of ways:
JSON.parse(#response.body)["new_id"]
JSON.parse(#response.body).symbolize_keys[:new_id]
JSON.parse(#response.body).with_indifferent_access[:new_id]
I bet the hash has a symbol key instead of a string key. Try with array[:new_id].
use params to get the value like:
new_id= array[:new_id]

encoded URL construction fails in a Rails application

I've a very simple problem. I want to construct a encoded url from an object. I've an object called "invitation". "invitation" has following fields, "message", "date", "name". I want to construct a following encoded string from this object. So when I use this url, it will pre-fill google mail's compose form.
https://mail.google.com/mail/u/0/?view=cm&fs=1&su=Party+on+date&body=%0Amessage%0Ahttp://localhost:3000/invitations/3%0Aname%0A&tf=1
I've declared a helper as shown below (which suppose to return an encoded string and can be use in a view). ..
module ApplicationHelper
def google_mail_encoded_url(invite)
uri = URI.parse('https://mail.google.com/u/0/?')
uri.query = URI.encode_www_form('view'=> "cm", 'fs' => "1", 'su' => "Party on " + invite.date, 'body' => "\nHi,\n" + invite.message + "\n" + invitations_url(invite))
puts uri.to_s
end
end
I tried following in rails console,
#invite = Invitations.where(:id => 10)
helper.google_mail_encoded_url(#invite) #just to see the output....
This fails with NameError: undefined local variable or method `invitations_url' for main:Object. Is this the correct way to call and construct encoded url? Any help is appreciated.
That is because the routes are not loaded when you open a console.
To be able to use them run the following in your console:
> include Rails.application.reload_routes!.first.url_helpers
=> Object
> root_path
=> "/"

Stringify keys error when building a hash

I am getting a stringify_keys error.
Currently I am calling the following method which works perfectly:
def attributes
{
city: #content[1..20].strip,
streetname: #content[21..40].strip,
house_number: #content[41..46].strip.to_i
}
end
Now that I am refactoring my code, I need to build the hash from the ground up where the keys and values are populating the hash based on certain conditions (conditions are not written yet).
def attributes
test = {}
test["city"] = #content[1..20].strip
test["streetname"] = #content[21..40].strip
test["house_number"] = #content[41..46].strip.to_i
end
Now I am getting the stringify_keys error. I checked the docs for clues on how to build a hash but there isn't anything that could help me.
Where is the problem? If you need more code, please ask.
The key is symbol in your first piece of code, and you have to return test at last in your second piece of code.
def attributes
test = {}
test[:city] = #content[1..20].strip
test[:streetname] = #content[21..40].strip
test[:house_number] = #content[41..46].strip.to_i
test
end
In Rails with active support you can use symbolize_keys and stringify_keys look example:
=> hash = {"foo" => 1, 'baz' => 13}
=> {"foo"=>1, "baz"=>13}
=> hash.symbolize_keys
=> {:foo=>1, :baz=>13}
and back:
=> hash.symbolize_keys.stringify_keys
=> {"foo"=>1, "baz"=>13}

Why does it say I have the wrong number of arguments with RestClient Delete Method?

I have been using RestClient to call the API, so here I am calling the DELETE method to delete one image:
#mposter_D = params[:mposter_D]
#mid_D = params[:mid_D]
req = Hash.new
req['mov'] = #mid_D
puts "....#{req.to_json}"
resource_pos = RestClient::Resource.new
Rails.application.config.sta_url+"/movi/pos/"+#mposter_D
response_pos = resource_pos.delete req.to_json, :content_type => :json
After calling this I am getting this:
ArgumentError (wrong number of arguments (2 for 1)): in the last line of code
I was having the same problem. Apparently you cannot pass parameters from within the url when doing a delete method. (i.e. This will NOT work: http://example.com/resource?foo=bar&baz=qux)
If you need to add parameters to your delete request use the following format:
RestClient.delete 'http://example.com/resource', :params => {:foo => 'bar', :baz => 'qux'}
See the restclient docs section called Query Parameters
All I know about delete via rest_client is that, it takes only one parameter :
RestClient.delete 'http://demo.com/your_resourse'
you have to pass your url in that method. Thanks
Try this:
RestClient.delete 'http://foo.com/your_resourse_id?#{req.to_query}'
Or:
RestClient.delete 'http://foo.com/your_resourse_id?mov=' + #mid_D

Extracting URLs from a String that do not contain 'http'

I have the following 3 strings...
a = "The URL is www.google.com"
b = "The URL is google.com"
c = "The URL is http://www.google.com"
Ruby's URI extract method only returns the URL in the third string, because it contains the http part.
URI.extract(a)
=> []
URI.extract(b)
=> []
URI.extract(c)
=> ["http://www.google.com"]
How can I create a method to detect and return the URL in all 3 instances?
Use regular expressions :
Here is a basic one that should work for most cases :
/(https?:\/\/)?\w*\.\w+(\.\w+)*(\/\w+)*(\.\w*)?/.match( a ).to_s
This will only fetch the first url in the string and return a string.
There's no perfect solution to this problem: it's fraught with edge cases. However, you might be able to get tolerably good results using something like the regular expressions used by Twitter to extract URLs from tweets (stripping off the extra leading spaces is left as an exercise!):
require './regex.rb'
def extract_url(s)
s[Twitter::Regex[:valid_url]]
end
a = "The URL is www.google.com"
b = "The URL is google.com"
c = "The URL is http://www.google.com"
extract_url(a)
# => " www.google.com"
extract_url(b)
# => " google.com"
extract_url(c)
# => " http://www.google.com"
You seem to be satisfied with Sucrenoir's answer. The essence of Sucrenoir's answer is to identity a URL by assuming that it includes at least one period. if that is the case, Sucrenoir's regex can be simplified (not equivalently, but for the most part) to this:
string[/\S+\.\S+/]
This is something I used a while ago, hopefully it helps
validates :url, :format =>
{ :with => URI::regexp(%w(http https)), :message => "Not Valid URL" }
Pass it through that validation (I assume your using a database)
Try with this method. Hope it will work for you
def get_url(str)
arr = str.split(' ')
url = nil
arr.map {|arr_str| url = arr_str if arr_str.include?('.com')}
url
end
This is your example
get_url("The URL is www.google.com") #=> www.google.com
get_url("The URL is google.com") #=> google.com
get_url("The URL is http://www.google.com") #=> http://www.google.com

Resources