Sha256: 99fd09c6429fc990a22be75f895c66976141313830ec66f4c4a01d279c1ed5a6

Contents?: true

Size: 1.22 KB

Versions: 1

Compression:

Stored size: 1.22 KB

Contents

#
# Cities
#
class City
  include Mongoid::Document
  include Mongoid::Geospatial
  include Geopolitocracy

  field :zip,    type: String
  field :area,   type: Integer  # m2 square area
  field :souls,  type: Integer  # Population
  field :geom,   type: Point,   spatial: true

  alias_method :population, :souls

  spatial_scope :geom

  attr_writer :x, :y, :z

  belongs_to :region
  belongs_to :nation
  has_many :hoods

  before_validation :set_defaults, on: [:create]

  validates :name, uniqueness: { scope: :region_id }
  validate :region_inside_nation

  def region_inside_nation
    return if !region || region.nation == nation
    errors.add(:region, "not inside Nation")
  end

  def set_defaults
    self.nation ||= region.try(:nation)
    return unless City.where(slug: slug).first
    self.slug += "-#{region.abbr}"
    return unless City.where(slug: slug).first
    fail "Two cities with the same name in #{region}: '#{slug}'"
  end

  def ==(other)
    other && slug == other.slug
  end

  def <=>(other)
    slug <=> other.slug
  end

  def with_region
    return name unless region
    "#{name}/#{region.abbr || region.name}"
  end

  def with_nation
    with_region + '/' + nation.abbr
  end

  def to_s
    with_region
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
geopolitical-0.8.8 app/models/city.rb