Running GET Request Through Rails on separate thread - ruby-on-rails

I have a get request that retrieves JSON needed for graphs to display on a page. I'd do it in JQuery, but because of the API that I am using, it is not possible -- so I have to do it in rails.
I'm wondering this: If I run the get request on a separate thread in the page's action, can the variable then be passed to javascript after the page loads? I'm not sure how threading works in rails.
Would something like this work:
Thread.new do
url = URI.parse("http://api.steampowered.com/IDOTAMatch_570/GetMatchHistory/v001/?key=#{ENV['STEAM_WEB_API_KEY']}&account_id=#{id}&matches_requested=25&game_mode=1234516&format=json")
res = Net::HTTP::get(url)
matchlist = JSON.parse(res)
matches = []
if matchlist['result'] == 1 then
matchlist['result']['matches'].each do |match|
matches.push(GetMatchWin(match['match_id']))
end
end
def GetMatchWin(match_id, id)
match_data = matchlist["result"]["matches"].select {|m| m["match_id"] == match_id}
end
end
end
Given that the above code is in a helper file, and it then gets called in the action for the controller as such:
def index
if not session.key?(:current_user) then
redirect_to root_path
else
gon.winlossdata = GetMatchHistoryRawData(session[:current_user][:uid32])
end
end
The "gon" part is just a gem to pass data to javascript.

Related

Send parameters from controller to model rails

I'm working on the Meetup Api.
I would like to save some conferences from the API into my database.
The saving conferences depend of the parameters passing into the view to the controller :
<%= link_to 'See conferences', conferences_path(:title => "ParisRb")%> |
Then I call the good method to look for the good conferences (comparing to the params) among all the one received from the api.
I would like the methods to be very generic and to be able to save any conferences not only 'ParisRb'.
So I modify all my methods in this goal but there is one I can not modify, I don't know how.
This is my whole code. The one I'd like to modify is self.conferences_filter(data) wich is supposed to receive the params from the controller instead of 'ParisRb'. But I know that passing parameters from the controller to the model is not a good practice. So any idea is welcome :)
lib/api_meetup.rb
class ApiMeetup
BASE_URI = "https://api.meetup.com"
def events(urlname)
HTTParty.get(BASE_URI + "/#{urlname}/events")
end
end
conferences_controller.rb
def index
#call to the API
response = ApiMeetup.new.events(params[:title])
api_data = JSON.parse(response.body)
filtered_conferences = Conference.conferences_filter(api_data)
conferences = Conference.save_conferences_from_api(filtered_conferences)
#conferences = conferences.current_conferences
end
conference.rb
#Keep only requested conferences
def self.conferences_filter(data)
requested_conferences = []
data.each do |event|
if event["name"].include?('ParisRb') #This should receive params[:title] instead of 'ParisRb'
requested_conferences << event
end
end
requested_conferences
end
#Save requested conferences from the Meetup API
def self.save_conferences_from_api(conferences)
# data = data_from_api
conferences.each do |line|
conference = self.new
conference.title = line['name']
conference.date = format_date(line['time'])
conference.url = line['link']
if conference.valid?
conference.save
end
end
self.all
end
That's was actually quite obvious.
I just needed to pass to argument to my method :
filtered_conferences = Conference.conferences_filter(api_data, params[:title])
#Keep only requested conferences
def self.conferences_filter(data, title)
requested_conferences = []
data.each do |event|
if event["name"].include?(title)
requested_conferences << event
end
end
requested_conferences
end

instance variable is null in show method rails

