How do i fix an implicit conversion for a ruby json code - ruby

I'm trying to save a json file with already inputed data with the code snippet below:
def read_rentals
return [] unless File.exist?('rentals.json')
rentals_json = JSON.parse(File.read('rentals.json'))
rentals_json.map do |rental|
Rental.new(rental['date'], #person[rental['person_index']], #books[rental['book_index']])
end
end
but I get the error message:
block in read_rentals': no implicit conversion from nil to integer (TypeError)
it stopped my script from running. robocop Rental.new line above as the error case.

The JWT.encode method expects a hash of claims. You should simply get the first value of the array and put that in as a parameter. There is no other way around. This is simply the current state of the ruby-jwt implementation.

I found the solution:
in my rentals.json, my person_index was set as null. i changed it to an integer, and the script was working
[
{
"date": "04/23",
"book_index": 0,
"person_index": 0
}
]

Related

Powerautomate Parsing JSON Array

I've seen the JSON array questions here and I'm still a little lost, so could use some extra help.
Here's the setup:
My Flow calls a sproc on my DB and that sproc returns this JSON:
{
"ResultSets": {
"Table1": [
{
"OrderID": 9518338,
"BasketID": 9518338,
"RefID": 65178176,
"SiteConfigID": 237
}
]
},
"OutputParameters": {}
}
Then I use a PARSE JSON action to get what looks like the same result, but now I'm told it's parsed and I can call variables.
Issue is when I try to call just, say, SiteConfigID, I get "The output you selected is inside a collection and needs to be looped over to be accessed. This action cannot be inside a foreach."
After some research, I know what's going on here. Table1 is an Array, and I need to tell PowerAutomate to just grab the first record of that array so it knows it's working with just a record instead of a full array. Fair enough. So I spin up a "Return Values to Virtual Power Agents" action just to see my output. I know I'm supposed to use a 'first' expression or a 'get [0] from array expression here, but I can't seem to make them work. Below are what I've tried and the errors I get:
Tried:
first(body('Parse-Sproc')?['Table1/SiteConfigID'])
Got: InvalidTemplate. Unable to process template language expressions in action 'Return_value(s)_to_Power_Virtual_Agents' inputs at line '0' and column '0': 'The template language function 'first' expects its parameter be an array or a string. The provided value is of type 'Null'. Please see https://aka.ms/logicexpressions#first for usage details.'.
Also Tried:
body('Parse-Sproc')?['Table1/SiteconfigID']
which just returns a null valued variable
Finally I tried
outputs('Parse-Sproc')?['Table1']?['value'][0]?['SiteConfigID']
Which STILL gives me a null-valued variable. It's the worst.
In that last expression, I also switched the variable type in the return to pva action to a string instead of a number, no dice.
Also, changed 'outputs' in that expression for 'body' .. also no dice
Here is a screenie of the setup:
To be clear: the end result i'm looking for is for the system to just return "SiteConfigID" as a string or an int so that I can pipe that into a virtual agent.
I believe this is what you need as an expression ...
body('Parse-Sproc')?['ResultSets']['Table1'][0]?['SiteConfigID']
You can see I'm just traversing down to the object and through the array to get the value.
Naturally, I don't have your exact flow but if I use your JSON and load it up into Parse JSON step to get the schema, I am able to get the result. I do get a different schema to you though so will be interesting to see if it directly translates.

How to access / address nested fields on Logstash

I am currently trying to convert a nested sub field that contains hexadecimal string to an int type field using Logstash filter
ruby{
code => 'event.set("[transactions][gasprice_int]", event.get("[transactions][gasPrice]").to_i(16))'
}
but it's returning the error
[ERROR][logstash.filters.ruby ][main][2342d24206691f4db46a60285e910d102a6310e78cf8af43c9a2f1a1d66f58a8] Ruby exception occurred: wrong number of arguments calling `to_i` (given 1, expected 0)
I also tried looping through json objects in transactions field using
transactions_num = event.get("[transactions]").size
transactions_num.times do |index|
event.set("[transactions][#{index}][gasprice_int]", event.get("[transactions][#{index}][gasPrice].to_i(16)"))
end
but this also returned an error of
[ERROR][logstash.filters.ruby ][main][99b05fdb6022cc15b0f97ba10cabb3e7c1a8fabb8e0c47d6660861badffdb28e] Ruby exception occurred: Invalid FieldReference: `[transactions][0][gasPrice].to_i(16)`
This method of conversion of hex-string to int type using a ruby filter worked when I wasn't dealing with nested fields, so can anyone please help me how to correctly address nested fields in this case?
btw,
this is the code that still works
ruby {
code => 'event.set("difficulty_int", event.get("difficulty").to_i(16))'
}
I think you have answered this one yourself in your final example - the to_i should not be inside the double quotes. So
...event.get("[transactions][#{index}][gasPrice].to_i(16)"))
should be
...event.get("[transactions][#{index}][gasPrice]").to_i(16))

