Sha256: 38ae17ed285cfb25439d33f31e31fb310d78ebb8416e391510e05d8f322abc0e

Contents?: true

Size: 737 Bytes

Versions: 2

Compression:

Stored size: 737 Bytes

Contents

# NilConditional Operator in Ruby

# Patch Object class
class Object
  def _?
    NilConditional.new(self)
  end
end

# Nil Conditional class
class NilConditional
  def initialize(object)
    @object = object
  end

  def method_missing(name, *params)
    if @object.respond_to?(name)
      return_value = nil
      if block_given?
        return_value = @object.public_send(name, *params, &Proc.new)
      else
        return_value = @object.public_send(name, *params)
      end
      return return_value unless return_value.nil?
    end
    self.class.new(@object)
  end

  def nil?
    true
  end

  def ==(other)
    return true if other.nil?
    super
  end

  def eql?(other)
    return true if other.eql?(nil)
    super
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nil_conditional-2.0.1 lib/nil_conditional.rb
nil_conditional-2.0.0 lib/nil_conditional.rb