Sha256: d95593997a71a30aa363d8932d9c676c1c91f4e289cb9908b1a73650b65ce3fa

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

# The dot operator calls methods on objects. Power Dots are dots with extra features
#
#   .? calls a method if the reciever is not nil, returns nil
#   otherwise. We have to write it ._?. in order to be valid Ruby
#
#   .try. calls a mehod only if the recipient resonds to that method 

require 'delegate'
require 'singleton'
require 'blankslate'

class Object

  def _?()
    self
  end
  
  def try
    CallIfAvailable.new(self)
  end

end

  
class NilClass
  def _?()
    SafeNil.instance
  end
end


class SafeNil 
  include Singleton
  
  def method_missing(method, *args, &b)
    return nil unless nil.respond_to? method
    nil.send(method, *args, &b) rescue nil
  end
end


alias DelegateClass_without_safe_nil DelegateClass 
def DelegateClass(klass)
  c = DelegateClass_without_safe_nil(klass)
  c.class_eval do 
    def _?
      self
    end
  end
  c
end


class CallIfAvailable < BlankSlate
  
  def initialize(target)
    @target = target
  end
  
  def method_missing(name, *args, &b)
    @target.send(name, *args, &b) if @target.respond_to?(name)
  end
  
end


Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
hobosupport-0.2 lib/hobosupport/methodcall.rb
hobosupport-0.7.3.99 lib/hobosupport/methodcall.rb
hobosupport-0.7.4 lib/hobosupport/methodcall.rb
hobosupport-0.7.5 lib/hobosupport/methodcall.rb