RSpec - trying to stub a method that returns its own argument

I have a method which I'm trying to stub out in my unit test. The real method gets called with one argument (a string) and then sends out a text message. I need to stub out the method but return the string that gets passed in as an argument.
The code I have in my RSpec test is this:
allow(taxi_driver).to receive(:send_text).with(:string).and_return(string)
This returns:
NameError: undefined local variable or method 'string'
If I change the return argument to :string, I get the following error:
Please stub a default value first if message might be received with other args as well
I've tried googling and checking the relishapp.com site, but can't find the answer to something which appears quite simple and straightforward.
You can pass a block:
allow(taxi_driver).to receive(:send_text).with(kind_of(String)){|string| string }
expect(taxi_driver.send_text("123")).to eq("123")
My method is being called like this: send_text("the time now is #{Time.now}"). The string varies according to the time, thats why I need the mock to return the varying string. Perhaps its not within the scope of a mock to do this?
In such a case, I usually use Timecop gem in order to freeze system time. Here is a sample use case:
describe "#send_text" do
let(:taxi_driver) { TaxiDriver.new }
before do
Timecop.freeze(Time.local(2016, 1, 30, 12, 0, 0))
end
after do
Timecop.return
end
example do
expect(taxi_driver.send_text("the time now is #{Time.now}")).to eq \
"the time now is 2016-01-30 12:00:00 +0900"
end
end

how to get each value from json in ruby sinatra?

