Class: JpPrefecture::Prefecture::Finder

Inherits:
Object
  • Object
show all
Defined in:
lib/jp_prefecture/prefecture/finder.rb

Overview

都道府県の検索を行うクラス

Constant Summary collapse

NAME_FIELDS =

名前を前方一致で検索できる項目

%i[name name_e name_r name_h name_k].freeze
FIELDS =

find で検索できる項目

(NAME_FIELDS + %i[code zip all_fields]).freeze

Instance Method Summary collapse

Constructor Details

#initializeFinder

Returns a new instance of Finder.



16
17
18
# File 'lib/jp_prefecture/prefecture/finder.rb', line 16

def initialize
  @mapping = Mapping.data
end

Instance Method Details

#find(field:, value:) ⇒ JpPrefecture::Prefecture?

指定した項目を検索

Parameters:

  • field (Symbol)

    検索する項目。nil の場合は都道府県コードとして扱う

  • value (String, Integer)

    検索する内容

Returns:

  • (JpPrefecture::Prefecture)

    都道府県が見つかった場合は都道府県インスタンス

  • (nil)

    都道府県が見つからない場合は nil



26
27
28
29
# File 'lib/jp_prefecture/prefecture/finder.rb', line 26

def find(field:, value:)
  code = find_code(field, value)
  JpPrefecture::Prefecture.build_by_code(code)
end

#where(field:, value:) ⇒ Array<JpPrefecture::Prefecture>

指定した項目を前方一致で検索し、一致したすべての都道府県を返す

Parameters:

  • field (Symbol)

    検索する項目。NAME_FIELDS 以外を指定した場合は空配列

  • value (String)

    検索する内容

Returns:



36
37
38
39
40
41
42
43
44
# File 'lib/jp_prefecture/prefecture/finder.rb', line 36

def where(field:, value:)
  return [] unless NAME_FIELDS.include?(field)

  value = value.to_s.downcase
  return [] if value.empty?

  @mapping.select { |_code, names| names[field].start_with?(value) }
          .map { |code, _names| JpPrefecture::Prefecture.build_by_code(code) }
end