Module: Corefines::Object::ThenIf

Defined in:
lib/corefines/object.rb

Instance Method Summary collapse

Instance Method Details

#then_if(*conditions) {|self| ... } ⇒ Object

Returns self if self or any of the conditions evaluates to false, otherwise returns the evaluation of the block.

Each condition may be of the type:

  • Symbol - name of the method to be invoked using public_send.

  • Array - name of the method followed by arguments to be invoked using public_send.

  • Proc - proc to be called with self as the argument.

  • Any other object to be evaluated as true, or false.

Examples:

"foo".then_if(:empty?) { "N/A" } # => "foo"
   "".then_if(:empty?) { "N/A" } # => "N/A"

Yields:

  • (self)

    gives self to the block.


267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/corefines/object.rb', line 267

module ThenIf
  refine ::Object do
    def then_if(*conditions)
      return self if conditions.empty? && !self
      return self unless conditions.all? do |arg|
        case arg
        when ::Symbol then public_send(arg)
        when ::Array then public_send(*arg)
        when ::Proc then arg.call(self)
        else arg
        end
      end
      yield self
    end
  end
end