Related
I'm trying to figure out why the console is outputting objects in a stacktrace as if they were inspected.
I'm using the api version of rails 6. So far I've tried lowering the log level, setting config.consider_all_requests_local = false and attempted using minitest-reporters but nothing has worked.
Here's an example result from running rails t
rails test test/controllers/players_controller_test.rb:21
E
Error:
PlayersControllerTest#test_should_get_index:
NoMethodError: undefined method `players' for #<PlayersControllerTest:0x000055e0a12f1728 #_routes=nil, #NAME="test_should_get_index", #failures=[#<Minitest::UnexpectedError: Unexpected exception>], #assertions=0, #integration_session=#<#<Class:0x000055e0a0cf5018>:0x000055e0a12eb490 #_routes=nil, #app=#<Api::Application:0x000055e09d3e4440 #_all_autoload_paths=["/home/code/splendor/api/app/channels", "/home/code/splendor/api/app/controllers", "/home/code/splendor/api/app/controllers/concerns", "/home/code/splendor/api/app/jobs", "/home/code/splendor/api/app/mailers", "/home/code/splendor/api/app/models", "/home/code/splendor/api/app/models/concerns"], #_all_load_paths=["/home/code/splendor/api/lib", "/home/code/splendor/api/vendor", "/home/code/splendor/api/app/channels", "/home/code/splendor/api/app/controllers", "/home/code/splendor/api/app/controllers/concerns", "/home/code/splendor/api/app/jobs", "/home/code/splendor/api/app/mailers", "/home/code/splendor/api/app/models", "/home/code/splendor/api/app/models/concerns"], #app=#<Rack::Cors:0x000055e09cca0850 #app=#<ActionDispatch::HostAuthorization:0x000055e09cca2678 #app=#<Rack::Sendfile:0x000055e09cca2ce0 #app=#<ActionDispatch::Static:0x000055e09cfeb208 #app=#<ActionDispatch::Executor:0x000055e09cfeb5a0 #app=#<RailsPerformance::Rails::MiddlewareTraceStorerAndCleanup:0x000055e09cfeb6e0 #app=#<RailsPerformance::Rails::Middleware:0x000055e09cfeb7d0 #app=#<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x000055e09e1e5d78 #name="ActiveSupport::Cache::Strategy::LocalCache", #local_cache_key=:active_support_cache_null_store_local_cache_6500, #app=#<Rack::Runtime:0x000055e09cfebb68 #app=#<ActionDispatch::RequestId:0x000055e09cfebca8 #app=#<ActionDispatch::RemoteIp:0x000055e09cfebde8 #app=#<Rails::Rack::Logger:0x000055e09cfebed8 #app=#<ActionDispatch::ShowExceptions:0x000055e09cfebfa0 #app=#<ActionDispatch::DebugExceptions:0x000055e09d3d4360 #app=#<ActionDispatch::ActionableExceptions:0x000055e09d3d4680 #app=#<ActionDispatch::Reloader:0x000055e09d3d4860 #app=#<ActionDispatch::Callbacks:0x000055e09d3d49c8 #app=#<Rack::Head:0x000055e09d3d4bd0 #app=#<Rack::ConditionalGet:0x000055e09d3d4d10 #app=#<Rack::ETag:0x000055e09d3d4ef0 #app=#<Warden::Manager:0x000055e09d3d5490 #config={:default_scope=>:user, :scope_defaults=>{}, :default_strategies=>{:user=>[:jwt, :database_authenticatable]}, :intercept_401=>false, :failure_app=>#<Devise::Delegator:0x000055e09c52b908>}, #app=#<Warden::JWTAuth::Middleware:0x000055e09d3d55d0 #app=#<ActionDispatch::Routing::RouteSet:0x000055e09e6713b0>>>, #cache_control="max-age=0, private, must-revalidate", #no_cache_control="no-cache">>>>, #executor=#<Class:0x000055e09c99af20>>>, #routes_app=#<Api::Application:0x000055e09d3e4440 ...>, #response_format=:api, #interceptors=[]>, #exceptions_app=#<ActionDispatch::PublicExceptions:0x000055e09c8960e8 #public_path=#<Pathname:/home/code/splendor/api/public>>>, #taggers=[]>, #check_ip=true, #proxies=[#<IPAddr: IPv4:127.0.0.0/255.0.0.0>, #<IPAddr: IPv6:0000:0000:0000:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>, #<IPAddr: IPv6:fc00:0000:0000:0000:0000:0000:0000:0000/fe00:0000:0000:0000:0000:0000:0000:0000>, #<IPAddr: IPv4:10.0.0.0/255.0.0.0>, #<IPAddr: IPv4:172.16.0.0/255.240.0.0>, #<IPAddr: IPv4:192.168.0.0/255.255.0.0>]>, #header="X-Request-Id">, #header_name="X-Runtime">>>>, #executor=#<Class:0x000055e09ccd9790>>, #file_handler=#<ActionDispatch::FileHandler:0x000055e09cfeaf38 #root="/home/code/splendor/api/public", #index="index", #precompressed=["br", "gzip", "identity"], #compressible_content_types=/\A(?:text\/|application\/javascript)/, #file_server=#<Rack::Files:0x000055e09cca3de8 #root="/home/code/splendor/api/public", #headers={"Cache-Control"=>"public, max-age=3600"}, #default_mime="text/plain", #head=#<Rack::Head:0x000055e09cca32d0 #app=#<Proc:0x000055e09cca3438 /home/.rvm/gems/ruby-3.0.2/gems/rack-2.2.3/lib/rack/files.rb:33 (lambda)>>>>>, #variation=nil, #mappings=[]>, #permissions=#<ActionDispatch::HostAuthorization::Permissions:0x000055e09cca2178 #hosts=[]>, #exclude=nil, #response_app=#<Proc:0x000055e09c1912e8 /home/.rvm/gems/ruby-3.0.2/gems/actionpack-6.1.4.1/lib/action_dispatch/middleware/host_authorization.rb:61 (lambda)>>, #debug_mode=false, #logger_proc=nil, #logger=nil, #all_resources=[#<Rack::Cors::Resources:0x000055e09cc91580 #origins=["*"], #resources=[#<Rack::Cors::Resource:0x000055e09cc6af70 #path="*", #credentials=false, #max_age=7200, #pattern=/^(.*?)$/, #if_proc=nil, #vary_headers=nil, #public_resource=true, #headers=["authorization"], #methods=["get", "post", "put", "patch", "delete", "options", "head"], #expose=nil>], #public_resources=true>]>, #config=#<Rails::Application::Configuration:0x000055e09dff8448 #root=#<Pathname:/home/code/splendor/api>, #generators=#<Rails::Configuration::Generators:0x000055e09c89f760 #aliases={}, #options={:rails=>{:orm=>:active_record, :test_framework=>:test_unit, :integration_tool=>:test_unit, :system_tests=>:test_unit}, :active_record=>{:migration=>true, :timestamps=>true}, :test_unit=>{:fixture=>false, :fixture_replacement=>:factory_bot}}, #fallbacks={}, #templates=[], #colorize_logging=true, #api_only=true, #hidden_namespaces=[], #after_generate_callbacks=[]>, #middleware=#<ActionDispatch::MiddlewareStack:0x000055e09c21bdd0 #middlewares=[Rack::Cors, ActionDispatch::HostAuthorization, Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, RailsPerformance::Rails::MiddlewareTraceStorerAndCleanup, RailsPerformance::Rails::Middleware, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::ActionableExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, Rack::Head, Rack::ConditionalGet, Rack::ETag, Warden::Manager, Warden::JWTAuth::Middleware]>, #javascript_path="javascript", #encoding=#<Encoding:UTF-8>, #allow_concurrency=nil, #consider_all_requests_local=false, #filter_parameters=[:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn], #filter_redirect=[], #helpers_paths=["/home/.rvm/gems/ruby-3.0.2/gems/devise-4.8.1/app/helpers"], #hosts=[], #host_authorization={}, #public_file_server=#<ActiveSupport::OrderedOptions {:enabled=>true, :index_name=>"index", :headers=>{"Cache-Control"=>"public, max-age=3600"}}>, #force_ssl=false, #ssl_options={:hsts=>{:subdomains=>true}}, #session_store=:cookie_store, #time_zone="UTC", #beginning_of_week=:monday, #log_level=:debug, #cache_store=:null_store, #railties_order=[:all], #relative_url_root=nil, #reload_classes_only_on_change=true, #file_watcher=ActiveSupport::FileUpdateChecker, #exceptions_app=nil, #autoflush_log=true, #log_formatter=#<ActiveSupport::Logger::SimpleFormatter:0x000055e09e0076a0 #datetime_format=nil>, #eager_load=false, #secret_key_base=nil, #api_only=true, #debug_exception_response_format=:api, #x=#<Rails::Application::Configuration::Custom:0x000055e09e007600 #configurations={}>, #enable_dependency_loading=false, #read_encrypted_secrets=false, #content_security_policy=nil, #content_security_policy_report_only=false, #content_security_policy_nonce_generator=nil, #content_security_policy_nonce_directives=nil, #require_master_key=false, #loaded_config_version=6.1, #credentials=#<ActiveSupport::OrderedOptions {:content_path=>#<Pathname:/home/code/splendor/api/config/credentials.yml.enc>, :key_path=>#<Pathname:/home/code/splendor/api/config/master.key>}>, #autoloader=:zeitwerk, #disable_sandbox=false, #add_autoload_paths_to_load_path=true, #permissions_policy=nil, #rake_eager_load=false, #paths=#<Rails::Paths::Root:0x000055e09e107e38 #path=#<Pathname:/home/code/splendor/api>, #root={"app"=>#<Rails::Paths::Path:0x000055e09e107d48 #paths=["app"], #current="app", #root=#<Rails::Paths::Root:0x000055e09e107e38 ...>, #glob="{*,*/concerns}", #exclude=["assets", "javascript"], #autoload_once=false, #eager_load=true, #autoload=false, #load_path=false>, "app/assets"=>#<Rails::Paths::Path:0x000055e09e107cd0 #paths=["app/assets"], #current="app/assets", #root=#<Rails::Paths::Root:0x000055e09e107e38 ...>, #glob="*", #exclude=nil, #autoload_once=false, #eager_load=false, #autoload=false, #load_path=false>, "app/controllers"=>#<Rails::Paths::Path:0x000055e09e107c58 #paths=["app/controllers"], #current="app/controllers", #root=#<Rails::Paths::Root:0x000055e09e107e38 ...>, #glob=nil, #exclude=nil, #autoload_once=false,
...
Finished in 5.930508s, 9.1055 runs/s, 13.1523 assertions/s.
54 runs, 78 assertions, 1 failures, 10 errors, 0 skips
And a link to the full stacktrace as it was too large to fit
I was able to find a workaround!
You create a custom initializer file in the config/initializers directory of your application that removes the variables that contain useless info. Once I removed the following the error messages were more useful.
Here's my config/initializers/hide_test_error_trace.rb:
ActionDispatch::IntegrationTest.class_eval do
def hide_test_error_trace
#integration_session = nil
#connection_subscriber = nil
#tagged_logger = nil
#delegate = nil
end
end
i have to make an http get call to an external service. By sending an address, the latitude and longitude coordinates are returned. The problem is that if the address is Russian or French I have errors like:
URI must be ascii only "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={Barrage de G\u00E9nissiat, Rue Marcel Paul, Injoux, Franclens, Nantua, Ain, Auvergne-Rh\u00F4ne-Alpes, Francia metropolitana, 74910, Francia}&format=json"
My code is:
url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={"+ address_search +"}&format=json";
response = Faraday.get url
the variable address_search is:
Barrage de Génissiat, Rue Marcel Paul, Injoux, Franclens, Nantua, Ain, Auvergne-Rhône-Alpes, Francia metropolitana, 74910, Francia
Faraday is just a grm in rails to make an HTTP request, nothing strange. I have to manipulate the URL. Do you have any suggestion?
EDIT:
print Rails.logger.info "body " + response.body
print Rails.logger.info response.status
print Rails.logger.info response.env.url
This is the output
body []
200
https://nominatim.openstreetmap.org/?addressdetails=1&format=json&q=Barrage+de+G%C3%A9nissiat%2C+Rue+Marcel+Paul%2C+Injoux%2C+Franclens%2C+Nantua%2C+Ain%2C+Auvergne-Rh%C3%B4ne-Alpes%2C+Francia+metropolitana%2C+74910%2C+Francia
Rendering homes/index.html.erb within layouts/application
The query should be encoded, you can do it manually:
query = 'Barrage de Génissiat, Rue Marcel Paul, Injoux, Franclens, Nantua, Ain, Auvergne-Rhône-Alpes, Francia metropolitana, 74910, Francia'
address_search = URI.escape(query)
url = "https://nominatim.openstreetmap.org/?format=json&addressdetails=1&q=#{address_search}&format=json"
response = Faraday.get(url)
Or leave the job for Faraday:
query = 'Barrage de Génissiat, Rue Marcel Paul, Injoux, Franclens, Nantua, Ain, Auvergne-Rhône-Alpes, Francia metropolitana, 74910, Francia'
connection = Faraday.new('https://nominatim.openstreetmap.org')
response = connection.get do |request|
request.params = { format: 'json', addressdetails: 1, q: query }
end
Here is the response:
=> #<Faraday::Response:0x0000556afc452060
#env=
#<struct Faraday::Env
method=:get,
body=
"[{\"place_id\":104161692,\"licence\":\"Data \xC2\xA9 OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright\",\"osm_type\":\"way\",\"osm_id\":80667335,\"boundingbox\":[\"46.0516289\",\"46.0531641\",\"5.8112371\",\"5.81
4139\"],\"lat\":\"46.0523765\",\"lon\":\"5.812744291298651\",\"display_name\":\"Barrage de G\xC3\xA9nissiat, Rue Marcel Paul, Injoux, Franclens, Nantua, Ain, Auvergne-Rh\xC3\xB4ne-Alpes, France m\xC3\xA9tropolitaine, 74910, France\"
,\"class\":\"tourism\",\"type\":\"attraction\",\"importance\":1.7983764706069638,\"icon\":\"https://nominatim.openstreetmap.org/images/mapicons/poi_point_of_interest.p.20.png\",\"address\":{\"tourism\":\"Barrage de G\xC3\xA9nissiat\
",\"road\":\"Rue Marcel Paul\",\"suburb\":\"Injoux\",\"village\":\"Franclens\",\"municipality\":\"Nantua\",\"county\":\"Ain\",\"state\":\"Auvergne-Rh\xC3\xB4ne-Alpes\",\"country\":\"France\",\"postcode\":\"74910\",\"country_code\":\
"fr\"}}]",
url=
#<URI::HTTPS https://nominatim.openstreetmap.org/?addressdetails=1&format=json&q=Barrage+de+G%C3%A9nissiat%2C+Rue+Marcel+Paul%2C+Injoux%2C+Franclens%2C+Nantua%2C+Ain%2C+Auvergne-Rh%C3%B4ne-Alpes%2C+Francia+metropolitana%2C+74910%2C+Francia>,
request=#<struct Faraday::RequestOptions params_encoder=nil, proxy=nil, bind=nil, timeout=nil, open_timeout=nil, write_timeout=nil, boundary=nil, oauth=nil, context=nil>,
request_headers={"User-Agent"=>"Faraday v0.17.3"},
ssl=
#<struct Faraday::SSLOptions
verify=true,
ca_file=nil,
ca_path=nil,
verify_mode=nil,
cert_store=nil,
client_cert=nil,
client_key=nil,
certificate=nil,
private_key=nil,
verify_depth=nil,
version=nil,
min_version=nil,
max_version=nil>,
parallel_manager=nil,
params=nil,
response=#<Faraday::Response:0x0000556afc452060 ...>,
response_headers=
{"server"=>"nginx",
"date"=>"Thu, 15 Oct 2020 19:42:53 GMT",
"content-type"=>"application/json; charset=UTF-8",
"transfer-encoding"=>"chunked",
"connection"=>"close",
"access-control-allow-origin"=>"*",
"access-control-allow-methods"=>"OPTIONS,GET"},
status=200,
reason_phrase="OK">,
#on_complete_callbacks=[]>
Make sure that you use https schema, otherwise, you'll get a response with a redirect.
I use this code:
query = "Barrage de Génissiat, Rue Marcel Paul, Injoux, Franclens, Nantua, Ain, Auvergne-Rhône-Alpes, Francia metropolitana, 74910, Francia"
connection = Faraday.new('https://nominatim.openstreetmap.org')
response = connection.get do |request|
request.params = { format: 'json', addressdetails: 1, q: query }
end
print Rails.logger.info response.body
And I receive []..
I have an app that calls the Google Drive API to create and copy documents in a Google Drive folder, the create method generates a folder for each Test and creates copies of a Google Doc (question doc) and puts them in the associated folder to the Test (answers).
In localhost it works and all API responses arrive successfully, but in EC2 the response of the last request to the API doesn't arrive.
In the app's log the request doesn't appear but if the success response of the previous Google Doc generated("200"," HTTP :: Message ... from Google Drive API").
# log/production.log
D, [2019-09-07T01:47:11.891256 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] Sending HTTP post https://www.googleapis.com/drive/v3/files/1exr3HKLe6IgOZU8I22VZEV4WH24UrKnGOPvmGi8-g2k/copy?fields=id%2CwebViewLink%2Cname
D, [2019-09-07T01:47:14.442112 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] 200
D, [2019-09-07T01:47:14.442366 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] #<HTTP::Message:0x000055f8e60e6d40 #http_header=#<HTTP::Message::Headers:0x000055f8e60e6d18 #http_version="1.1", #body_size=0, #chunked=false, #request_method="POST", #request_uri=#<Addressable::URI:0x2afc73073d44 URI:https://www.googleapis.com/drive/v3/files/1exr3HKLe6IgOZU8I22VZEV4WH24UrKnGOPvmGi8-g2k/copy?fields=id%2CwebViewLink%2Cname>, #request_query=nil, #request_absolute_uri=nil, #status_code=200, #reason_phrase="OK", #body_type=nil, #body_charset=nil, #body_date=nil, #body_encoding=#<Encoding:UTF-8>, #is_request=false, #header_item=[["Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"], ["Pragma", "no-cache"], ["Expires", "Mon, 01 Jan 1990 00:00:00 GMT"], ["Date", "Sat, 07 Sep 2019 01:47:14 GMT"], ["Vary", "Origin"], ["Vary", "X-Origin"], ["Content-Type", "application/json; charset=UTF-8"], ["Content-Encoding", "gzip"], ["X-Content-Type-Options", "nosniff"], ["X-Frame-Options", "SAMEORIGIN"], ["X-XSS-Protection", "1; mode=block"], ["Server", "GSE"], ["Alt-Svc", "quic=\":443\"; ma=2592000; v=\"46,43,39\""], ["Transfer-Encoding", "chunked"]], #dumped=false>, #peer_cert=#<OpenSSL::X509::Certificate: subject=#<OpenSSL::X509::Name CN=*.googleapis.com,O=Google LLC,L=Mountain View,ST=California,C=US>, issuer=#<OpenSSL::X509::Name CN=GTS CA 1O1,O=Google Trust Services,C=US>, serial=#<OpenSSL::BN:0x000055f8e6101028>, not_before=2019-08-23 10:30:37 UTC, not_after=2019-11-21 10:30:37 UTC>, #http_body=#<HTTP::Message::Body:0x000055f8e60e6ca0 #body="{\n \"id\": \"1qmoh-0cTJTNesh1qmxe97Bm0BpnXlrAng3ul2Ttryn8\",\n \"name\": \"Pregunta 2\",\n \"webViewLink\": \"https://docs.google.com/document/d/1qmoh-0cTJTNesh1qmxe97Bm0BpnXlrAng3ul2Ttryn8/edit?usp=drivesdk\"\n}\n", #size=0, #positions=nil, #chunk_size=nil>, #previous=nil>
D, [2019-09-07T01:47:14.443173 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] Success - #<Google::Apis::DriveV3::File:0x000055f8e6100768
#id="1qmoh-0cTJTNesh1qmxe97Bm0BpnXlrAng3ul2Ttryn8",
#name="Pregunta 2",
#web_view_link=
"https://docs.google.com/document/d/1qmoh-0cTJTNesh1qmxe97Bm0BpnXlrAng3ul2Ttryn8/edit?usp=drivesdk">
D, [2019-09-07T01:47:14.443797 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] ^[[1m^[[35m (0.2ms)^[[0m ^[[1m^[[35mBEGIN^[[0m
D, [2019-09-07T01:47:14.444924 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] ^[[1m^[[36mAnswer Create (0.4ms)^[[0m ^[[1m^[[32mINSERT INTO "answers" ("name", "id_google_doc", "gdrive_link", "test_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"^[[0m [["name", "Pregunta 2"], ["id_google_doc", "1qmoh-0cTJTNesh1qmxe97Bm0BpnXlrAng3ul2Ttryn8"], ["gdrive_link", "https://docs.google.com/document/d/1qmoh-0cTJTNesh1qmxe97Bm0BpnXlrAng3ul2Ttryn8/edit?usp=drivesdk"], ["test_id", 59], ["created_at", "2019-09-07 01:47:14.444031"], ["updated_at", "2019-09-07 01:47:14.444031"]]
D, [2019-09-07T01:47:14.446000 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] ^[[1m^[[35m (0.9ms)^[[0m ^[[1m^[[35mCOMMIT^[[0m
D, [2019-09-07T01:47:14.446717 #12230] DEBUG -- : [3457498a-19dd-4a0a-a326-4dbf47a358c5] Sending HTTP post https://www.googleapis.com/drive/v3/files/1gtGCWyATlRkCu8yMLOifdPt_F6c2oRRwc2zLUG0HGUc/copy?fields=id%2CwebViewLink%2Cname
# app/controllers/tests_controller.rb
# POST /tests
# POST /tests.json
def create
#test = Test.new(test_params)
#students_course = #test.test_rubric.course.students
#questions = #test.test_rubric.questions
if #test.test_rubric.tests.first.present?
init_drive_service
#test.test_rubric.tests.each do |old_test|
#gdrive_service.delete_doc(old_test.id_google)
old_test.destroy
end
end
respond_to do |format|
if #students
init_drive_service
#root_folder = Folder.find(#test.test_rubric.tests_folder_id)
#students_course.each do |student_test|
#test1 = Test.new(test_params)
#test_folder = new_folder(student_test.dni,#root_folder) #create folder in Google Drive
#test1.id_google = #test_folder.id_gdrive
#test1.gdrive_link = #test_folder.gdrive_link
#test1.student = student_test
#test1.shared = false
#test1.save
#questions.each do |q|
#test_answer_gdrive = #gdrive_service.copy_doc(q.name, q.id_google_doc, #test_folder.id_gdrive) # ----- HERE CRASH ----
#answer = Answer.new(name: #test_answer_gdrive.name,
id_google_doc: #test_answer_gdrive.id,
gdrive_link: #test_answer_gdrive.web_view_link)
#answer.test = #test1
#answer.save
end
end
format.html { redirect_to evaluaciones_path(curso: #test.test_rubric.course), alert: 'success', notice: #test.test_rubric.name+' - Pruebas generadas exitosamente'}
format.json { render :show, status: :created, location: #test }
else
format.html { render :new }
format.json { render json: #test.errors, status: :unprocessable_entity }
end
end
end
Could I be exceeding the Google Drive API calls limit or could I have an error in the #questions.each loop ?
I have a rails app and I'm trying to get calendar freebusy events from google. When I run the following code I get undefined method "bytesize" for #<Hash.. error for the result = client.execute(.... method. I checked out some other stackoverflow answers, but I can't see what I'm doing wrong. Anyone can tell me how I should deal with this problem?
controller
include GoogleCalendarApi
......
#user = current_user
#google = #user.socials.where(provider: "google_oauth2").first
unless #google.blank?
# #client = get_busy_events(#google)
# #result = open_gcal_connection(get_busy_events, #client, #google)
#result = get_busy_events(#google)
end
.....
lib/google_calendar_api.rb
def init_google_api_calendar_client(google_account)
#method only called if google_oauth2 social exists
client = Google::APIClient.new
client.authorization.access_token = google_account.token
client.authorization.client_id = ENV['GOOGLE_API_KEY']
client.authorization.client_secret = ENV['GOOGLE_API_SECRET']
client.authorization.refresh_token = google_account.refresh_token
return client
end
def get_busy_events(social_object)
client = init_google_api_calendar_client(social_object)
old_token = client.authorization.access_token
service = client.discovered_api('calendar', 'v3')
result = client.execute(
api_method: service.freebusy.query,
body: { timeMin: '2015-12-24T17:06:02.000Z',
timeMax: '2016-01-30T17:06:02.000Z',
items: [{ id: social_object.email }]},
headers: {'Content-Type' => 'application/json'})
new_token = client.authorization.access_token
if old_token != new_token
social_object.update_attribute(token: new_token)
end
return result
end
full error:
Google::APIClient - Initializing client with options {}
21:33:15 puma.1 | Google::APIClient - Please provide :application_name and :application_version when initializing the client
21:33:15 puma.1 | Google::APIClient::Request Sending API request get https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest {"User-Agent"=>"google-api-ruby-client/0.8.6 Mac OS X/10.10.4\n (gzip)", "Accept-Encoding"=>"gzip", "Content-Type"=>""}
21:33:15 puma.1 | Decompressing gzip encoded response (12528 bytes)
21:33:15 puma.1 | Decompressed (103479 bytes)
21:33:15 puma.1 | Google::APIClient::Request Result: 200 {"expires"=>"Thu, 31 Dec 2015 05:36:09 GMT", "date"=>"Thu, 31 Dec 2015 05:31:09 GMT", "etag"=>"\"ye6orv2F-1npMW3u9suM3a7C5Bo/U5WRLEvUgzkUohB7qwzTs2ir15o\"", "vary"=>"Origin, X-Origin", "content-type"=>"application/json; charset=UTF-8", "x-content-type-options"=>"nosniff", "x-frame-options"=>"SAMEORIGIN", "x-xss-protection"=>"1; mode=block", "content-length"=>"12528", "server"=>"GSE", "age"=>"126", "cache-control"=>"public, max-age=300, must-revalidate, no-transform", "alternate-protocol"=>"443:quic,p=1", "alt-svc"=>"quic=\":443\"; ma=604800; v=\"30,29,28,27,26,25\"", "connection"=>"close"}
21:33:15 puma.1 | Google::APIClient::Request Sending API request post https://www.googleapis.com/calendar/v3/freeBusy {"User-Agent"=>"google-api-ruby-client/0.8.6 Mac OS X/10.10.4\n (gzip)", "Content-Type"=>"application/json", "Accept-Encoding"=>"gzip", "Authorization"=>"Bearer ya29.WQKv43gUEb0Jt3jTBevBs0_Z9VurfGxmbH8Knv8E9Sqbw4zxeCHjydwUeyo3MSAotYj0", "Cache-Control"=>"no-store"}
21:33:15 puma.1 | Completed 500 Internal Server Error in 382ms (ActiveRecord: 0.8ms)
21:33:15 puma.1 |
21:33:15 puma.1 | NoMethodError - undefined method `bytesize' for #<Hash:0x007fb6d25b9330>:
21:33:15 puma.1 | /Users/Silo/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/net/http/generic_request.rb:182:in `send_request_with_body'
21:33:15 puma.1 | /Users/Silo/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/net/http/generic_request.rb:120:in `exec'
From Pardeep's link, try
result = client.execute(
api_method: service.freebusy.query,
body: URI.encode_www_form({ timeMin: '2015-12-24T17:06:02.000Z',
timeMax: '2016-01-30T17:06:02.000Z',
items: [{ id: social_object.email }]}),
headers: {'Content-Type' => 'application/json'})
The problem is that the body could not be sent as a hash. You should encode as an string.
How do I retrieve the Plan ID in Rails from Stripe's invoice.payment_succeeded webhook event?
I have tried the code below but keep on getting plan is nil error.
plan_id = event.data.object.lines.data[1].plan.id
Here is the web hook event.
{
"id"=>"evt_111111111",
"created"=>1207343135,
"livemode"=>true,
"type"=>"invoice.payment_succeeded",
"data"=>{
"object"=>{
"date"=>2437418246,
"id"=>"in_......",
"period_start"=>1406044997,
"period_end"=>1437238559,
"lines"=>{
"object"=>"list",
"total_count"=>1,
"has_more"=>false,
"url"=>"/v1/invoices/in_...../lines",
"data"=>[
{
"id"=>"sub_.....",
"object"=>"line_item",
"type"=>"subscription",
"livemode"=>true,
"amount"=>29900,
"currency"=>"cad",
"proration"=>false,
"period"=>{
"start"=>2437418246,
"end"=>2437418246
},
"quantity"=>1,
"plan"=>{
"interval"=>"month",
"name"=>"Business",
"created"=>2437446,
"amount"=>19900,
"currency"=>"cad",
"id"=>"P3",
"object"=>"plan",
"livemode"=>true,
"interval_count"=>1,
"trial_period_days"=>7,
"metadata"=>{},
"statement_description"=>nil
},
"description"=>nil,
"metadata"=>{}
}
],
"count"=>1
},
"subtotal"=>19900,
"total"=>19900,
"customer"=>"cus_.....",
"object"=>"invoice",
"attempted"=>true,
"closed"=>true,
"forgiven"=>false,
"paid"=>true,
"livemode"=>true,
"attempt_count"=>1,
"amount_due"=>19900,
"currency"=>"cad",
"starting_balance"=>0,
"ending_balance"=>0,
"next_payment_attempt"=>nil,
"webhooks_delivered_at"=>14022ert61,
"charge"=>"ch_......",
"discount"=>nil,
"application_fee"=>nil,
"subscription"=>"sub_......",
"metadata"=>{},
"statement_description"=>nil,
"description"=>nil
}
},
"object"=>"event",
"pending_webhooks"=>1,
"request"=>nil,
"webhook"=>{
"id"=>"evt_....."
}
}
You appear to only have a single item in the data list.
Note that Arrays in Ruby start at index 0.
I believe you will want to change data[1] to data[0].
Note, this can still break if there is a chance that the data list can be empty.