Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1786

Case Statements don't work with Mongoid document instances

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.4.7
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      The Object #=== method is defined as "case equality", being the equality that you'd like to enforce in case statements. In mongoid this is now class-equality. This means you can build a case statement in mongoid around classes, but not regular mongoid document instances.

      Take the example below:

      class A
        include Mongoid::Document
      end
      
      a = A.new
      b = A.new
      
      puts a == a # Returns true
      puts a == b # Returns false
      puts a === b # Returns true as mongoid === only checks class equality
      
      case a
        when b
          puts "Printed because A and B are the same class... This doesn't seem intuitive"
        when a
          puts "This should be printed, but isn't."
      end
      
      case a.id
        when b.id
          puts "Not printed as they don't match"
        when a.id
         puts "This is printed as the id === id uses the Ruby Object rules"
      end
      

      Having a specific class/subclass match does seem useful if one of the objects is a class – however, if they are both regular instances it would make more sense to use equals.

      Current workaround is to use the id insstead. e.g. "case a.id...".

            Assignee:
            Unassigned Unassigned
            Reporter:
            jonathannen Jon Williams
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: