Created
November 21, 2013 07:14
-
-
Save seanbollin/7577272 to your computer and use it in GitHub Desktop.
Mongo Mapper Custom Type
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 Direction | |
attr_reader :short, :long | |
def self.to_mongo(value) | |
case value.long | |
when 'north' | |
'n' | |
when 'northeast' | |
'ne' | |
when 'east' | |
'e' | |
when 'southeast' | |
'se' | |
when 'south' | |
's' | |
when 'southwest' | |
'sw' | |
when 'west' | |
'w' | |
when 'northwest' | |
'nw' | |
when 'down' | |
'd' | |
when 'up' | |
'u' | |
when 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'd', 'u' | |
value | |
else | |
raise 'Invalid direction.' | |
end | |
end | |
def self.from_mongo(value) | |
value.is_a?(self) ? value : Direction.new(value) | |
end | |
def initialize(value) | |
if value == 'north' or value == 'northeast' or value == 'east' or value == 'southeast' or value == 'south' or value == 'southwest' or value == 'west' or value == 'northwest' or value == 'up' or value == 'down' | |
raise 'Invalid direction. Use two-letter short-hand notation.' | |
end | |
case value | |
when 'n' | |
@short = value | |
@long = 'north' | |
when 'ne' | |
@short = value | |
@long = 'northeast' | |
when 'e' | |
@short = value | |
@long = 'east' | |
when 'se' | |
@short = value | |
@long = 'southeast' | |
when 's' | |
@short = value | |
@long = 'south' | |
when 'sw' | |
@short = value | |
@long = 'southwest' | |
when 'w' | |
@short = value | |
@long = 'west' | |
when 'nw' | |
@short = value | |
@long = 'northwest' | |
when 'u' | |
@short = value | |
@long = 'up' | |
when 'd' | |
@short = value | |
@long = 'down' | |
else | |
raise 'Invalid direction.' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Depending on what your looking for, I think we could improve the below; however, hopefully it demonstrates an alternative.