Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Collecting Inputs | Define conversions to user-defined types

概要

Define conversions to user-defined types

前提

Confident Rubyではメソッド内の処理を次のように分類しています。
・Collecting Inputs(引数チェック、変換など)
・Performing Work(主処理)
・Delivering Output(戻り値に関わる処理)
・Handling Failure(例外処理)

当記事は上記のうち、Collecting Inputsに関する話です。

詳細

状況

あなたのメソッドのロジックが、あなたが定義したクラスをinputに要求している。
可能なら対応したクラスの型に変換したい。

概要

オブジェクトを対象クラスのインスタンスに変換するための変換手続きを定義する。

理由

任意のオブジェクトを作るためのよく知られた手続きは、
第三者がまるで"native"であるかのように受け入れることができいる。

サンプルコード仕様

ファイナルファンタジーの回復キャラと
ドラクエの回復キャラに変換用のメソッドを定義します。

サンプルコード

# encoding: utf-8
class Priest
  attr_reader :recover_level
  def initialize(recover_level)
    @recover_level = recover_level
  end

  def cast_a_recover_spell
    recover_spells[recover_level]
  end
end

class FinalFantasy < Priest
  RECOVER_SPELLS = ['ケアル', 'ケアルラ', 'ケアルガ']

  def recover_spells
    RECOVER_SPELLS
  end

  def to_ff
    self
  end

  def to_dq
    DragonQuest.new(@recover_level)
  end
end

class DragonQuest < Priest
  RECOVER_SPELLS = ['ホイミ', 'ベホイミ', 'ベホマ']

  def recover_spells
    RECOVER_SPELLS
  end

  def to_dq
    self
  end

  def to_ff
    FinalFantasy.new(@recover_level)
  end
end

priests = [FinalFantasy.new(0), DragonQuest.new(1)]
priests.each do |priest|
  puts priest.to_ff.cast_a_recover_spell
  puts priest.to_dq.cast_a_recover_spell
end

出力

ケアル
ホイミ
ケアルラ
ベホイミ