0
0

More than 5 years have passed since last update.

Rails黒魔術

Last updated at Posted at 2017-04-13

Railsの黒魔術

少し前の出来事、
大急ぎでシステムを作ろうとしたために、同僚とのコミュニケーション不足で似たような役割のクラスを
全く違う名前で作ってしまった。とりあえずの応急処置としてどうするか。

golf_price.rb
class GolfPrice
  # code
  # name
end
hotel_pack_content.rb
class HotelPackContent
  # handling_code
  # content_name
end
hotel_pack_content.rb
class HotelPackContent
  def code
    handling_code
  end
  def name
    content_name
  end
end

HotelPrice = HotelPackContent

しかし、このままではrails cで先にHotelPackContentを書いた後でしかHotelPriceが使えない。
いきなりHotelPrice.allと書こうものなら、未定義です!と怒られる。
HotelPackContentモデルをコピって以下のようにする。

hotel_price.rb
class HotelPackContent
  def code
    handling_code
  end
  def name
    content_name
  end
end

HotelPrice = HotelPackContent

これで、rails cでいきなりHotelPrice.allとしても動くようになった。
コピったのを変更したい場合にあっちを編集こっちも編集と二重管理するくらいなら、

hotel_price.rb
require 'hotel_pack_content'

の方がいいんだろうな〜。…ということで書きました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0