short for: bar != null ? 'foo$bar' : null - dart

Is there a shorter more idiomatic way to implement the ternary null check expression to set the picture?
final ownUser = User(
id: user.id,
displayName: user.displayName ?? 'Anonymous',
picture: user.avatarId != null ? '${apiBase}/avatars/${user.avatarId}' : null,
);
This logic is quite common on a daily basis and our code base would benefit a lot readability if we could express this in a more idiomatic way, especially removing to state null twice ((1) in the condition and (2) as the result in the else case). But I wonder if any operator even get's rid of the null, e.g. something like this
read: "null or this expression"
picture: user.avatarId ?:! '${apiBase}/avatars/${user.avatarId}',

Related

Is there a way to do logical OR between two {#eq} conditionals?

I am looking for a way to do logical OR between two {#eq} conditionals. Can I do it in some straightforward way?
For illustration, consider example below. I am iterating over result array. If grp argument is equal to all, I don't want to filter what goes to the page. If it is not equal to all, then I want to filter the array elements by group property being equal to grp. The condition would be expressed as (grp == "all" || group == grp) in JS. Currently, without any way to do OR between the two conditions, I have to repeat the BODY of the loop -- going against the DRY principle.
{#result grp=grp}
{#eq key=grp value="all"}
BODY
{:else}
{#eq key=group value=grp}
BODY
{/eq}
{/eq}
{/result}
The special {#any} helper allows you to express logical OR. (There is also a {#none} helper for logical NAND.)
{#result grp=grp}
{#select}
{#eq key=grp value="all"/}
{#eq key=group value=grp/}
{#any}BODY{/any}
{/select}
{/result}
If you need to do something more complex than that-- for example, if BODY is dependent on the value of grp and group-- you can always write a custom Dust helper to move your logic into Javascript. Here's a short example of what that would look like, and you can read further in the documentation on context helpers.
{
"filter": function(chunk, context, bodies, params) {
var group = context.resolve(params.group);
var grp = context.resolve(params.grp);
if (grp == "all" || group == grp) {
chunk = chunk.render(bodies.block, context.push({
somethingNewBasedOff: "the value of group and grp"
}));
}
return chunk;
}
}
And then you'd use it like:
{#result grp=grp}
{#filter group=group grp=grp}
The filter test passed. The new data I added to the context is {somethingNewBasedOff}
{/filter}
{/result}

Append strings if not nil

In the view of a rail's app, I want to achieve:
If user's height isn't nil: return the height value with string "cm"
Otherwise: return string "N/A".
I'm wondering if there's a way to do this. The code below:
user.try(:profile_name).try(:push("as Alias")) || "N/A"
isn't working. The part try(:push("cm")) gives me an error. I thought of using the << operator to append strings by using , but I think there should be a neater way to complete this. Is there anyone who can give me a hint?
--another similar example which I want to accomplish but not working:
user.try(:height).try(:to_s).try(:push("cm")) || "N/A"
How about:
(user && user.profile.present?) ? "#{user.profile} as Alias" : 'N/A'

Grails GSP null safety check trouble

I am trying to populate a text field on my GSP as such:
<label>Phone(aaa-bbb-cccc):</label>&nbsp<g:textField name="phone" style ="border-radius: 5px"
value="${recordToEdit.telephones = [] ? null : recordToEdit.telephones.first()}"></g:textField><br>
but it still tell me I can't access first() on an empty list. telephones is a List of Strings each being a phone number.
as #gross-jonas pointed out, the recordToEdit.telephones = [] ? .. : .. is terribly wrong already, unless it's a typo
the check you are trying to make should look like:
value="${recordToEdit.telephones ? recordToEdit.telephones.first() : ''}"
or
value="${recordToEdit.telephones?.getAt( 0 ) ?: ''}"
You can just use the Null Safe Operator (?.) as
${recordToEdit.telephones?.first()}
for null checks, which is not sufficient.
UPDATE
for empty list checks and null checks,
${ recordToEdit.telephones ? recordToEdit.telephones[0] : '' }
will be good.
Dude, didn't you just mean == instead of = ?
It looks like you are overwriting your telephones which get issued successfully instead of comparing it.

FirstOrDefault on List not working

I have a list like
var listDataDemo = model.Jobs.ToList();
The listDataDemo has data like following
Count = 13
[0]: {PaymentItemModel}
when i type in Immediate Window like
listData.FirstOrDefault()
it gives result
Amount: 0
Date: {1/01/0001 12:00:00 AM}
Method: "PayPal"
PayerName: null
PayerNumber: null
PaymentDetailType: Payment
TransactionId: null
But when i write(code in my class)
var demoVal = listData.FirstOrDefault(p=>p.Method=="PayPal")
The name 'demoVal' does not exist in the current context(no value)
How to get a value from LIST.
Please help me.
The below code is working fine for me. Just have a look:
List<test> testList = new List<test>();
testDB testObj = new testDB();
testList = testObj.fn_getAll();
var abc = testList.FirstOrDefault(a => a.Id == 3);
And you just try to change the name of the variable, this might be causing the issue.
I hope it will help you.. :)
Off the cuff, the predicate you're providing to FirstOrDefault to filter results looks like it has a syntax error: (p=>p.Method="PayPal") should be (p=>p.Method=="PayPal").
Granted this was probably a typo, for completeness:
'=' is an assignment operator, for when you want to assign a value to a variable.
'==' is an equality comparison operator, for when you want to test equality between values and get 'true' or 'false'.
Edited to answer beyond the typo...
Are you using Entity Framework?
EF has extension methods for FirstOrDefault also, except the filter parameter is an SQL query. If you're using EF, then you could be missing the following:
using System.Collections.Generic;
using System.Linq;
It looks like the predicate in your call to FirstOrDefault has a typo. You want == for comparison, not = for assignment.

Error using Ruby OR in if

I have this simple condition in my ruby code:
if user.text != ("Empty" || "Damaged")
do something...
the thing is that when it is "Damaged" it still enters the loop, so I have to use this:
if user.text != "Empty"
if user.text != "Damaged"
...
..
What is the correct syntax to make the first one work?
Thanks!
Use this:
unless ["Empty", "Damaged"].include?(user.text)
...
end
The problem with your first approach is that a || b means that: if a != nil then it is a, else it is b. As you can see it is good for variables, not constants as they are rarely nil. Your expression ("Empty" || "Damaged") simply equals "Empty".
You want to use the this as a binary operator, the correct form would be:
if (user.text != "Empty") && (user.text != "Damaged")
The upper solution is just shorter. It consists of an array of elements you want to avoid, and you just simply check is the user.text is not present in it.
#Matzi has the right answer, for sure. But here's why what you're doing is failing:
Your statement ("Empty" || "Damaged") evaluates to "Empty"
You're saying return either one of these, whichever non-false thing you find first. In Ruby, any string, number or Object returns true, so you return "Empty" every time.
A better way to lay it out if you really want to use an if statement:
if user.text != "Empty" && user.text != "Damaged"
...
end
I assume, by the way, that you're trying to say "If the user text is neither Damaged nor Empty".
Hope that helps.
if ((text != "Empty") && (text != "Damaged"))

Resources