Skip to content

Instantly share code, notes, and snippets.

@camallen
Created October 6, 2012 10:14
Show Gist options
  • Save camallen/3844542 to your computer and use it in GitHub Desktop.
Save camallen/3844542 to your computer and use it in GitHub Desktop.
Nil Boolean Mongoid custom serialization with blank strings
class TriBoolean
attr_reader :value
def initialize(value)
@value = value
end
# Converts an object of this instance into a database friendly value.
def mongoize
return nil if boolean_blank?
Boolean.mongoize(value)
end
class << self
# Get the object as it was stored in the database, and instantiate
# this custom class from it.
def demongoize(object)
object
end
# Takes any possible object and converts it to how it would be
# stored in the database.
def mongoize(object)
TriBoolean.new(object).mongoize
end
# Converts the object that was supplied to a criteria and converts it
# into a database friendly form.
def evolve(object)
# https://groups.google.com/forum/?fromgroups=#!topic/mongoid/78dPs0_GnWU
mongoize(object)
end
end
private
def boolean_blank?
!value.is_a?(Boolean) && value.blank?
end
end
@mltsy
Copy link

mltsy commented Feb 12, 2019

FWIW - I found that Boolean.mongoize was returning a string for some reason (which ended up always storing and returning a string from the database), so I ended up using Boolean.evolve in place of that, in the mongoize function, which correctly converts "true" to a Boolean true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment