I have the following check for nil:
client = !deal['deal']['party']['party'].nil? ? deal['deal']['party']['party']['company_id'] : ""
but still I get:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
How can I prevent this?
I don't know Ruby, but I think it goes wrong before the .nil:
deal['deal']['party']['party']
^ ^ ^
The arrows indicate possible nil indexes. For example, what if ["deal"] is nil or the first ["party"] is nil?
You might want to have a look at the andand game:
http://andand.rubyforge.org/
By checking !deal.nil? and !deal['deal'].nil? and !deal['deal']['party'].nil? and !deal['deal']['party']['party'].nil?
At each step, you can use an appropriate method built in NilClass to escape from nil, if it were array, string, or numeric. Just add to_hash to the inventory of this list and use it.
class NilClass; def to_hash; {} end end
client = deal['deal'].to_hash['party'].to_hash['party'].to_hash['company_id'].to_s
You can also do:
client = deal.fetch('deal', {}).fecth('party', {}).fetch('party', {}).fetch('company_id', '')
Related
Can someone simply explain to me how null assertion (!) works and when to use it?
The ! operator can be used after any expression, e!.
That evaluates the expression e to value v, then checks whether v is the null value. If it is null, an error is thrown. If not, then e! also evaluates to v.
The static type of an expression e! is (basically) the static type of e with any trailing ?s remove. So, if e has type int?, the type of e! is int.
You should not use e! unless e can be null (the type of e is potentially nullable).
The ! operator is dynamically checked. It can throw at runtime, and there is no static check which can guarantee that it won't. It's like using a value with type dynamic in that all the responsibility of preventing it from throwing is on the author, the compiler can't help you, and you need good tests to ensure that it won't throw when it's not supposed to.
It's called an assertion because it should never throw in production code.
So, use e! when you know (for some reason not obvious to the compiler, perhaps because of some invariant guaranteeing that the value is not null while something else is true) that e is not null.
Example:
abstract class Box<T extends Object> {
bool hasValue;
T? get value;
}
...
Box<int> box = ...;
if (box.hasValue) {
var value = box.value!;
... use value ...
}
If you are repeatedly using ! on the same expression, do consider whether it's more efficient to read it into a local variable just once.
Also, if (like this Box example) the value being null is equivalent to the other test you just did, maybe just check that directly:
Box<int> box = ...;
var value = box.value;
if (value != null) {
... use value ...
}
This code, with an explicit != null check on a local variable, is statically guaranteed to not throw because the value is null.
The code using ! above relies on the author to maintain whichever invariant allowed them to write the !, and if something changes, the code might just start throwing at runtime. You can't tell whether it's safe just by looking at the code locally.
Use ! sparingly, just like the dynamic type and late declarations, because they're ways to side-step the compiler's static checking and ensure it that "this is going to be fine". That's a great feature when you need it, but it's a risk if you use it unnecessarily.
I want to check if resource[:contractor] (resource is a hash) includes bank_transfer.creaditor_name (which is string) like below:
resource['contractor'].include?(bank_transfer.creditor_name)
I need to cover case when bank_transfer.creditor_name = nil - how to do that using ruby safe operator ? With current implementation I'm getting an error:
TypeError:
no implicit conversion of nil into String
From the business perspective I cannot just do:
bank_transfer.creditor_name&.include?(resource['contractor'])
Why don't you just check for nil upfront?
bank_transfer.creditor_name &&
resource['contractor'].include?(bank_transfer.creditor_name)
There is a JSONB information field with this structure:
{
"ignore"=>false
}
I want to get all records whose ignore field is true:
#user.posts.where("information ->> 'ignore' = TRUE")
This line throws an error:
PG::UndefinedFunction: ERROR: operator does not exist: text = boolean
And I could not find anything in Google. Everywhere we are talking about textual meanings. But there is nothing about booleans.
You must cast the result of information->>'ignore' to boolean:
#user.posts.where("(information ->> 'ignore')::boolean = TRUE")
I had the same issue in upgrading to Rails 5/6. It seems the way the pg gem casts has changed a little, but this works for me:
#user.posts.where("(information ->> 'ignore')::boolean = ?", true)
When an argument is added as the second parameter to a where method call, ActiveRecord will do the work to cast this appropriately for you. If you add .explain to the query above, you should see something like:
EXPLAIN for: SELECT ... AND ((information ->> 'ignore')::boolean = TRUE) ...
I am trying to mod a Lua game (CtGW). There is a function, engine:GetSavegames, which returns an array of strings, and I cannot access. I need to modify the returned results. I tried the following, but recieved a "function arguments expected near 'engine'" error.
getsaves = engine:GetSavegames
engine:GetSavegames = function()
return getsaves()
end
engine:GetSavegames is only valid syntax for method invocation and not for assignments. As #ChrisBeck wrote in the comment, you need to use engine.GetSavegame, but you also need to pass any parameters you can get as those will include the actual object.
Something like this may work:
local getsaves = engine.GetSavegames
engine.GetSavegames = function(...)
return getsaves(...)
end
This operation is usually called monkeypatching.
I have a problem with classes. I got below error:
Attempt to index local 'self' (a nil value)
When I call the getter method of below class.
Item.lua file:
require "classlib"
Item = class("Item")
function Item:__init()
self.interval = 1
end
function Item:getInterval()
return self.interval
end
I'm calling this getter function like this:
dofile("../src/item.lua")
item = Item()
function test_item()
assert_equal(1, item.getInterval())
end
What's the problem here?
Kind regards...
In general, you should call member functions by :.
In Lua, colon (:) represents a call of a function, supplying self as the first parameter.
Thus
A:foo()
Is roughly equal to
A.foo(A)
If you don't specify A as in A.foo(), the body of the function will try to reference self parameter, which hasn't been filled neither explicitly nor implicitly.
Note that if you call it from inside of the member function, self will be already available:
-- inside foo()
-- these two are analogous
self:bar()
self.bar(self)
All of this information you'll find in any good Lua book/tutorial.
the obj:method is just syntactictal sugar for:
definition:
function obj:method(alpha) is equivalent to obj.method(self,alpha)
execution:
obj:method("somevalue") is equivalent to obj.method(obj,"somevalue") Regards
Change:
assert_equal(1, item.getInterval())
to:
assert_equal(1, item:getInterval())
In Lua, it was some ridiculous for error reporting. From class point of view, the .getInterval() method should called with a self parameter, while the :getInterval() method is implicitly included the self parameter. And the syntax error should labeled in the called point, not the definition-body of getInterval().
In traditional, while you miscalled a method, it was not the method's fault, but the caller.