Sha256: 4ba842b4cdec5922badfbf38b1be2af4d091c7a32b6296ee0eed239a16470c21

Contents?: true

Size: 867 Bytes

Versions: 2

Compression:

Stored size: 867 Bytes

Contents

module ISO3166; end

class ISO3166::Country
  class BadMongoidTypeError < StandardError; end

  def mongoize
    ISO3166::Country.mongoize(self)
  end

  class << self

    def mongoize(country)
      if country.is_a?(self) && !country.data.nil?
        country.alpha2
      elsif self.send(:valid_alpha2?, country)
        new(country).alpha2
      else
        raise BadMongoidTypeError.new('Given value is neither a valid country object nor a valid alpha2 code')
      end
    end

    def demongoize(alpha2)
      new(alpha2)
    end

    def evolve(country)
      mongoize(country)
    end

    private

    def valid_alpha2?(country)
      return false unless country.is_a?(String)

      if ISO3166::Country.new(country).nil?
        raise BadMongoidTypeError.new('Given string is not a valid alpha2 code.')
      else
        true
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
countries-0.10.0 lib/countries/mongoid.rb
countries-0.9.3 lib/countries/mongoid.rb