Sha256: 467524c23ac6a706502a173a9b23a7ef4f3ca35263b119036161fc8e30cac7a4

Contents?: true

Size: 1.04 KB

Versions: 6

Compression:

Stored size: 1.04 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

6 entries across 6 versions & 1 rubygems

Version Path
hobosupport-0.8.1 lib/hobosupport/methodcall.rb
hobosupport-0.8.4 lib/hobo_support/methodcall.rb
hobosupport-0.8 lib/hobosupport/methodcall.rb
hobosupport-0.8.2 lib/hobosupport/methodcall.rb
hobosupport-0.8.3 lib/hobosupport/methodcall.rb
hobosupport-0.8.5 lib/hobo_support/methodcall.rb