Undefined split method while using request.url - ruby-on-rails

I am trying to get the current url of my page and the parameters that go with it. When I manually put the url in, the undefined split method error does not occur. I have tried the following:
request.url
request.original_url
request.fullpath
adding in
id = request.original_url
and adding this function
def original_url
base_url + original_fullpath
end
What does currently work for me is below, but I cannot have the same url and parameters every time so this method won't work later on.
#parse current url
#what I would like below in comment
#id = request.original_url
url = "http://127.0.0.1:3000/reviews/new?id=2"
uri = URI.parse(url)
params = CGI.parse(uri.query)
id = params['id'].first
Any help or tips on if I'm missing something would be appreciated.

Had the same issue. The absence of query parameters in url was causing it.
url = "http://127.0.0.1:3000/reviews/new" # no query params
uri = URI.parse(url)
query = uri.query # nil
params = CGI.parse(query) # Undefined split Exception
This solves it:
uri = URI.parse(url)
if uri.query
params = CGI.parse(uri.query)
id = params['id'].first
end

Related

How can I get the value in a hash of the response of POST request on Ruby?

Now, I am working on a project using post request on Ruby.
I could get the response with the code below.
def send_param(param)
uri = URI.parse('https:~~~~~~~~~~~~')
https = Net::HTTP.new(uri.host, 443)
response = https.post(uri.path, param.to_query)
print response.body
end
And response.body looks like something like this
{"result": {"id":1111, "name": John}}
Now, I need to get the value of John above.
it will be something like this.
response["name"]
but I can't get the value as expected.
So I want you to help me, if you can.
Thank you.
You can parse it and fetch the result after it using the dig method.
def send_param(param)
uri = URI.parse('https:~~~~~~~~~~~~')
https = Net::HTTP.new(uri.host, 443)
response = https.post(uri.path, param.to_query)
JSON.parse(response.body)
end
result = send_param({})
result.dig('result', 'name')

How can I parse subpages of another website in Rails?

I'm creating a third-party web application of Last.fm and I'm having an issue with getting info about certain artist from them.
I have a method that parses data about some #{artist} from JSON:
artists_helper.rb
require 'net/http'
require 'json'
module ArtistsHelper
def about(artist)
artist = "?"
url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
end
end
If I change '?' to the artist name in that method I can successfully parse info about artist from JSON file of that artist. But for when I go the page e.g. http://localhost:3000/artists/Wild+Nothing I need the method 'about(artist)' to get the value 'Wild+Nothing' and parse the data for Wild Nothing from Last.fm's JSON file.
How can I tell the method 'about' that what stands after http://localhost:3000/artists/ is the required value?
In the routes, have a get route name that accepts a variable
get 'artists/:name', to: 'artists#about'
In the artists controller, have an about function:
def about
artist = params[:name]
url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response)
render json: response
end
and we are good to go to display the json on the view.
If you need the param in the helper, just pass params[:name] to the helper as a parameter.
about(param[:name]) #wherever you are calling this method in the controller or view
def about(artist)
url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
end

how to set array params in get request in rails

I use http get in rails. There are array params in the request. How can I encode the params into the request?
My code is like the next:
uri = URI(url)
uri.query = URI.encode_www_form(params) if params
resp = Net::HTTP.get_response(uri)
data = resp.body
When the params have an array, such as ids, the url will like "http://url?ids=1&ids=2", but I want to the url like "http://url?ids[]=1&ids[]=2".

JSON Post to rails

Hi guys I am having an issue and have read over a few topics on here and still can't solve my problem.
I am building an API on rails 4.0 and I have a method in my controller, shown bellow:
def jsonApiSearch
#firstName = params[:fn] #
#lastName = params[:ls] #
#eID = params[:custid] #
#prod = params[:prod] #
#classifation = params[:classifation] #
#status = params[:status] #
#specialty = params[:specialty] #
#aIDType = params[:aIDType] #
#aID = params[:aID] #
#address = params[:address] #
#city = params[:city] #
#state = params[:state] #
#country = params[:country] #
#postalCode = params[:pc] #
#role = params[:role]
#affiliation = params[:affill]
#priorityRank = params[:pr]
#strict = params[:strict]
#do something with the data
end
My Route File has the the following code:
post '/jsonsearch', to: 'api#jsonApiSearch'
So I then send a post request to the /jsonsearch endpoint.
I set the content type and the application/json, and then place this into the body as a this:
{"message": "Let's see if this works.","subject": "JSON via curl"}
I keep getting back a 422 Unprocessable Entity error.
Does anyone have any idea what I am doing wrong?
SOLVED:
Turns out that I left protect_from_forgery enabled, which was causing an issue. That is now fixed.
Turns out that I left protect_from_forgery enabled, which was causing an issue. It is turned on be default and will stop any non-get methods from working without some sort of authorization in place. Turn it off and your post will start working.

How to remove special characters from params hash?

I have one application with the following code:
quantity = 3
unit_types = ['MarineTrac','MotoTrac','MarineTrac']
airtime_plan = 'Monthly Airtime Plan'
url = "http://localhost:3000/home/create_units_from_paypal?quantity=#{quantity}&unit_types=#{unit_types}&airtime_plan=#{airtime_plan}"
begin
resp = Net::HTTP.get(URI.parse(URI.encode(url.strip)))
resp = JSON.parse(resp)
puts "resp is: #{resp}"
true
rescue => error
puts "Error: #{error}"
return nil
end
It sends data to my other application via the URL params query string. This is what the controller method of that other application looks like:
def create_units_from_paypal
quantity = params[:quantity]
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity.times do |index|
Unit.create! unit_type_id: UnitType.find_by_name(unit_types[index]),
airtime_plan_id: AirtimePlan.find_by_name(airtime_plan),
activation_state: ACTIVATION_STATES[:activated]
end
respond_to do |format|
format.json { render :json => {:status => "success"}}
end
end
I get this error:
<h1>
NoMethodError
in HomeController#create_units_from_paypal
</h1>
<pre>undefined method `times' for "3":String</pre>
<p><code>Rails.root: /Users/johnmerlino/Documents/github/my_app</code></p>
I tried using both raw and html_safe on the params[:quantity] and other params, but still I get the error. Note I had to use URI.encode(url) because URI.parse(url) returned bad uri probably because of the array of unit_types.
Change:
quantity.times do |index|
To:
quantity.to_i.times do |index|
The reason you are having this problem is because you are treating the params values as the types that you originally tried to send, but they are actually always going to be strings. Converting back to the expected 'type' solves your problem.
However, you have some more fundamental problems. Firstly, you are trying to send an array by simply formatting it to a string. However, this is not the format that the receiving application expects to translate back to an array. Secondly, there is duplication in your request - you don't need to specify a quantity. The length of the array itself is the quantity. A better method would be to build your url like this:
url = 'http://localhost:3000/home/create_units_from_paypal?'
url << URI.escape("airtime_plan=#{airtime_plan}") << "&"
url << unit_types.map{|ut| URI.escape "unit_types[]=#{ut}" }.join('&')
On the receiving side, you can do this:
def create_units_from_paypal
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity = unit_types.try(:length) || 0
#...

Resources