Module: JpPrefecture::Base

Defined in:
lib/jp_prefecture/base.rb

Instance Method Summary collapse

Instance Method Details

#jp_prefecture(column_name, options = {}) ⇒ Object

モデル内で使用するための設定を行う

変換対象のカラムを指定する:

class Place < ActiveRecord::Base
  include JpPrefecture
  jp_prefecture :prefecture_code
end

p = Place.new
p.prefecture_code = 1
p.prefecture
# => #<JpPrefecture::Prefecture:0x007fd0a3d10f30 @code=1, @name="北海道", @name_e="Hokkaido">

生成するメソッド名は method_name で指定する:

class Place < ActiveRecord::Base
  include JpPrefecture
  jp_prefecture :prefecture_code, method_name: :pref
end

p = Place.new
p.prefecture_code = 1
p.pref
# => #<JpPrefecture::Prefecture:0x007fcb8444dcc8 @code=1, @name="北海道", @name_e="Hokkaido">

Parameters:

  • column_name (Symbol)

    変換対象のカラム

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :method_name (Symbol)

    生成するメソッド名。デフォルト: :prefecture


33
34
35
36
37
38
39
40
# File 'lib/jp_prefecture/base.rb', line 33

def jp_prefecture(column_name, options = {})
  column_name = column_name.to_sym if column_name.is_a?(String)
  method_name = options[:method_name] || :prefecture

  define_method method_name do
    JpPrefecture::Prefecture.find(send(column_name))
  end
end