I have developed a rest api, in which I am using instance variable. there are two methods index and show, I have created a instance variable in index method which I want to use in show method on user request.
But i do not know, the instance variable is null in show method, I am sure that I am not initaializing the class anywhere explicitly. Code snippet is below
def index
data = Hash.new
#temp = DataHelper.filter(params)
if(params[:type] == 'Student')
json = DataStudenteHelper.sfilter(params, #temp)
else
json = EmpDataHelper.empfilter(params, #temp)
end
puts data.to_json
render :status => :ok, :json => json
end
def show
puts #temp.to_json // null here
if (params[:type] == 'Student')
#h = StudentHelpHelper.shfilter(params, #temp)
else
#h = EmpDataHelpHelper.emphfilter(params, #temp)
end
render :status => :ok, :json => #h
end
in the methods sfilter, empfilter, shfilter and emphfilter, I am just processing #temp but it is null in show method...
So any idea what is the issue thanks...
You seem to be assuming that a controller will persist across multiple requests so that you can initialize a variable in an index action and still be able to use it in a subsequent show action. This is not the case. Rails controller instances exist only for the duration of the request they serve. You cannot keep values in memory like this across requests (nor should you want to as that would require that requests be served in a particular order and would leak data between different users).
If you need to initialize this variable before all of your controller actions consider using a before filter. In your case this probably means that you also need to supply the data you need in the params of the show action.

Spree error when using decorator with the original code

Need a little help over here :-)
I'm trying to extend the Order class using a decorator, but I get an error back, even when I use the exactly same code from source. For example:
order_decorator.rb (the method is exactly like the source, I'm just using a decorator)
Spree::Order.class_eval do
def update_from_params(params, permitted_params, request_env = {})
success = false
#updating_params = params
run_callbacks :updating_from_params do
attributes = #updating_params[:order] ? #updating_params[:order].permit(permitted_params).delete_if { |k,v| v.nil? } : {}
# Set existing card after setting permitted parameters because
# rails would slice parameters containg ruby objects, apparently
existing_card_id = #updating_params[:order] ? #updating_params[:order][:existing_card] : nil
if existing_card_id.present?
credit_card = CreditCard.find existing_card_id
if credit_card.user_id != self.user_id || credit_card.user_id.blank?
raise Core::GatewayError.new Spree.t(:invalid_credit_card)
end
credit_card.verification_value = params[:cvc_confirm] if params[:cvc_confirm].present?
attributes[:payments_attributes].first[:source] = credit_card
attributes[:payments_attributes].first[:payment_method_id] = credit_card.payment_method_id
attributes[:payments_attributes].first.delete :source_attributes
end
if attributes[:payments_attributes]
attributes[:payments_attributes].first[:request_env] = request_env
end
success = self.update_attributes(attributes)
set_shipments_cost if self.shipments.any?
end
#updating_params = nil
success
end
end
When I run this code, spree never finds #updating_params[:order][:existing_card], even when I select an existing card. Because of that, I can never complete the transaction using a pre-existent card and bogus gateway(gives me empty blanks errors instead).
I tried to bind the method in order_decorator.rb using pry and noticed that the [:existing_card] is actuality at #updating_params' level and not at #updating_params[:order]'s level.
When I delete the decorator, the original code just works fine.
Could somebody explain to me what is wrong with my code?
Thanks,
The method you want to redefine is not really the method of the Order class. It is the method that are mixed by Checkout module within the Order class.
You can see it here: https://github.com/spree/spree/blob/master/core/app/models/spree/order/checkout.rb
Try to do what you want this way:
Create file app/models/spree/order/checkout.rb with code
Spree::Order::Checkout.class_eval do
def self.included(klass)
super
klass.class_eval do
def update_from_params(params, permitted_params, request_env = {})
...
...
...
end
end
end
end

Capybara + remote form request

I have a form that I'm testing using Capybara. This form's URL goes to my Braintree sandbox, although I suspect the problem would happen for any remote URL. When Capybara clicks the submit button for the form, the request is routed to the dummy application rather than the remote service.
Here's an example app that reproduces this issue: https://github.com/radar/capybara_remote. Run bundle exec ruby test/form_test.rb and the test will pass, which is not what I'd typically expect.
Why does this happen and is this behaviour that I can rely on always happening?
Mario Visic points out this description in the Capybara documentation:
Furthermore, you cannot use the RackTest driver to test a remote application, or to access remote URLs (e.g., redirects to external sites, external APIs, or OAuth services) that your application might interact with.
But I wanted to know why, so I source dived. Here's my findings:
lib/capybara/node/actions.rb
def click_button(locator)
find(:button, locator).click
end
I don't care about the find here because that's working. It's the click that's more interesting. That method is defined like this:
lib/capybara/node/element.rb
def click
wait_until { base.click }
end
I don't know what base is, but I see the method is defined twice more in lib/capybara/rack_test/node.rb and lib/capybara/selenium/node.rb. The tests are using Rack::Test and not Selenium, so it's probably the former:
lib/capybara/rack_test/node.rb
def click
if tag_name == 'a'
method = self["data-method"] if driver.options[:respect_data_method]
method ||= :get
driver.follow(method, self[:href].to_s)
elsif (tag_name == 'input' and %w(submit image).include?(type)) or
((tag_name == 'button') and type.nil? or type == "submit")
Capybara::RackTest::Form.new(driver, form).submit(self)
end
end
The tag_name is probably not a link -- because it's a button we're clicking -- so it falls to the elsif. It's definitely an input tag with type == "submit", so then let's see what Capybara::RackTest::Form does:
lib/capybara/rack_test/form.rb
def submit(button)
driver.submit(method, native['action'].to_s, params(button))
end
Ok then. driver is probably the Rack::Test driver for Capybara. What's that doing?
lib/capybara/rack_test/driver.rb
def submit(method, path, attributes)
browser.submit(method, path, attributes)
end
What is this mysterious browser? It's defined in the same file thankfully:
def browser
#browser ||= Capybara::RackTest::Browser.new(self)
end
Let's look at what this class's submit method does.
lib/capybara/rack_test/browser.rb
def submit(method, path, attributes)
path = request_path if not path or path.empty?
process_and_follow_redirects(method, path, attributes, {'HTTP_REFERER' => current_url})
end
process_and_follow_redirects does what it says on the box:
def process_and_follow_redirects(method, path, attributes = {}, env = {})
process(method, path, attributes, env)
5.times do
process(:get, last_response["Location"], {}, env) if last_response.redirect?
end
raise Capybara::InfiniteRedirectError, "redirected more than 5 times, check for infinite redirects." if last_response.redirect?
end
So does process:
def process(method, path, attributes = {}, env = {})
new_uri = URI.parse(path)
method.downcase! unless method.is_a? Symbol
if new_uri.host
#current_host = "#{new_uri.scheme}://#{new_uri.host}"
#current_host << ":#{new_uri.port}" if new_uri.port != new_uri.default_port
end
if new_uri.relative?
if path.start_with?('?')
path = request_path + path
elsif not path.start_with?('/')
path = request_path.sub(%r(/[^/]*$), '/') + path
end
path = current_host + path
end
reset_cache!
send(method, path, attributes, env.merge(options[:headers] || {}))
end
Time to break out the debugger and see what method is here. Sticking a binding.pry before the final line in that method, and a require 'pry' in the test. It turns out method is :post and, for interest's sake, new_uri is a URI object with our remote form's URL.
Where's this post method coming from? method(:post).source_location tells me:
["/Users/ryan/.rbenv/versions/1.9.3-p374/lib/ruby/1.9.1/forwardable.rb", 199]
That doesn't seem right... Does Capybara have a def post somewhere?
capybara (master)★ack "def post"
lib/capybara/rack_test/driver.rb
76: def post(*args, &block); browser.post(*args, &block); end
Cool. We know that browser is aCapybara::RackTest::Browser` object. The class beginning gives the next hint:
class Capybara::RackTest::Browser
include ::Rack::Test::Methods
I know that Rack::Test::Methods comes with a post method. Time to dive into that gem.
lib/rack/test.rb
def post(uri, params = {}, env = {}, &block)
env = env_for(uri, env.merge(:method => "POST", :params => params))
process_request(uri, env, &block)
end
Ignoring env_for for the time being, what does process_request do?
lib/rack/test.rb
def process_request(uri, env)
uri = URI.parse(uri)
uri.host ||= #default_host
#rack_mock_session.request(uri, env)
if retry_with_digest_auth?(env)
auth_env = env.merge({
"HTTP_AUTHORIZATION" => digest_auth_header,
"rack-test.digest_auth_retry" => true
})
auth_env.delete('rack.request')
process_request(uri.path, auth_env)
else
yield last_response if block_given?
last_response
end
end
Hey, #rack_mock_session looks interesting. Where's that defined?
rack-test (master)★ack "#rack_mock_session ="
lib/rack/test.rb
40: #rack_mock_session = mock_session
42: #rack_mock_session = MockSession.new(mock_session)
In two places, very close to each other. What's on and around these lines?
def initialize(mock_session)
#headers = {}
if mock_session.is_a?(MockSession)
#rack_mock_session = mock_session
else
#rack_mock_session = MockSession.new(mock_session)
end
#default_host = #rack_mock_session.default_host
end
Ok then, so it ensures it is a MockSession object. What's MockSession and how is its request method defined?
def request(uri, env)
env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
#last_request = Rack::Request.new(env)
status, headers, body = #app.call(#last_request.env)
headers["Referer"] = env["HTTP_REFERER"] || ""
#last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
body.close if body.respond_to?(:close)
cookie_jar.merge(last_response.headers["Set-Cookie"], uri)
#after_request.each { |hook| hook.call }
if #last_response.respond_to?(:finish)
#last_response.finish
else
#last_response
end
end
I'm going to go right ahead here and assume #app is the Rack application stack. By calling the call method, the request is routed directly to this stack, rather going out to the world.
I conclude that this behaviour looks like its intentional and that I can indeed rely on it being that way.

Rails Builder::XmlMarkup for Web Service - Repetitive Section

I am using Builder to construct XML messages being sent to a WebService. Each of the different methods require different xml but they all have a set of common elements to start of the request (mostly account authentication stuff). Is there any way to do it in a DRY way? Here is my code for constructing a change pass phrase request:
# XML REQUEST SETUP
msg = Builder::XmlMarkup.new(:indent=>2)
query = {}
test_hsh = self.testmode ? {:Test => "YES"} : {}
# BUILD THE REQUEST
query[:changePassPhraseRequestXML] = msg.ChangePassPhraseRequest(test_hsh) do |asr|
asr.RequesterID APP_CONFIG[:endicia_partner_id].to_s
asr.RequestID "1"
asr.CertifiedIntermediary do |ci|
ci.AccountID APP_CONFIG[:endicia_account_number].to_s
ci.PassPhrase APP_CONFIG[:endicia_passphrase].to_s
end
asr.NewPassPhrase APP_CONFIG[:passphrase].to_s
end
Basically all the elements except the NewPassPhrase one are common to all (or most) requests. Right now I copy the same code over and over but I don't like this at all.
Any ideas on Dry'ing it up?
As soon as I posted this. I had an idea, put the first set into their own method. Duh!
def account_status(options = {})
# XML REQUEST SETUP
msg = Builder::XmlMarkup.new(:indent=>2)
query = {}
test_hsh = self.testmode ? {:Test => "YES"} : {}
# BUILD THE REQUEST
query[:changePassPhraseRequestXML] = msg.ChangePassPhraseRequest(test_hsh) do |asr|
self.add_authentication_elements(asr)
asr.NewPassPhrase APP_CONFIG[:new_pass_phrase].to_s
end
end
def add_authentication_elements(parent_node)
parent_node.RequesterID self.endicia_partner_id.to_s
parent_node.RequestID "1"
parent_node.CertifiedIntermediary do |ci|
ci.AccountID self.endicia_account_number.to_s
ci.PassPhrase self.endicia_passphrase.to_s
end
end
Works great! Another option would of course be to extend Builder in some way but this is nice and simple.

Resources