title: “ [Gem] static_model yamlファイルを読み込んでActive Recordのように扱う [Rails]”
category: Rails

🐯 tags: [Rails, Ruby, Gem]

Where?yamlで定義したデータを読み込んでActive Recordのクラスのようにデータを扱うことができるGem「static_model」の紹介です。

static_model


🐰 Gemのインストール

いつ戻おりGemfileに以下を追加して、bundle installを実行してください。

group :development do
# Static Model(yamlでActiveRecordっぽいクラスを作る)
gem "static_model"
end

🏈 static_modelの作成手順

まずは、static_modelの元となるyamlファイルを作成。

- id: 1
title: The Ruby Way
author: Hal Fulton
- id: 2
title: Programming Ruby
author: Dave Thomas
publisher: Pragmatic Programmers

続いて、static_modelを作成します。このstatic_model内で先ほど作成したyamlファイルの場所を指定します。

class Book < StaticModel::Base
set_data_file "#{Rails.root}/path/to/my/file/withanothername.yml"
end

👽 static_modelの利用例

static_modelの具体的な利用例です。Active Recordみたいなことが簡単にできちゃいます。

>> Book.find(1)
=> #"Hal Fulton", :title=>"The Ruby Way"}, id1

>> Book.first
=> #"Hal Fulton", :title=>"The Ruby Way"}, id1

>> Book.find(:all) (or Book.all)
=> [#"Hal Fulton", :title=>"The Ruby Way"}, id1,
#"Dave Thomas", :title=>"Programming Ruby", :publisher=>"Pragmatic Programmers"}, id2]

>> Book.find_by_title('The Ruby Way')
=> #"Hal Fulton", :title=>"The Ruby Way"}, id1

>> b = Book.first
>> b.title
=> "The Ruby Way"
>> b.id
=> 1

Active Recordのクラスとリレーション(:belong_to, :has_one, :has_many)をもつこともできるようです。

class Reader < ActiveRecord::Base
belongs_to :book, :foreign_key => 'book_id'
end

>> r = Reader.create(:name => 'Aaron Quint', :book_id => 1)
=> #
>> r.book
=> #"Hal Fulton", :title=>"The Ruby Way"}, id1

もし、興味があればぜひチャレンジしてみてください!

static_model

🖥 VULTRおすすめ

VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!

📚 おすすめの書籍