Module: Iso::Country::Finders

Included in:
Country
Defined in:
lib/iso-country/finders.rb

Instance Method Summary collapse

Instance Method Details

#allObject



4
5
6
# File 'lib/iso-country/finders.rb', line 4

def all
  @countries.values || {}
end

#find(*args) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/iso-country/finders.rb', line 8

def find(*args)
  unless args.first.is_a?(Symbol)
    raise ArgumentError, 'Find takes one or more symbol IDs. Try #where'
  end

  case args.first
  when :all
    send(args.first)
  else
    find_with_ids(*args)
  end
end

#find_one(id) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/iso-country/finders.rb', line 32

def find_one(id)
  unless @countries[id]
    raise CountryNotFound, "Couldn't find Country with id=#{id}"
  end

  @countries[id]
end

#find_some(ids) ⇒ Object



40
41
42
# File 'lib/iso-country/finders.rb', line 40

def find_some(ids)
  ids.map {|id| find_one(id) }
end

#find_with_alpha2(alpha2) ⇒ Object



66
67
68
# File 'lib/iso-country/finders.rb', line 66

def find_with_alpha2(alpha2)
  all.find {|country| country.alpha2 == alpha2.to_s.upcase }
end

#find_with_alpha3(alpha3) ⇒ Object



70
71
72
# File 'lib/iso-country/finders.rb', line 70

def find_with_alpha3(alpha3)
  all.find {|country| country.alpha3 == alpha3.to_s.upcase }
end

#find_with_ids(*ids) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/iso-country/finders.rb', line 21

def find_with_ids(*ids)
  case ids.size
  when 0
    raise "Couldn't find Country without an ID"
  when 1
    find_one(ids.first)
  else
    find_some(ids)
  end
end

#find_with_name(name, locale = nil) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/iso-country/finders.rb', line 78

def find_with_name(name, locale = nil)
  if !locale
    all.find {|country| country.names.values.include?(name) }
  else
    all.find {|country| country.names[locale] == name }
  end
end

#find_with_numeric(numeric) ⇒ Object



74
75
76
# File 'lib/iso-country/finders.rb', line 74

def find_with_numeric(numeric)
  all.find {|country| country.numeric == numeric.to_i }
end

#where(opts) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/iso-country/finders.rb', line 44

def where(opts)
  if opts.is_a?(Array) || opts.is_a?(Symbol)
    find(opts)
  elsif opts.is_a?(String) && opts.length == 2
    find_with_alpha2(opts)
  elsif opts.is_a?(String) && opts.length == 3
    find_with_alpha3(opts)
  elsif opts.is_a?(String) && opts.length > 3
    find_with_name(opts)
  elsif opts.is_a?(Numeric)
    find_with_numeric(opts)
  else
    if opts[:alpha2]
      find_with_alpha2(opts[:alpha2])
    elsif opts[:alpha3]
      find_with_alpha3(opts[:alpha3])
    elsif opts[:numeric]
      find_with_numeric(opts[:numeric])
    end
  end
end