tjmair tjmair - 3 months ago 19
Ruby Question

Sinatra passing params as a hash to function

I am trying to pass the hash of params to a function in my post services resource in sinatra, see below.

post '/service' do
create_itop_entry(params)
end


And my function I am passing the params to....

def create_itop_entry(fields)
params = {'json_data' => '{"operation":"core/create",
"comment":"Service created on ' + Time.now.strftime("%Y-%m-%d") + '",
"class":"Service",
"fields":{
org_id: "'+ fields["org_id"] +'",
status: "' + fields["status"] + '",
stack_type: "' + fields["stack_type"] + '",
version: "' + fields["version"] + '",
hostname: "' + fields["hostname"] + '",
longitude: "' + fields["longitude"] + '",
latitude: "' + fields["latitude"] + '",
abbreviation_code: "' + fields["abbreviation_code"] + '",
name: "' + fields["name"] + '",
email: "' + fields["email"] + '",
apn: "' + fields["apn"] + '"
},
"output_fields":"id, friendlyname"
}'
}
end


The function call below returns my expected result... which is the values in the hash being added to my json_data. When I print out params.inspect from sinatra it returns the same hash as below.

puts create_itop_entry({"org_id"=>"4", "status"=>"pilot", "stack_type"=>"single", "version"=>"2.9.29", "hostname"=>"test.pilot.net", "longitude"=>"-81.20", "latitude"=>"41.20", "abbreviation_code"=>"zzz", "name"=>"Test-Test", "email"=>"test@testing.com", "apn"=>"TestRange1 10.36.192.80-28,TestRange2 10.131.201.0-24"})


The error I am getting is no implicit conversion of Array into String... I am new to ruby/sinatra so I could just be missing something simple...

[2016-08-27 17:28:03] DEBUG WEBrick::HTTPServlet::FileHandler is mounted on /.
[2016-08-27 17:28:03] DEBUG Rack::Handler::WEBrick is mounted on /.
[2016-08-27 17:28:03] INFO WEBrick::HTTPServer#start: pid=32343 port=4567
[2016-08-27 17:28:14] DEBUG accept: ::1:58203
[2016-08-27 17:28:14] DEBUG Rack::Handler::WEBrick is invoked.
[2016-08-27 17:28:15] ERROR TypeError: no implicit conversion of Array into String
/home/geapp/.gem/ruby/2.0/gems/rack-1.6.4/lib/rack/handler/webrick.rb:113:in `block in service'
/home/geapp/.gem/ruby/2.0/gems/rack-1.6.4/lib/rack/handler/webrick.rb:112:in `each'
/home/geapp/.gem/ruby/2.0/gems/rack-1.6.4/lib/rack/handler/webrick.rb:112:in `service'
/usr/share/ruby/2.0/webrick/httpserver.rb:138:in `service'
/usr/share/ruby/2.0/webrick/httpserver.rb:94:in `run'
/usr/share/ruby/2.0/webrick/server.rb:295:in `block in start_thread'
localhost - - [27/Aug/2016:17:28:14 UTC] "POST /service HTTP/1.1" 500 338

Answer

Your function returns a hash. This is not a valid type to return from a Sinatra route. Returning a hash is causing the webserver to get confused, resulting in this error.

Perhaps you mean to call to_json and return the resulting string?