rubydaemonstandard-librarydaemonsruby-daemons

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.


Solution

  • 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