Search code examples
ruby-on-railsrubyhanami

Have Hanami an alternative for .present?


Rails has useful present? method. How can I check the same in Hanami?


Solution

  • present? is the opposite of blank? in Ruby on Rails.

    You could use Hanami::Utils::Blank:

    require 'hanami/utils/blank'
    
    Hanami::Utils::Blank.blank?(nil)     #=> true
    Hanami::Utils::Blank.blank?(' ')     #=> true
    Hanami::Utils::Blank.blank?('Artur') #=> false
    

    However there are two concerns:

    This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

    You could use ActiveSupport without Ruby on Rails

    Active Support is a collection of utility classes and standard library extensions. It's a separate gem and you can use it independently.

    You could extend Object:

    class Object
      def blank?
        respond_to?(:empty?) ? !!empty? : !self
      end
    
      def present?
        !blank?
      end
    end
    

    And the last option

    You may prefer using pure Ruby and its nil? and empty? methods if semantics is suitable.