how to set search parameter in google-api-ruby-client - ruby

in order to retrieve the contents of a folder I have to use the following url
https://www.googleapis.com/drive/v2/files?q='root'
so I thought it should be working by passing an additional parameter
#client.execute(
:api_method => #drive.files.list ,
:parameters =>{q=> "title='root'" })
But this does not work
An error occurred: {"errors"=>[{"domain"=>"global", "reason"=>"invalid", "message"=>"Invalid Value", "locationType"=>"parameter", "location"=>"q"}], "code"=>400, "message"=>"Invalid Value"}
This is pretty obvious when I see the request uri
https://www.googleapis.com/drive/v2/files?q=title%253D%27levelA%27
My first attempt was to user URI.encode "title='root'" which does not work neither.
I really dont know how I could keep the single quotes ?
Best,
Philip
p.s.: a link to the mentioned gem http://rubydoc.info/github/google/google-api-ruby-client/frames

ok, now I found a working solution, even though it is a very cumbersome one.
search = CGI.escape("q='root'")
u.query = search
u= Addressable::URI.parse "https://www.googleapis.com/drive/v2/files"
req=Google::APIClient::Request.new(:uri=> u)
client.execute req
I hope this helps someone..

Related

Why is this lighttpd url rewrite not workng?

I have the following mod_rewrite code for lighttpd, but it does not properly foreward the user:
$SERVER["socket"] == ":3041" {
server.document-root = server_root + "/paste"
url.rewrite-once = ( "^/([^/\.]+)/?$" => "?page=paste&id=$1")
}
It should turn the url domain.com/H839jec into domain.com/index.php?page=paste&id=H839jec however it is not doing that, instead it is redirecting everything to domain.com. I dont know much about mod_rewrite and would appreciate some input on why it is doing this.
Use the following :
url.rewrite-once = ("^/(.*)$" => "/?page=paste&id=$1")
I don't know the exact issue in your code, but first the regex looks unnecessarily complicated and may not match what you expected it to match, and second you're redirecting to a query string where as I would expect you still need to redirect to a valid path before the query string, that's why I redirect to /?page... instead of just ?page....

Stuck with HTTP GET authentication in Ruby

