Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

Groovy:

if there`s my_object -> access 'name' and capitalize

my_object?.name?.capitalize()

What is the equivalent for ruby to avoid a nil object to access attributes with this facility?

Thanks

like image 992
Luccas Avatar asked Jan 10 '12 15:01

Luccas


2 Answers

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
like image 137
Mischa Avatar answered Nov 15 '22 19:11

Mischa


The andand gem provides this functionality.

my_object.andand.name.andand.capitalize()
like image 43
Dave Newton Avatar answered Nov 15 '22 19:11

Dave Newton