Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's `.present?` without Rails?

I'm developing a "Rails-less" Ruby daemon for automation (although in theory it runs within a Rails directory). For general purposes and the principle of the matter, I would like to find the (most) "native"/common way to utilize a Ruby version of .present?/.blank?/.empty?/.nil? to identify if an array or a (hash) value exists and is not empty (i.e., [] or {}).

From what I've read (e.g., Stack Overflow) and tested, all of these functions appear to be Rails-specific methods, part of ActiveSupport(?).

Coming from other web/interpreter languages (PHP, Python, JS, etc.), this is a general logic function most languages (with arrays, which are most) have this functionality built in one way or another (e.g., PHP's isset( ... ) or JavaScript's .length).

I understand there are RegEx workarounds for .blank?, but .present? seems it would require exception handling to identify if it's "present"). I'm having a hard time believing it doesn't exist, but there's little talk about Ruby without Rails' involvement.

like image 255
Jonathan Avatar asked Oct 20 '25 21:10

Jonathan


1 Answers

Active Support is broken in small pieces so that you can load just what you need. For .blank? and .present? methods it would be enough to require:

require 'active_support/core_ext/object/blank.rb'

As docs say.

Object#nil? , Array#empty? and Hash#empty? already defined so you dont need anything to require to use those.

Make sure active_support gem installed in your system

like image 114
Martin Zinovsky Avatar answered Oct 22 '25 11:10

Martin Zinovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!