Rails console error stacktrace is extremely large - ruby-on-rails

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

Related

how do I print a Rails POST request output?

I have this request:
post '/api/v1/fruit', params: valid_fruits, headers: lots_of_security
how can I see what's going on behind the scenes and see the many fruits contained in the raw output that will be sent after executing it?
[1] pry(#<Api::V1::InquiriesController>)> request
returns this very verbose and complete answer:
=> #<ActionDispatch::Request:0x0000aaaae4ba5308
#env=
{"rack.version"=>[1, 3],
"rack.input"=>#<StringIO:0x0000aaaae4bdffa8>,
"rack.errors"=>#<StringIO:0x0000aaaae4be0070>,
"rack.multithread"=>true,
"rack.multiprocess"=>true,
"rack.run_once"=>false,
"REQUEST_METHOD"=>"POST",
"SERVER_NAME"=>"www.example.com",
"SERVER_PORT"=>"80",
"QUERY_STRING"=>"",
"PATH_INFO"=>"/api/v1/inquiries",
"rack.url_scheme"=>"http",
"HTTPS"=>"off",
"SCRIPT_NAME"=>"",
"CONTENT_LENGTH"=>"141",
"rack.test"=>true,
"REMOTE_ADDR"=>"127.0.0.1",
"REQUEST_URI"=>"/api/v1/inquiries",
"HTTP_HOST"=>"www.example.com",
"CONTENT_TYPE"=>"application/x-www-form-urlencoded",
"HTTP_ACCEPT"=>"application/vnd",
"HTTP_AUTHORIZATION"=>"Bc29dEtvWGiYtmaZGTqL484r",
"HTTP_COOKIE"=>"",
"action_dispatch.parameter_filter"=>[:password],
"action_dispatch.redirect_filter"=>[],
"action_dispatch.secret_key_base"=>
"redacted",
"action_dispatch.show_exceptions"=>false,
"action_dispatch.show_detailed_exceptions"=>true,
"action_dispatch.logger"=>
#<ActiveSupport::Logger:0x0000aaaae205d4e8
#default_formatter=
#<Logger::Formatter:0x0000aaaae205d678 #datetime_format=nil>,
<page break> --- Press enter to continue ( q<enter> to break ) --- <page break>

PATCH fetch json body to Rails

I'm PATCHing a form to Rails through fetch, but some attributes are not handled properly on the server side.
I'm running Rails 5.2.2 over Ruby ruby 2.5.1p57
When I post the data to the server, I get this console.log output in browser:
{id: 10172, weekday: 1, is_only_private: false, is_allow_forced: false, from_time: 08:00, to_time: 09:00, act_ids: [10001, 10002], customer_id: 10000, consultation_id: 10000}
But on the server side I can see this log on console:
Parameters: {"id"=>"10172", "weekday"=>1, "is_only_private"=>false, "is_allow_forced"=>false, "from_time"=>"08:00", "to_time"=>"09:00", "act_ids"=>[10001, 10002], "customer_id"=>"10000", "consultation_id"=>"10000", "timetable"=>{"id"=>"10172", "weekday"=>1, "is_only_private"=>false, "is_allow_forced"=>false, "from_time"=>"08:00", "to_time"=>"09:00"}}
act_ids disappears inside timetable attribute
My app it's hybrid, it's responding with HTML and JSON (even XML) in the same routes.
Question:
Is not it solved in this version of Rails yet?
Workaround with this
def timetable_params
my_params = params.require(:timetable).permit :weekday,
:is_only_private,
:is_allow_forced,
:from_time,
:to_time,
act_ids: []
my_params[:act_ids] ||= params[:act_ids]
my_params
end
Probably you permitted it as permit(..., :to_time, :act_ids), but array should be permitted via act_ids: [], which you already have in your timetable_params code
On clean application this works correctly:
#!/usr/bin/env ruby
# frozen_string_literal: true
require "bundler/inline"
gemfile(!!ENV['INSTALL']) do
source "https://rubygems.org"
gem 'rails', '5.2.2'
end
require "action_controller/railtie"
class TestApp < Rails::Application
config.root = __dir__
config.eager_load = false
config.session_store :cookie_store, key: "cookie_store_key"
secrets.secret_key_base = "secret_key_base"
config.logger = Logger.new($stdout)
Rails.logger = config.logger
end
TestApp.initialize!
TestApp.routes.draw{ resources :timetables, only: :update }
class TimetablesController < ActionController::Base
include Rails.application.routes.url_helpers
wrap_parameters format: [:json, :xml]
def update
render json: timetable_params
end
def timetable_params
params.require(:timetable).permit(:weekday,
:is_only_private,
:is_allow_forced,
:from_time,
:to_time,
act_ids: [])
end
end
require "minitest/autorun"
require "rack/test"
class BugTest < Minitest::Test
include Rack::Test::Methods
def test_returns_success
payload = {
"id"=>"10172", "weekday"=>1, "is_only_private"=>false, "is_allow_forced"=>false,
"from_time"=>"08:00", "to_time"=>"09:00",
"act_ids"=>[10001, 10002],
"customer_id"=>"10000", "consultation_id"=>"10000"
}
patch "/timetables/10172.json", payload.to_json, { 'CONTENT_TYPE' => 'application/json' }
assert last_response.ok?
puts "resp body: #{last_response.body}"
resp = JSON.parse(last_response.body)
assert_includes(resp.keys, "act_ids")
end
private def app
Rails.application
end
end
produces
Run options: --seed 62182
# Running:
I, [2019-06-14T16:04:02.967561 #44749] INFO -- : Started PATCH "/timetables/10172.json" for 127.0.0.1 at 2019-06-14 16:04:02 +0300
I, [2019-06-14T16:04:02.971039 #44749] INFO -- : Processing by TimetablesController#update as JSON
I, [2019-06-14T16:04:02.971161 #44749] INFO -- : Parameters: {"id"=>"10172", "weekday"=>1, "is_only_private"=>false, "is_allow_forced"=>false, "from_time"=>"08:00", "to_time"=>"09:00", "act_ids"=>[10001, 10002], "customer_id"=>"10000", "consultation_id"=>"10000", "timetable"=>{"id"=>"10172", "weekday"=>1, "is_only_private"=>false, "is_allow_forced"=>false, "from_time"=>"08:00", "to_time"=>"09:00", "act_ids"=>[10001, 10002], "customer_id"=>"10000", "consultation_id"=>"10000"}}
D, [2019-06-14T16:04:02.971850 #44749] DEBUG -- : Unpermitted parameters: :id, :customer_id, :consultation_id
I, [2019-06-14T16:04:02.972484 #44749] INFO -- : Completed 200 OK in 1ms (Views: 0.4ms)
resp body: {"weekday":1,"is_only_private":false,"is_allow_forced":false,"from_time":"08:00","to_time":"09:00","act_ids":[10001,10002]}
.
Finished in 0.020124s, 49.6919 runs/s, 149.0757 assertions/s.
1 runs, 3 assertions, 0 failures, 0 errors, 0 skips

Consume JSON - Shopify API response

I'm trying to work with what I think is a JSON response from Shopify. It looks like this:
=> #<ActiveResource::Collection:0x007f61f45c3840
#elements=
[#<ShopifyAPI::Product:0x007f61f45c3638
#attributes=
{"id"=>2156425793,
"title"=>"Hue Women's Python Net Tight, Black, Small-Medium",
"body_html"=>"Python pattern",
"vendor"=>"HUE",
"product_type"=>"Apparel",
"created_at"=>"2015-10-02T09:42:07-04:00",
"handle"=>"hue-womens-python-net-tight-black-small-medium",
"updated_at"=>"2015-10-02T09:42:07-04:00",
"published_at"=>"2015-10-02T09:42:07-04:00",
"template_suffix"=>nil,
"published_scope"=>"global",
"tags"=>"",
"variants"=>
[#<ShopifyAPI::Variant:0x007f61f45c11a8
#attributes=
{"id"=>6989658561,
"title"=>"First",
"price"=>"18.00",
"sku"=>"123",
"position"=>1,
"grams"=>0,
"inventory_policy"=>"deny",
"compare_at_price"=>"18.00",
"fulfillment_service"=>"amazon_marketplace_web",
"inventory_management"=>"shopify",
"option1"=>"First",
"option2"=>nil,
"option3"=>nil,
"created_at"=>"2015-10-02T09:42:07-04:00",
"updated_at"=>"2015-10-02T09:42:07-04:00",
"requires_shipping"=>true,
"taxable"=>true,
"barcode"=>nil,
"inventory_quantity"=>1,
"old_inventory_quantity"=>1,
"image_id"=>nil,
"weight"=>0.0,
"weight_unit"=>"lb"},
#persisted=true,
#prefix_options={:product_id=>2156425793}>,
#<ShopifyAPI::Variant:0x007f61f45b4d18
#attributes=
{"id"=>6989658625,
"title"=>"Second",
"price"=>"18.00",
"sku"=>"345",
"position"=>2,
"grams"=>0,
"inventory_policy"=>"deny",
"compare_at_price"=>"18.00",
"fulfillment_service"=>"amazon_marketplace_web",
"inventory_management"=>"shopify",
"option1"=>"Second",
"option2"=>nil,
"option3"=>nil,
"created_at"=>"2015-10-02T09:42:07-04:00",
"updated_at"=>"2015-10-02T09:42:07-04:00",
"requires_shipping"=>true,
"taxable"=>true,
"barcode"=>nil,
"inventory_quantity"=>3,
"old_inventory_quantity"=>3,
"image_id"=>nil,
"weight"=>0.0,
"weight_unit"=>"lb"},
#persisted=true,
#prefix_options={:product_id=>2156425793}>],
"options"=>
[#<ShopifyAPI::Option:0x007f61f45a92b0
#attributes={"id"=>2550138369, "product_id"=>2156425793,
"name"=>"Title", "position"=>1, "values"=>["First", "Second"]},
#persisted=true,
#prefix_options={}>],
"images"=>
[#<ShopifyAPI::Image:0x007f61f459b390
#attributes=
{"id"=>5116928641,
"position"=>1,
"created_at"=>"2015-10-02T09:42:07-04:00",
"updated_at"=>"2015-10-02T09:42:07-04:00",
"src"=>"https://cdn.shopify.com/s/files/1/0842/7077/products
/41ooqKhDYRL._UL1500.jpeg?v=1443793327",
"variant_ids"=>[]},
#persisted=true,
#prefix_options={:product_id=>2156425793}>],
"image"=>
#<ShopifyAPI::Image:0x007f61f4598050
#attributes=
{"id"=>5116928641,
"position"=>1,
"created_at"=>"2015-10-02T09:42:07-04:00",
"updated_at"=>"2015-10-02T09:42:07-04:00",
"src"=>"https://cdn.shopify.com/s/files/1/0842/7077/products
/41ooqKhDYRL._UL1500.jpeg?v=1443793327",
"variant_ids"=>[]},
#persisted=true,
#prefix_options={:product_id=>2156425793}>},
#persisted=true,
#prefix_options={}>],
#original_params={:title=>"Hue Women's Python Net Tight"},
#resource_class=ShopifyAPI::Product>
The response I get from searching for a product via the Shopify API is of the class:
ActiveResource::Collection
I first tried turning that to JSON with .to_json but thats just a string and I can't loop thru it easily.
I then tried to turn it to an array with .to_a but now I can't get into the data..
The original response is in the x variable and now its an array.. If I try
x[0] - I get the original response back
x[1] - nil
X[0]["id] - NoMethodError: undefined method `[]' for
#<ShopifyAPI::Product:0x007f61f45c3638>
x["id"] - TypeError: no implicit conversion of String into Integer
x[0][0] - NoMethodError: undefined method `[]' for
#<ShopifyAPI::Product:0x007f61f45c3638>
x[0].class - Shopify::Product which is a ActiveResource::Collection
x[0].to_array - NoMethodError: undefined method `to_array' for
#<ShopifyAPI::Product:0x007f61f45c3638>
The data you show is an array of Product instances. Simply take the data, which I'll call data, and loop through it to get each product.
data.each do |product|
puts product.title
puts product.vendor
end
You can obviously extend your functionality from here.

Nokogiri does not load parse whole xml file

I have a XML document:
<event>
<type>SUBSCRIPTION_ORDER</type>
<marketplace>
<baseUrl>https://www.acme-marketplace.com</baseUrl>
<partner>ACME</partner></marketplace>
</marketplace>
<creator>
<email>admin#fakeco</email>
<firstName>Alice</firstName>
<lastName>Hacker</lastName>
<openId>https://www.acme-marketplace.com/openid/id/a11a7918-bb43-4429-a256-f6d729c71033</openId>
<uuid>a11a7918-bb43-4429-a256-f6d729c71033</uuid>
</creator>
<payload>
<company>
<uuid>d15bb36e-5fb5-11e0-8c3c-00262d2cda03</uuid>
<email>admin#fakeco</email>
<name>Fake Co.</name>
<phoneNumber>1-415-555-1212</phoneNumber>
<website>fakeco</website>
</company>
<order>
<editionCode>BASIC</editionCode>
<item>
<quantity>10</quantity>
<unit>USER</unit>
</item>
</order>
</payload>
</event>
and I got strange result when I load it with nokogiri:
1.9.3p194 :056 > doc = Nokogiri::XML(File.open("test.xml")).to_s
=> "<?xml version=\"1.0\"?>\n<event>\n <type>SUBSCRIPTION_ORDER</type>\n <marketplace>\n <baseUrl>https://www.acme-marketplace.com</baseUrl>\n <partner>ACME</partner></marketplace>\n </event>\n"
What am I doing wrong?
You've got two closing </marketplace> tags, which is invalid XML:
<partner>ACME</partner></marketplace>
</marketplace>
Remove one of them and Nokogiri should read the file fine.
If you parse your XML into a Nokgiri::XML document:
doc = Nokogiri::XML(<<EOT)
<event>
<type>SUBSCRIPTION_ORDER</type>
<marketplace>
<baseUrl>https://www.acme-marketplace.com</baseUrl>
<partner>ACME</partner></marketplace>
</marketplace>
<creator>
<email>admin#fakeco</email>
<firstName>Alice</firstName>
<lastName>Hacker</lastName>
<openId>https://www.acme-marketplace.com/openid/id/a11a7918-bb43-4429-a256-f6d729c71033</openId>
<uuid>a11a7918-bb43-4429-a256-f6d729c71033</uuid>
</creator>
<payload>
<company>
<uuid>d15bb36e-5fb5-11e0-8c3c-00262d2cda03</uuid>
<email>admin#fakeco</email>
<name>Fake Co.</name>
<phoneNumber>1-415-555-1212</phoneNumber>
<website>fakeco</website>
</company>
<order>
<editionCode>BASIC</editionCode>
<item>
<quantity>10</quantity>
<unit>USER</unit>
</item>
</order>
</payload>
</event>
EOT
Then check the document's errors method, you'll see:
doc.errors
[
[0] #<Nokogiri::XML::SyntaxError:0x100a6dbb8
attr_reader :code = 76,
attr_reader :column = 19,
attr_reader :domain = 1,
attr_reader :file = nil,
attr_reader :int1 = 1,
attr_reader :level = 3,
attr_reader :line = 6,
attr_reader :str1 = "event",
attr_reader :str2 = "marketplace",
attr_reader :str3 = nil
>,
[1] #<Nokogiri::XML::SyntaxError:0x100a6daa0
attr_reader :code = 5,
attr_reader :column = 5,
attr_reader :domain = 1,
attr_reader :file = nil,
attr_reader :int1 = 0,
attr_reader :level = 3,
attr_reader :line = 7,
attr_reader :str1 = nil,
attr_reader :str2 = nil,
attr_reader :str3 = nil
>
]
That's Nokogiri telling you about the problems with the document. You can react to that simply enough using:
if (!doc.errors.empty?)
...
end
It tries to recover from errors because of the RECOVER flag being set in the parse step, but there are some cases it can't fix, such as the doubled closing tag. You'll need to do a pre-flight check and fix to cleanse the document before Nokogiri can make sense of it. Unfortunately, not all XML is generated correctly, and whoever created that should have run it through a validity checker before putting it out there. As is, it's non-conforming and considered illegal in the XML world.

undefined method `collect' for 2:Fixnum

def function1
#user=User.find(params[:user_id])
#participants=Participant.find_all_by_user_id(params[:user_id])
bar_1_data = #user.get_total
bar_2_data = params[:count]
color_1 = 'c53711'
color_2 = '0000ff'
min=0
max=100
puts(bar_1_data) # prints 2 on console
puts(bar_2_data) # prints 3 on console
puts (bar_1_data).is_a? Integer # prints true
puts (bar_2_data).is_a? Integer # prints false
bc=GoogleChart::BarChart.new("300x80", " ", :horizontal, false)
bc.data " ", [100], 'ffffff'
bc.data "Bar1", bar_1_data, color_1
bc.data "Bar2", bar_2_data.to_i, color_2
bc.axis :x, :range => [min,max]
bc.show_legend = true
bc.stacked = false
bc.data_encoding = :extended
#bc= bc.to_url
end
end
I am getting the argument error "comparison of String with 100 failed" int the above controller code. Then I changed the lines
bc.data "Bar1", bar_1_data, color_1
bc.data "Bar2", bar_2_data, color_2
to
bc.data "Bar1", bar_1_data.to_i, color_1
bc.data "Bar2", bar_2_data.to_i, color_2
which gives me undefined method collect for 2:Fixnum at line #bc= bc.to_url.
On console it gives the following error:
NoMethodError (undefined method `collect' for 2:Fixnum):
gchartrb (0.8) lib/google_chart/base.rb:499:in `extended_encode'
gchartrb (0.8) lib/google_chart/base.rb:461:in `encode_data'
gchartrb (0.8) lib/google_chart/bar_chart.rb:69:in `process_data'
gchartrb (0.8) lib/google_chart/bar_chart.rb:68:in `collect'
gchartrb (0.8) lib/google_chart/bar_chart.rb:68:in `process_data'
gchartrb (0.8) lib/google_chart/base.rb:440:in `add_data'
gchartrb (0.8) lib/google_chart/base.rb:305:in `prepare_params'
gchartrb (0.8) lib/google_chart/base.rb:77:in `to_url'
app/controllers/assess_controller.rb:139:in `function1'
gchartrb (0.8) lib/google_chart/bar_chart.rb:22:in `initialize'
app/controllers/assess_controller.rb:131:in `new'
app/controllers/assess_controller.rb:131:in `function1'
/Library/Ruby/Gems/1.8/gems/hoptoad_notifier-2.4.11/lib/hoptoad_notifier/rack.rb:27:in `call'
/Library/Ruby/Gems/1.8/gems/hoptoad_notifier-2.4.11/lib/hoptoad_notifier/user_informer.rb:12:in `call'
Rendering rescues/layout (internal_server_error)
Tried printing bc in the view as <p><img src="<%= puts (#bc) %>" ></p>,it doesn't print anything, but when I am printing bc in the controller it prints
#<GoogleChart::BarChart:0x103be9660>.
Am I not sending it correctly to the view? I have tried both #bc=bc.to_url and puts bc.to_url as in http://gchartrb.rubyforge.org/.
What am I missing?
Without knowing the api for google charts, I see this:
bc.data " ", [100], 'ffffff'
bc.data "Bar1", bar_1_data, color_1
bc.data "Bar2", bar_2_data.to_i, color_2
The parameters of the first line are of type String, Array, String.
The parameters of the next two are String, Fixnum, String
Your error message is undefined method collect for 2:Fixnum ... so perhaps you should change the Fixnum to Array.
bc.data " ", [100], 'ffffff'
bc.data "Bar1", [bar_1_data], color_1
bc.data "Bar2", [bar_2_data.to_i], color_2
It looks like you're loading bar_1_data and bar_2_data into arrays. Thus the error undefined method to_i for Array.
Instead of:
bar_1_data = [#user.get_total]
bar_2_data = [params[:count]]
Just try
bar_1_data = #user.get_total
bar_2_data = params[:count]
Note that putting your data inside [] brackets means it's now an array of one item.

Resources