StaticRecord はもうメンテナンスしていません。かわりに memory_record gem を使ってみてください。
class Direction
include StaticRecord
static_record [
{key: :left, name: "左", vector: [-1, 0]},
{key: :right, name: "右", vector: [ 1, 0]},
], attr_reader_auto: true
def long_name
"#{name}方向"
end
end
Direction.collect(&:name) # => ["左", "右"]
Direction.keys # => [:left, :right]
Direction[:right].key # => :right
Direction[:right].code # => 1
Direction[:right].vector # => [1, 0]
Direction[:right].long_name # => "右方向"
Direction[1].key # => :right
Direction[:up] # => nil
Direction.fetch(:up) rescue $! # => #<KeyError: Direction.fetch(:up) では何にもマッチしません。class Foo
include StaticRecord
static_record [
{code: 1, key: :a, name: "A"},
{code: 2, key: :b, name: "B"},
{code: 3, key: :c, name: "C"},
], attr_reader: :name
end
Foo.collect(&:code) # => [1, 2, 3]レガシーなコードをリファクタリングするときの、互換性が必要なときにぐらいにしか使わない。
Enumerable が入っているので each 系メソッドが利用可
Foo.each {|v| ... }
Foo.collect {|v| ... }form.collection_select(:selection_code, Foo, :code, :name)内部で key の値をキーとしたハッシュを持っているため O(1) で取得できる。
Foo[1].name # => "A"
Foo[:a].name # => "A"object = Foo.first
object.key # => :a
object.code # => 1属性は @attributes[:xxx] で参照できるが、頻繁に参照するときには面倒なので :attr_reader => :xxx でメソッド化している。
属性をすべて attr_reader する
attr_reader でメソッド定義せず object.attributes[:xxx] で参照する。
そのために新しくクラスを作っているので普通に定義すればいい。
name が定義されてなかったら key の翻訳を返す name メソッドを定義している。
name の別名で to_s を定義している。
Foo.fetch(:xxx) # => <KeyError: ...>以下は全部同じ
Foo[:xxx] || :default # => :default
Foo.fetch(:xxx, :default} # => :default
Foo.fetch(:xxx) { :default } # => :defaultFoo.fetch_if(nil) # => nil
Foo.fetch_if(:a) # => #<Foo:... @attributes={...}>
Foo.fetch_if(:xxx) # => <KeyError: ...>