List all rails routes with http method associated - ruby-on-rails

I use this method to list all routes of my rails application:
def routes
Rails.application.routes.routes.collect do |r|
{ path: r.path.spec.to_s }
end
end
My result is:
[
{ :path => '/my/path/' },
{ :path => '/my/path2/' },
...
]
I want to obtain also the http method used for that route. How to do it?
Exploring class documentation I couldn't find it.
The expected result is:
[
{ :path => '/my/path/', :method => :get },
{ :path => '/my/path2/', :method => :post },
...
]
There is a way to obtain the http method associated to a route? (or a list of methods)

ActionDispatch::Journey::Route has a verb method which returns a RegExp:
You could try this:
def routes
Rails.application.routes.routes.collect do |r|
{ path: r.path.spec.to_s, :verb => r.verb.source[/[a-z]+/i].to_sym }
end
end

Related

Simple API wrapper with HTTParty

I' am trying to create a simple wrapper for skyscanner API. The problems is that when try to get the sessionKey, what I get is <HTTParty::Response:0x10 parsed_response=nil, #response=#<Net::HTTPUnsupportedMediaType 415 Unsupported Media Type readbody=true>. I am not sure what is that I am doing wrong. I am new to rails and I will appreciate any direction on how to solve this problem?. Thanks
require 'httparty'
class Skyscanner
include HTTParty
format :json
base_uri "http://partners.api.skyscanner.net/apiservices/pricing"
def self.find(originplace, destinationplace)
#options = { query:
{
:apiKey => "API_KEY",
:country => "US",
:currency => "USD",
:locale => "en-us",
:adults => 1,
:children => 0,
:infants => 0,
:originplace => originplacea,
:destinationplace => destinationplace,
:outbounddate => "2017-02-20",
:inbounddate => "2017-02-27",
:locationschema => "iata",
:cabinclass => "Economy"
}
}
#headers = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'}
#sessionkey_request = HTTParty.post("http://partners.api.skyscanner.net/apiservices/pricing/v1.0/",:body => #options,:headers => #headers)
puts #sessionkey_request.inspect
#get_sessionkey = #sessionkey_request.headers['location']
#sessionkey = #get_sessionkey.to_s().split('/').last
puts #sessionkey.inspect
end
end
If anyone have a better way of approaching this wrapper, please advice me on how to. Thanks

Custom JSON response with acts_as_taggable_on

