Skip to content

Instantly share code, notes, and snippets.

@seanbollin
Created November 21, 2013 07:14
Show Gist options
  • Save seanbollin/7577272 to your computer and use it in GitHub Desktop.
Save seanbollin/7577272 to your computer and use it in GitHub Desktop.
Mongo Mapper Custom Type
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
@jwieringa
Copy link

Depending on what your looking for, I think we could improve the below; however, hopefully it demonstrates an alternative.

class Direction
  include MongoMapper::Document
  key :direction, String, required: true
  validate :direction_is_abbreviated

  LEDGER = {
    'n' => 'north',
    'ne' => 'northeast',
    'e' => 'east',
    'se' => 'southeast',
    's' => 'south',
    'sw' => 'southwest',
    'w' => 'west',
    'nw' => 'northwest',
    'd' => 'down',
    'u' => 'up'
  }

  def long
    LEDGER[direction]
  end

  def short
    direction
  end

  private

  def direction_is_abbreviated
    case
    when LEDGER.has_value? direction
      self.direction = LEDGER.index(direction)
    when LEDGER.has_key? direction
      self.direction = direction
    else
     errors.add(:direction, "Invalid direction. Use one or two letter short-hand notation.")
    end
  end

end

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