avdi / naught

A toolkit for building Null Object classes in Ruby
MIT License
1.05k stars 53 forks source link

Basic question regarding truthiness #62

Closed tastycode closed 10 years ago

tastycode commented 10 years ago

So, I would love to use this, but it doesn't really mimic nil

with ruby

e = nil
puts "meow" if e # nothing printed

with naught

Null = Naught.build do |config|
  config.black_hole
  def nil?; true; end
end
e = Null.new
puts "meow" if e # => "meow"

I at least need null objects to have the "truthiness of false", that is when !!Null.new == false

I know that I'm probably not "thinking of this from the right perspective", could you enlighten me?

Just for fun, I ventured to see if i could get the behavior i was looking for, but had to use refinements as defining method on nil actually modifies all nil :(

module NayExtensions
  refine NilClass do
    def method_missing(name, *)
      self
    end

    def respond_to?(*)
      true
    end
  end
end

class Special
  using NayExtensions

  def meow
    nil
  end

  def purr
    meow.bar
  end
end

class NonSpecial
  def meow
    nil
  end

  def purr
    meow.bar
  end
end

puts "meow" unless Special.new.purr
puts "bark" unless NonSpecial.new.purr # => undefined method `bar' for nil:NilClass
avdi commented 10 years ago

I wrote an article about this: http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/

Bottom line, trying to make a non-nil object act "falsy" is a fool's errand in Ruby.

avdi commented 10 years ago

I mean, you can override unary ! to do what you want in Ruby, but that's just going to make the cases you can't control less consistent.

tastycode commented 10 years ago

You are right... i don't want to know.. i just want to do nothing in most cases. I just don't want one of these special objects getting too far out there.