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

demongoize custom field on pluck

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major - P3
    • Resolution: Fixed
    • None
    • 7.4.0
    • Query
    • Fully compatible with feature flag
    • Fully Compatible

    Description

      When doing a pluck on a custom field it would be nice if the value was 'demongoized'. For example

      class CustomField
        attr_reader :value
       
        def initialize(value)
          @value = value.to_s
        end
       
        def to_s
          value
        end
       
        def as_json
          value
        end
       
        # Converts an object of this instance into a database friendly value.
        def mongoize
          @mongoize ||= Base64.encode64(value)
        end
       
        # Get the object as it was stored in the database, and instantiate
        # this custom class from it.
        def self.demongoize(object)
          self.new(Base64.decode64(object))
        end
       
        # Takes any possible object and converts it to how it would be
        # stored in the database.
        def self.mongoize(object)
          self.new(object).mongoize
        end
       
        # Converts the object that was supplied to a criteria and converts it
        # into a database friendly form.
        def self.evolve(object)
          self.new(object).mongoize
        end
      end
       
      class Report
        include Mongoid::Document
       
        field :my_field, type: CustomField
      end
       
      Report.delete_all
      Report.create!(my_field: 'test')
      my_field = Report.first.my_field
      puts my_field # => expected 'test', actual 'test'
      puts my_field.class # => expected CustomField, actual CustomField
      my_field = Report.pluck(:my_field).first
      puts my_field # => requested 'test', currently "dGVzdA=="
      puts my_field.class # => requested CustomField, currently String
      

      So it would be helpful if the pluck decoded the base64 encoding using the demongoize method

      Attachments

        Issue Links

          Activity

            People

              neil.shweky@mongodb.com Neil Shweky (Inactive)
              jonathag@cisco.com Jonathon Gardner
              Votes:
              1 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: