How to add additional parameters to url? - encode url [closed] - ruby

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to add additional parameters to url from a hash? For example:
parameters = Hash.new
parameters["special"] = '25235'
parameters["code"] = 62346234
http: //127.0.0.1:8000/api/book_category/? %s parameters
require 'httparty'
require 'json'
response = HTTParty.get("http://127.0.0.1:8000/api/book_category/?")
json = JSON.parse(response.body)
puts json

The following should give you a valid URI which you can use for the json query.
require 'httparty'
parameters = {'special' => '512351235','code' => 6126236}
uri = URI.parse('http://127.0.0.1:8000/api/book_category/').tap do |uri|
uri.query = URI.encode_www_form parameters
end
uri.to_s
#=> "http://127.0.0.1:8000/api/book_category/?special=512351235&code=6126236"
The Tin Mans comment on your question is probably the better answer:
require 'httparty'
parameters = {'special' => '512351235','code' => 6126236}
response = HTTParty.get('http://127.0.0.1:8000/api/book_category/', :query => parameters)
json = JSON.parse(response.body)
puts json

The Addressable::URI class is an excellent replacement for the URI module in the standard library, and provides for just such manipulation of URI strings without having to build and escape the query string by hand.
This code demonstrates
require 'addressable/uri'
include Addressable
uri = URI.parse('http://127.0.0.1:8000/api/book_category/')
parametrs = {}
parametrs["special"] = '25235'
parametrs["code"] = 62346234
uri.query_values = parametrs
puts uri
output
http://127.0.0.1:8000/api/book_category/?code=62346234&special=25235

Related

regex to check url format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to check if my url format is correct, it has some AWS acces keys etc:
/https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=[.+]&Expires=[.+]&Signature=[.+]/.match(url)
^ something like this. Could you please help?
URI RFC specifies this regular expression for parsing URLs and URIs:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
You can also use the URI module from Ruby standard library:
require 'uri'
if url =~ /^#{URI::regexp(%w(http https))}$/
puts "it's an url alright"
else
puts "that's no url, that's a spaceship"
end
To check for the existence of "some AWS access keys etc" you can do:
require 'uri'
uri = URI.parse(url)
params = URI.decode_www_form(uri.query).to_h
if params.has_key?('AWSAccessKeyId')
unless params['AWSAccessKeyId'] =~ /\A[a-f0-9]{32}\z/
abort 'AWSAccessKeyId not valid'
end
else
abort 'AWSAccessKeyId required'
end
Of course you can just use regular expressions to parse them directly but it gets ugly because the order of the parameters may be different:
>> url = "https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=abcd12345&Expires=12345678&Signature=abcd"
>> matchdata = url.match(
/
\A
(?<scheme>http(?:s)?):\/\/
(?<host>[^\/]+)
(?<path>\/.+)\?
(?=.*(?:[\?\&]|\b)AWSAccessKeyId\=(?<aws_access_key_id>[a-f0-9]{1,32}))
(?=.*(?:[\?\&]|\b)Expires=(?<expires>[0-9]+))
/x
)
=> #<MatchData "https://bucket.s3.amazonaws.com/path/file.txt?"
scheme:"https"
host:"bucket.s3.amazonaws.com"
path:"/path/file.txt"
aws_access_key_id:"abcd12345"
expires:"12345678">
>> matchdata[:aws_access_key_id]
# => "abcd12345"
This uses
The positive lookahead of regex : (?=..) to ignore parameter
order
Ruby's regex named captures (?<param_name>.*) to identify
the params from match data
Non capturing groupings (?abcd|efgh)
The matcher (?[\&\?]|\b) to handle Expires=..., ?Expires=... or &Expires=...
And finally the /x free spacing modifier to
allow nicer formatting
We need a url to work with:
url = "/https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=somestuff&Expires=somemorestuff&Signature=evenmorestuff"
We also need to escape a bunch of stuff and do some non-greedy matching(.+?):
/https:\/\/bucket.s3.amazonaws.com\/path\/file\.txt\?AWSAccessKeyId=.+?&Expires=.+?&Signature=.+/.match(url)
=> #<MatchData "https://bucket.s3.amazonaws.com/path/file.txt?AWSAccessKeyId=somestuff&Expires=somemorestuff&Signature=evenmorestuff">

Ruby: remove from the string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the URL http://localhost:3000/en/invest_offers?utf8=blahblahblah. How can I get ?utf8=blahblahblah part of the URL? Thanks!
Do as below using URI::Generic.query:
require 'uri'
URI("http://localhost:3000/en/invest_offers?utf8=blahblahblah").query
# => "utf8=blahblahblah"
Use URI::parse, URI::Generic#query:
require 'uri'
url = 'http://localhost:3000/en/invest_offers?utf8=blahblahblah'
URI.parse(url)
# => #<URI::HTTP:0x0000000213aae0 URL:http://localhost:3000/en/invest_offers?utf8=blahblahblah>
URI.parse(url).query
# => "utf8=blahblahblah"
Do the following:--
require 'uri'
url = 'http://localhost:3000/en/invest_offers?utf8=blahblahblah'
parsed_url = URI.parse(url)
if you just want to get string query part like "utf8=blahblahblah"
you should do
parsed_url.query
if you want get "blahblahblah",
you should just do
params["utf8"]
or else
p = CGI.parse(parsed_url.query)
# p is now {"utf8"=>["blahblahblah"]}
p["utf8"].first
#=> "blahblahblah"

