Module: Basho::ActiveRecord::PostalAutoResolve Private

Defined in:
lib/basho/active_record/postal_auto_resolve.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

郵便番号変更時に +before_save+ で住所カラムを自動解決する。 Base#basho_postal のマッピングオプション指定時に使用される。

Constant Summary collapse

MAPPING_KEYS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

サポートするマッピングキーの一覧

%i[prefecture city town prefecture_code city_code].freeze

Class Method Summary collapse

Class Method Details

.install(model_class, postal_column, mappings) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

モデルに +before_save+ コールバックを登録する。

Parameters:

  • model_class (Class)

    ActiveRecordモデルクラス

  • postal_column (String)

    郵便番号カラム名

  • mappings (Hash)

    マッピング設定



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/basho/active_record/postal_auto_resolve.rb', line 21

def install(model_class, postal_column, mappings)
  unless model_class.respond_to?(:before_save)
    raise Basho::Error, "#{model_class} does not support before_save callbacks"
  end

  postal_col = postal_column.to_s
  resolved = mappings.slice(*MAPPING_KEYS).transform_values(&:to_s).freeze

  model_class.before_save do
    next unless will_save_change_to_attribute?(postal_col)

    postal = Basho::PostalCode.find(send(postal_col))

    resolved.each do |key, target_col|
      send(:"#{target_col}=", PostalAutoResolve.resolve_value(postal, key))
    end
  end
end

.resolve_city_code(postal) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

郵便番号データから自治体コードを逆引きする。

Parameters:

Returns:

  • (String, nil)

    6桁自治体コード



61
62
63
64
# File 'lib/basho/active_record/postal_auto_resolve.rb', line 61

def resolve_city_code(postal)
  City.where(prefecture_code: postal.prefecture_code)
      .find { |c| c.full_name == postal.city_name }&.code
end

.resolve_value(postal, key) ⇒ String, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

マッピングキーに対応する値を郵便番号データから解決する。

Parameters:

  • postal (PostalCode, nil)

    郵便番号データ

  • key (Symbol)

    マッピングキー

Returns:

  • (String, Integer, nil)


45
46
47
48
49
50
51
52
53
54
55
# File 'lib/basho/active_record/postal_auto_resolve.rb', line 45

def resolve_value(postal, key)
  return nil unless postal

  case key
  when :prefecture      then postal.prefecture_name
  when :city            then postal.city_name
  when :town            then postal.town
  when :prefecture_code then postal.prefecture_code
  when :city_code       then resolve_city_code(postal)
  end
end