I just implemented acts_as_taggable_on in my app and now I'm trying to trim my JSON response so it doesn't return everything for the Model in question. Here's what my as_json method looks like:
def as_json(options={})
super(:only => [:serial_number],
:include => {
:device_functions => { :only => [:can_scan, :can_brute] },
:scan_options => { :methods => :scan_ip_list}
}
)
end
Which currently returns:
{
"serial_number": "abcdefg12345",
"device_functions": [
{
"can_scan": true
}
],
"scan_options": [
{
"id": 1,
"device_id": 11,
"created_at": "2016-02-05T02:26:26.090Z",
"updated_at": "2016-02-05T02:26:26.090Z",
"scan_ip_list": [
"10.10.10.100-110",
"10.10.10.1"
]
}
]
}
I want to get rid of extra data that I don't need, such as id, device_id, created_at and updated_at now.
Also, using :only => worked find for the :device_functions response, but I had to use :methods => for :scan_options since I'm using acts_as_taggable_on... at least that's what I read and was the only option that returned something (I tried :only => and :include => as well but they returned an empty hash:
{
"serial_number": "abcdefg12345",
"device_functions": [
{
"can_scan": true
}
],
"scan_options": [
{}
]
}
You just need to add the :only option to your :scan_options hash too:
# ...
:scan_options => { :methods => :scan_ip_list, :only => :scan_ip_list }
Also, FWIW, you should probably merge into option in case you ever want to supply some of your own options, so:
# ...
super options.merge( :only => ...etc.

Multiply association to_json

I am working on this code:
render json: User.find(params[:id]).to_json(
:include =>
{
:user_quests => { :inlcude => { :quest }, :only => { :id } },
:user_skills
},
:except =>
{
:authentication_token,
:email
}
)
It results in a SyntaxError. The only working code I currently have is:
render json: User.find(params[:id]).to_json(
:include =>
[
:user_quests,
:user_skills
],
:except =>
[
:authentication_token,
:email
]
)
But I need to pass further parameters to only one of the associations to perform a nested include. The other one (:user_skills) should be fetched the same way as in the working code. How do I do that?
This code results in a syntax error, because you don't use collections properly. An array ([]) is a list of values, whereas a hashmap (or simply hash, {}) requires key-value pairs.
In to_json's context an array of associations:
[
:user_quests,
:user_skills
]
...is roughly equivalent to a hash of associations mapped to empty option hashes:
{
:user_quests => {},
:user_skills => {}
}
Having performed that transformation, you can selectively add options wherever you like.
Here it is solution which works for me and is compatible with Rails 4:
render json: User.find(params[:id]).as_json(
include:
{
user_quests:
{
include:
{
quest:
{
only: :_id
}
}
},
user_skills:
{
}
},
except: [:authentication_token, :email]
)

How to get CPC from Google Adwords Traffic Estimator Service in Ruby on Rails

I've been pouring over the google adwords api docs and I can't figure out how to format the selector to retrieve CPC information. I am using the google-adwords-api gem. Below is the method I'm working on inside my Adwords api module.
def self.traffic_estimator_service keyword
if !#adwords #If not already authenticated, do it first
Adwords.authenticate()
end
traffic_estimator_service = #adwords.service(:TrafficEstimatorService, API_VERSION)
selector = {
:xsi_type => 'KeywordEstimateRequest',
:match_type => 'EXACT',
:keyword => keyword
}
data = traffic_estimator_service.get(selector)
puts '---------------------------------'
puts data.inspect
puts '---------------------------------'
end
Of course I never get to the data2.inspect line because of the api errors. ie:
AdsCommon::Errors::UnexpectedParametersError (AdsCommon::Errors::UnexpectedParametersError: [:match_type]):
I've moved things around and tried multiple things inside the selector hash. Can someone give me an example of what this selector hash should look like?
selector = {
:campaign_estimate_requests => [
{
:xsi_type => 'CampaignEstimateRequest',
:ad_group_estimate_requests => {
:xsi_type => 'AdGroupEstimateRequest',
:keyword_estimate_requests => [
{
:max_cpc => {
:xsi_type => 'Money',
:micro_amount => 1_000_000
},
:xsi_type => 'KeywordEstimateRequest',
:keyword => {
:xsi_type => 'Keyword',
:text => keyword,
:match_type => 'EXACT'
}
}
]
}
}
]
}

Accessing a hashmap as an attribute of an object

I have an instance of an object that is created like this:
Example.create(:attrib0 => {
:attrib1 => value,
:attrib2 => [
{:attrib3 => value},
{:attrib4 => value}
]
})
How can I access :attrib4?
You should use serialize in your model, then you'll be able to return the hash correctly:
class SomeModel < ActiveRecord::Base
serialize :attrib0
end
Then the following should return the hash
hash = #model.attrib0
# => {:attrib1 => value, :attrib2 => [{:attrib3 => value}, {:attrib4 => value}]
# now to access attrib4 you need to get the attrib2 array,
# then grab attrib4 by its index:
hash[:attrib2][1]
# => {:attrib4 => value}
# or to get the value:
hash[:attrib2][1][:attrib4]
# => value
The above however can get quite complex and ugly, which is why I recommended creating another model for these attributes instead.
I think you should use nested attributes. Here's how it can be:
class Example
has_one :attrib0
accepts_nested_attributes_for :attrib0
end
params = { :attrib0 => { :attrib1 => value1,
:attrib2 => [ {:attrib3 => value3}, {:attrib4 => value4} ] }
}
example = Example.create(params[:attrib0])
example.attrib0.attrib1 #=> value1
example.attrib0.attrib2 #=> [ {:attrib3 => value3}, {:attrib4 => value4} ]
Using Ruby technique only:
h = {:attrib0 => {
:attrib1 => :value1,
:attrib2 => [
{:attrib3 => :value2},
{:attrib4 => :value3}
]
}}
p h[:attrib0][:attrib2].last[:attrib4] #=> :value3

Resources