Is There an Equivalent Null Prevention on Chained Attributes of Groovy in Ruby

Is there an equivalent null prevention on chained attributes of groovy in ruby?

This works in Rails:

my_object.try(:name).try(:capitalize)

If you want it to work in Ruby you have to extend Object like this:

class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end

Source

In Rails it's implemented like this:

class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
else
__send__(*a, &b)
end
end
end

class NilClass
def try(*args)
nil
end
end

.? (existence) operator in ruby?

Easiest thing to do is use the andand gem, although there are some other, pretty trivially-implemented options, like this, or this, or etc.

Does Ruby have syntax for safe navigation operator of nil values, like in Groovy?

In a rails app there is Object#try

So you can do

obj1.try(:obj2).try(:value)

or with a block (as said on comments bellow)

obj.try {|obj| obj.value}

UPDATE

In ruby 2.3 there is operator for this:

obj&.value&.foo

Which is the same as obj && obj.value && obj.value.foo

Simplify multiple nil checking in Rails

Rails has object.try(:method):

if @parent.try(:child).try(:grand_child).try(:attribute).present?
do_something

http://api.rubyonrails.org/classes/Object.html#method-i-try

Equivalent of .try() for a hash to avoid undefined method errors on nil?

You forgot to put a . before the try:

@myvar = session[:comments].try(:[], @comment.id)

since [] is the name of the method when you do [@comment.id].

What's the Best Mailing List Package? (Linux)

There is a MySQL member adapter in

https://sourceforge.net/tracker/?func=detail&atid=300103&aid=839386&group_id=103

I haven't tried it, and from the readme, it seems you'll need some Python expertise to use it, however, there are also comments in the tracker by other people who have successfully used it.

What does &. (ampersand dot) mean in Ruby?

It is called the Safe Navigation Operator. Introduced in Ruby 2.3.0, it lets you call methods on objects without worrying that the object may be nil(Avoiding an undefined method for nil:NilClass error), similar to the try method in Rails.

So you can write

@person&.spouse&.name

instead of

@person.spouse.name if @person && @person.spouse

From the Docs:

my_object.my_method

This sends the my_method message to my_object. Any
object can be a receiver but depending on the method's visibility
sending a message may raise a NoMethodError.

You may use &. to designate a receiver, then my_method is not invoked
and the result is nil when the receiver is nil. In that case, the
arguments of my_method are not evaluated.



Related Topics



Leave a reply



Submit