Code not working after little change [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm beginner in programming, I changed my code a little bit so that I can execute some def from the command line. After that change I got an error, but first my code:
require 'faraday'
#conn = Faraday.new 'https://zombost.de:8673/rest', :ssl => {:verify => false}
#uid = '8978'
def certificate
res = conn.get do |request|
request.url "acc/#{#uid}/cere"
end
end
def suchen(input)
#suche = input
#res = #conn.get do |request|
request.url "acc/?search=#{#suche}"
end
end
puts #res.body
Then I wrote into the console:
ruby prog.rb suchen(jumbo)
So, somehow i get the error:
Undefined method body for Nilclass
You're not invoking either of your methods, so #res is never assigned to.
#res evaluates to nil, so you're invoking nil.body.
RE: Your update:
ruby prog.rb suchen(jumbo)
That isn't how you invoke a method. You have to call it from within the source file. All you're doing is passing an argument to your script, which will be a simple string available in the ARGV array.
RE: Your comment:
It should go without saying that the solution is to actually invoke your method.
You can call the methods from the command line. Ruby has a function eval which evaluates a string. You can eval the command line argument strings.
Here's how. Change the line puts #res.body to
str = ARGV[1]
eval(ARGV[0])
puts #res.body
then run your program like so
$ ruby prog.rb suchen\(str\) jumbo

Using Net::HTTP, how can you store the url that you queried?

require 'net/http'
require 'uri'
#url = 'http://foobar.com'
#query_string = {foo1: 'bar1', foo2: 'bar2'}
#post_data = Net::HTTP.post_form(URI.parse(#url), #query_string)
#request = # ? How can I get the request URL + query?
#response = #post_data.body
Does anyone know how you can get the actual URL that you queried, not just the response?
i.e. I want to store this in a variable to record what was sent:
http://foobar.com?foo1=bar1&foo2=bar2
It's not getting it from the response itself (I don't think there is a way to do this with net/http), but you can get the variable you want by doing this:
#request = URI.parse(#url).tap{|x|x.query=URI.encode_www_form(#query_string)}.to_s
# => "http://foobar.com?foo1=bar1&foo2=bar2"
I believe you want to look into Ruby's URI Module:
http://www.ruby-doc.org/stdlib-2.0/libdoc/uri/rdoc/URI.html
Not sure, but you could probably get away with something like:
query_string = URI.encode_www_form(#query_string).to_s
record_of_uri = "#{#url}/?#{query_string}"
Noting that a post request doesn't send it's params in the url, to compose #request as described use:
#request = URI.escape(#url + '?' + URI.encode_www_form(#query_string))

How Do I search Twitter for a word with Ruby?

I have written code in Ruby that will display the timeline for a specific user. I would like to write code to be able to just search twitter to just find every user that has mentioned a word. My code is currently:
require 'rubygems'
require 'oauth'
require 'json'
# Now you will fetch /1.1/statuses/user_timeline.json,
# returns a list of public Tweets from the specified
# account.
baseurl = "https://api.twitter.com"
path = "/1.1/statuses/user_timeline.json"
query = URI.encode_www_form(
"q" => "Obama"
)
address = URI("#{baseurl}#{path}?#{query}")
request = Net::HTTP::Get.new address.request_uri
# Print data about a list of Tweets
def print_timeline(tweets)
tweets.each do |tweet|
require 'date'
d = DateTime.parse(tweet['created_at'])
puts " #{tweet['text'].delete ","} , #{d.strftime('%d.%m.%y')} , #{tweet['user']['name']}, #{tweet['id']}"
end
end
# Set up HTTP.
http = Net::HTTP.new address.host, address.port
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# If you entered your credentials in the first
# exercise, no need to enter them again here. The
# ||= operator will only assign these values if
# they are not already set.
consumer_key = OAuth::Consumer.new(
"")
access_token = OAuth::Token.new(
"")
# Issue the request.
request.oauth! http, consumer_key, access_token
http.start
response = http.request request
# Parse and print the Tweet if the response code was 200
tweets = nil
puts "Text,Date,Name,id"
if response.code == '200' then
tweets = JSON.parse(response.body)
print_timeline(tweets)
end
nil
How would I possibly change this code to search all of twitter for a specific word?
The easiest approach would be to use 'Twitter' gem. Refer to this Link for more information and the result type of the search results. Once you have all the correct authorization attribute in place (oAuth-Token,oAuth-secret, etc) you should be able to search as
Twitter.search('Obama')
or
Twitter.search('Obama', options = {})
Let us know, if that worked for you or not.
p.s. - Please mark the post as answered if it helped you. Else put a comment back with what is missing.
The Twitter API suggests the URI your should be using for global search is https://api.twitter.com/1.1/search/tweets.json and this means:
Your base_url component would be https://api.twitter.com
Your path component would be /1.1/search/tweets.json
Your query component would be the text you are searching for.
The query part takes a lot of values depending upon the API spec. Refer to the specification and you can change it as per your requirement.
Tip: Try to use irb (I'd recommend pry) REPL which makes it a lot easier to explore APIs. Also, checkout the Faraday gem which can be easier to use than the default HTTP library in Ruby IMO.

Resources