Created
October 6, 2012 10:14
-
-
Save camallen/3844542 to your computer and use it in GitHub Desktop.
Nil Boolean Mongoid custom serialization with blank strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 usingBoolean.evolve
in place of that, in themongoize
function, which correctly converts"true"
to a Booleantrue