I need to extract each key-value of json and that value should save in database. but i am getting trouble in getting value of each key in json.
JSON
{
"topo": [
{
"dpid": "00:00:00:00:00:00:00:03",
"ports": [
3,
1
]
}
],
"app": "vm_migration"
}
code
post '/save_summary', :provides => :json do
begin
params = JSON.parse(request.env["rack.input"].read)
return params["topo"][0]["dpid"]
#above code return correct value
return params["topo"][0]["ports"] #this is not working
rescue Exception => e
return e.message
end
end
i don't know what's wrong with ports statement, please help me to figure out small issue.
What you are returning – params["topo"][0]["ports"] – is an array of two elements, which is one of the things you can return from a Sinatra route:
An Array with two elements: [status (Fixnum), response body (responds to #each)]
So you are trying to return a response with status 3 and body 1. The response body needs to be an object that responds to each, and 1 doesn’t. If you check your logs or console you will probably see an error undefined method `each' for 1:Fixnum. Assuming you just want to see the array in the browser, simply convert it to a string:
return params["topo"][0]["ports"].to_s
The first example works because params["topo"][0]["dpid"] is a string, and you can return strings from routes.

no implicit conversion from nil to integer - when trying to add anything to array

I'm trying to build a fairly complex hash and I am strangely getting the error
no implicit conversion from nil to integer
when I use the line
manufacturer_cols << {:field => 'test'}
I use the same line later in the same loop, and it works no problem.
The entire code is
manufacturer_cols=[]
manufacturer_fields.each_with_index do |mapped_field, index|
if mapped_field.base_field_name=='exactSKU'
#this is where it is breaking, if I comment this out, all is good
manufacturer_cols << { :base_field=> 'test'}
else
#it works fine here!
manufacturer_cols << { :base_field=>mapped_field.base_field_name }
end
end
------- value of manufacturer_fields --------
[{"base_field":{"base_field_name":"Category","id":1,"name":"Category"}},{"base_field":{"base_field_name":"Description","id":3,"name":"Short_Description"}},{"base_field":{"base_field_name":"exactSKU","id":5,"name":"Item_SKU"}},{"base_field":{"base_field_name":"Markup","id":25,"name":"Retail_Price"}},{"base_field":{"base_field_name":"Family","id":26,"name":"Theme"}}]
Implicit Conversion Errors Explained
I'm not sure precisely why your code is getting this error but I can tell you exactly what the error means, and perhaps that will help.
There are two kinds of conversions in Ruby: explicit and implicit.
Explicit conversions use the short name, like #to_s or #to_i. These are commonly defined in the core, and they are called all the time. They are for objects that are not strings or not integers, but can be converted for debugging or database translation or string interpolation or whatever.
Implicit conversions use the long name, like #to_str or #to_int. This kind of conversion is for objects that are very much like strings or integers and merely need to know when to assume the form of their alter egos. These conversions are never or almost never defined in the core. (Hal Fulton's The Ruby Way identifies Pathname as one of the classes that finds a reason to define #to_str.)
It's quite difficult to get your error, even NilClass defines explicit (short name) converters:
nil.to_i
=> 0
">>#{nil}<<" # this demonstrates nil.to_s
=> ">><<"
You can trigger it like so:
Array.new nil
TypeError: no implicit conversion from nil to integer
Therefore, your error is coming from the C code inside the Ruby interpreter. A core class, implemented in C, is being handed a nil when it expects an Integer. It may have a #to_i but it doesn't have a #to_int and so the result is the TypeError.
This seems to have been completely unrelated to anything that had anything to do with manufacturer_cols after all.
I had arrived at the manufacturer_cols bit because if I commented that out, it ran fine.
However, if I commented out the part where I ran through the csv further down the page, it ran fine also.
It turns out the error was related to retrieving attempting to append the base_field when it was nil.
I thought I could use
manufacturer_cols.each do |col|
base_value = row[col[:row_index].to_i]
if col[:merges]
col[:merges].each do |merge|
base_value += merge[:separator].to_s + row[merge[:merge_row_index]]
end
end
end
unfortunately, that caused the error. the solution was
base_value = base_value + merge[:separator].to_s + row[merge[:merge_row_index]]
I hope this helps somebody, 'cause as DigitalRoss alluded to, it was quite a wild goose chase nailing down where in the code this was being caused and why.
I got this error when parsing through an API for "tag/#{idnum}/parents"...Normally, you'd expect a response like this:
{
"parents": [
{
"id": 8,
"tag_type": "MarketTag",
"name": "internet",
"display_name": "Internet",
"angellist_url": "https://angel.co/internet",
"statistics": {
"all": {
"investor_followers": 1400,
"followers": 5078,
"startups": 13214
},
"direct": {
"investor_followers": 532,
"followers": 1832,
"startups": 495
}
}
}
],
"total": 1,
"per_page": 50,
"page": 1,
"last_page": 1
}
but when I looked up the parents of the market category "adult" (as it were), I got this
{
"parents": [ ],
"total": 0,
"per_page": 50,
"page": 1,
"last_page": 0
}
Now ruby allowed a number of interactions with this thing to occur, but eventually it threw the error about implicit conversion
parents.each do |p|
stats = p['statistics']['all']
selector << stats['investor_followers'].to_i
end
selected = selector.index(selector.max)
parents[selected]['id'] ***<--- CODE FAILED HERE
end
This was a simple fix for me.
When I was getting this error using the Scout app, one of my mapped folders was header-1, when I removed the hyphen from the folder name and made it header1, the error went away.
It didn't like the hyphen for some reason...

Resources