lib/nil_conditional.rb in nil_conditional-1.0.0 vs lib/nil_conditional.rb in nil_conditional-2.0.0
- old
+ new
@@ -1,43 +1,38 @@
# NilConditional Operator in Ruby
+# Patch Object class
class Object
- def method_missing(name, *params)
- if name =~ /^__.+$/
- original = name.to_s.sub(/^__/, '').to_sym
-
- if block_given? && original =~ /^\w+$/
- binding = Proc.new.binding
- if binding.local_variable_defined?(original)
- var = binding.local_variable_get(original)
- return var unless var.nil?
- end
- end
-
- if respond_to?(original)
- return_value = block_given? ? send(original, *params, &Proc.new) :
- send(original, *params)
- return return_value unless return_value.nil?
- end
-
- NilConditional.new
- else
- super
- end
+ def _?
+ NilConditional.new(self)
end
end
+# Nil Conditional class
class NilConditional
+ def initialize(object)
+ @object = object
+ end
+
def method_missing(name, *params)
- return self.class.new
+ 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
+ return true if other.nil?
super
end
def eql?(other)
return true if other.eql?(nil)