Do something if value is present

I often find that I am writing Ruby code where I check for the presence of a value and then do something with that value if it is present. For instance.

if some_object.some_attribute.present? call_something(some_object.some_attribute) end 

I think it would be cool if it could be written as

 some_object.some_attribute.presence { |val| call_something(val) } => the return value of call_something 

Does anyone know if there is such a function in Ruby, or although support is active?

I opened a transfer request for this function.

+6
source share
3 answers

You can use a combination of presence and try :

If try is called without arguments, it returns the given block to the receiver, if it is not nil :

 'foo'.presence.try(&:upcase) #=> "FOO" ' '.presence.try(&:upcase) #=> nil nil.presence.try(&:upcase) #=> nil 
+11
source

You can try

 do_thing(object.attribute) if object.attribute 

This is normal if the attribute is not logical. In this case, it will not call if false.

If your attribute may be false, use .nil? .

 do_thing(object.attribute) unless object.attribute.nil? 
+2
source

Despite the lack of such functionality out of the box, you can do:

 some_object.some_attribute.tap do |attr| attr.present? && call_smth(attr) end 

On the other hand, Rails provides so many monkeypatches that one could add one to this circus:

 class Object def presense_with_rails raise 'Block required' unless block_given? yield self if self.present? # requires rails end def presense_without_rails raise 'Block required' unless block_given? skip = case self when NilClass, FalseClass then true when String, Array then empty? else false end yield self unless skip end end 
0
source

All Articles