I am trying to write short script to do HTTP authentication using GET request
This makes GET request.
def try_login(u, p)
path1 = '/index.php'
path2 = '?uuser=#{myuser}&ppass=#{mypass}'
r = send_request_raw({
'URI' => "#{path1}#{path2}",
'method' => 'GET'
})
...continued...
But this code does not work because error says:
undefined local variable or method `myuser'
--> Basically I am trying to send one (1) GET request with login parameters, and the app responds with a specific data. And I do not know how to put placeholders for user and pass in this GET request.
...
Next, I am checking the HTTP response. Response comes in as JSON mime like this:
Success response
{"param1":1,"param2"="Auth Success","menu":0,"userdesc":"My User","user":"uuser","pass":"ppass","check":"success"}
Fail response
{"param1":-1,"param2"="Auth Fail","check":"fail"}
--> How can I check the response body for this kind of data.
I have been trying all day now, but stuck totally. Please advice.
Edit:
I do not understand why some one down voted this question saying little to no research on my part. Until before yesterday morning, I had absolutely zero idea about ruby code & working with it. And then I spent numerous hours looking at many different examples, making my script and testing it out. When it still didn't work, I asked my question here. Please, if you still want to down vote, do it but please, at least share some pointers to solve this as well.
def try_login(u, p)
path1 = '/index.php'
path2 = '?uuser=#{myuser}&ppass=#{mypass}'
r = send_request_raw({
'URI' => "#{path1}#{path2}",
'method' => 'GET'
})
...continued...
Should be:
def try_login(u, p)
path1 = '/index.php'
path2 = "?uuser=#{u}&ppass=#{p}"
r = send_request_raw({
'URI' => "#{path1}#{path2}",
'method' => 'GET'
})
...continued...
For parsing JSON in Ruby, I would recommend you take a look at this answer to another question.
Edit: The reason try_login(u, p) isn't working as you would expect is because Ruby does not do string interpolation for single quoted (') strings. Additionally, myuser and mypass do not appear to be the correct variables.

How do I get just the sitename from url in ruby?

I have a url such as:
http://www.relevantmagazine.com/life/relationship/blog/23317-pursuing-singleness
And would like to extract just relevantmagazine from it.
Currently I have:
#urlroot = URI.parse(#link.url).host
But it returns www.relevantmagazine.com can anyone help me?
Using a gem for this might be overkill, but anyway: There's a handy gem called domainatrix that can extract the sitename for your while dealing with things like two element top-level domains and more.
url = Domainatrix.parse("http://www.pauldix.net")
url.url # => "http://www.pauldix.net" (the original url)
url.public_suffix # => "net"
url.domain # => "pauldix"
url.canonical # => "net.pauldix"
url = Domainatrix.parse("http://foo.bar.pauldix.co.uk/asdf.html?q=arg")
url.public_suffix # => "co.uk"
url.domain # => "pauldix"
url.subdomain # => "foo.bar"
url.path # => "/asdf.html?q=arg"
url.canonical # => "uk.co.pauldix.bar.foo/asdf.html?q=arg"
how about
#urlroot = URI.parse(#link.url).host.gsub("www.", "").split(".")[0]
Try this regular expression:
regex = %r{http://[w]*[\.]*[^/|$]*}
If you had the following url strings, it gives the following:
url = 'http://www.google.com/?q=blah'
url.scan(regex) => ["http://www.google.com"]
url = 'http://google.com/?q=blah'
url.scan(regex) => ["http://google.com"]
url = 'http://google.com'
url.scan(regex) => ["http://google.com"]
url = 'http://foo.bar.pauldix.co.uk/asdf.html?q=arg'
url.scan(regex) => ["http://foo.bar.pauldix.co.uk"]
It's not perfect, but it will strip out everything but the prefix and the host name. You can then easily clean up the prefix with some other code knowing now you only need to look for an http:// or http://www. at the beginning of the string. Another thought is you may need to tweak the regex I gave you a little if you are also going to parse https://. I hope this helps you get started!
Edit:
I reread the question, and realized my answer doesn't really do what you asked. I suppose it might be helpful to know if you know if the urls you're parsing will have a set format like always have the www. If it does, you could use a regular expression that extracts everything between the first and second period in the url. If not, perhaps you could tweak my regex so that it's everything between the / or www. and the first period. That might be the easiest way to get just the site name with none of the www. or the .com or .au.uk and such.
Revised regex:
regex = %r{http://[w]*[\.]*[^\.]*}
url = 'http://foo.bar.pauldix.co.uk/asdf.html?q=arg'
url.scan(regex) => ["http://foo"]
It'll be weird. If you use the regex stuff, you'll probably have to do it incrementally to clean up the url to extract the part you want.
Maybe you can just split it?
URI.parse(#link.url).host.split('.')[1]
Keep in mind that some registered domains may have more than one component to the registered country domain, like .co.uk or .co.jp or .com.au for example.
I found the answer inspired by tadman's answer and the answer in another question
#urlroot = URI.parse(item.url).host
#urlroot = #urlroot.start_with?('www.') ? #urlroot[4..-1] : #urlroot
#urlroot = #urlroot.split('.')[0]
First line get the host, second line gets removes the www. if they is one and third line get everything before the next dot.

How to print validation error outside of field constructor in Play framework 2

How can I show a validation error for a form field outside of a field constructor in Play framework 2? Here is what I tried:
#eventForm.("name").error.message
And I get this error:
value message is not a member of Option[play.api.data.FormError]
I'm confused because in the api docs it says message is a member of FormError. Also this works fine for global errors:
#eventForm.globalError.message
You can get a better grasp of it checking Form's sourcecode here
Form defines an apply method:
def apply(key: String): Field = Field(
this,
key,
constraints.get(key).getOrElse(Nil),
formats.get(key),
errors.collect { case e if e.key == key => e },
data.get(key))
That, as said in the doc, returns any field, even if it doesn't exist. And a Field has an errors member which returns a Seq[FormError]:
So, you could do something like that (for the Seq[FormError]):
eventForm("name").errors.foreach { error =>
<div>#error.message</div>
}
Or (for the Option[FormError])
eventForm("name").error.map { error =>
<div>#error.message</div>
}
Or, you could use Form errors:
def errors(key: String): Seq[FormError] = errors.filter(_.key == key)
And get all errors of a given key. Like this (for the Seq[FormError]):
eventForm.errors("name").foreach { error =>
<div>#error.message</div>
}
Or (for the Option[FormError])
eventForm.error("name").map { error =>
<div>#error.message</div>
}
If you want more details, check the source code. It's well written and well commented.
Cheers!
EDIT:
As biesior commented: to show human readable pretty messages with different languages you have to check how play works I18N out here
To be thorough you're probably going to have to deal with I18N. It's not hard at all to get it all working.
After reading the documentation you may still find yourself a bit consufed. I'll give you a little push. Add a messages file to your conf folder and you can copy its content from here. That way you'll have more control over the default messages. Now, in your view, you should be able to do something like that:
eventForm.errors("name").foreach { error =>
<div>#Messages(error.message, error.args: _*)</div>
}
For instance, if error.message were error.invalid it would show the message previously defined in the conf/messages file Invalid value. args define some arguments that your error message may handle. For instance, if you were handling an error.min, an arg could be the minimum value required. In your message you just have to follow the {n} pattern, where n is the order of your argument.
Of course, you're able to define your own messages like that:
error.futureBirthday=Are you sure you're born in the future? Oowww hay, we got ourselves a time traveler!
And in your controller you could check your form like that (just one line of code to show you the feeling of it)
"year" -> number.verifying("error.furtureBirthday", number <= 2012) // 2012 being the current year
If you want to play around with languages, just follow the documentation.
Cheers, again!
As you said yourself, message is a member of FormError, but you have an Option[FormError]. You could use
eventForm("name").error.map(_.message).getOrElse("")
That gives you the message, if there is an error, and "" if there isn't.

ruby-aaws Get specific Album

I am trying to get a specific music cd from Amazon using ruby-aaws.
il = ItemSearch.new( 'Music', { 'Artist' => artist_title,
'Title' => album_name } )
rg = ResponseGroup.new( 'Large' )
req = Request.new(AMAZON_KEY_ID, AMAZON_ASSOCIATES_ID, 'de')
resp = req.search( il, rg, 5)
But this fails. It only seems to work when I search for artist or title, not both at the same time. What am I making wrong? If I construct the url by hand, it works prefectly, but I really don't want to parse the xml manually myself.
I've had a bit of a look at the code of ruby-aaws. It looks like you should be able to set $DEBUG to true before calling any of the ruby-aaws methods/classes and see what URLs are being requested. If there are any discrepancies between your handcrafted URL and the one being generated by ruby-aaws, this might give you some clues.
I just tried this use-case with the latest version of ruby-aaws and it works just fine.
I used the following for the ItemSearch (with the same code you posted initially):
il = ItemSearch.new( 'Music', { 'Artist'=>'The Smiths', 'Title'=>'Hatful' })
and got good results back as I would expect. Please try again and see if perhaps the latest ruby-aaws has ironed out a wrinkle which was stopping you.

Resources