* MemoryRecord A small number of records Easy handling library ** Installation Install as a standalone gem #+BEGIN_SRC shell $ gem install memory_record #+END_SRC Or install within application using Gemfile #+BEGIN_SRC shell $ bundle add memory_record $ bundle install #+END_SRC ** Examples *** Basic usage #+BEGIN_SRC ruby class Language include MemoryRecord memory_record [ {key: :lisp, author: "John McCarthy" }, {key: :c, author: "Dennis Ritchie" }, {key: :ruby, author: "Yukihiro Matsumoto" }, ], attr_reader_auto: true def mr_author "Mr. #{author}" end end Language[:ruby].key # => :ruby Language[:ruby].code # => 2 Language[:ruby].author # => "Yukihiro Matsumoto" Language[:ruby].mr_author # => "Mr. Yukihiro Matsumoto" Language.keys # => [:lisp, :c, :ruby] Language.collect(&:author) # => ["John McCarthy", "Dennis Ritchie", "Yukihiro Matsumoto"] #+END_SRC *** How to decide =code= yourself? #+BEGIN_SRC ruby class Foo include MemoryRecord memory_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] #+END_SRC It is used only when refactoring legacy code, when compatibility is required. *** How to turn as an array? =Enumerable= extended, so that =each= method is available #+BEGIN_SRC ruby Foo.each { |e| ... } Foo.collect { |e| ... } #+END_SRC *** How do I submit a form to select in Rails? #+BEGIN_SRC ruby form.collection_select(:selection_code, Foo, :code, :name) #+END_SRC *** Is the reference in subscripts slow? Since it has a hash internally using the key value as a key, it can be acquired with O (1). #+BEGIN_SRC ruby Foo[1].name # => "A" Foo[:a].name # => "A" #+END_SRC *** Instances always react to =code= and =key= #+BEGIN_SRC ruby object = Foo.first object.key # => :a object.code # => 1 #+END_SRC *** =attr_reader= option The attribute value can be referenced with =@attributes[:xxx]=, but it is troublesome to refer frequently, so it is methodized with =attr_reader: xxx=. *** =attr_reader_auto= option Automatically all attributes =attr_reader= *** What if I do not want you to feel free to access the attributes of a record? =attr_reader= with no method definition and reference =object.attributes[:xxx]= *** How do I add a method to an instance? For that, I am creating a new class so I need to define it normally *** =name= method is special? If =name= is not defined, it defines a =name= method that returns a translation of =key= *** =to_s= method is defined? = Alias of =name=, =to_s= is defined. *** If there is no key, use fetch to get an error #+BEGIN_SRC ruby Foo.fetch(:xxx) # => #+END_SRC The following are all the same #+BEGIN_SRC ruby Foo[:xxx] || :default # => :default Foo.fetch(:xxx, :default} # => :default Foo.fetch(:xxx) { :default } # => :default #+END_SRC *** Use fetch_if to ignore if the key is nil #+BEGIN_SRC ruby Foo.fetch_if(nil) # => nil Foo.fetch_if(:a) # => # Foo.fetch_if(:xxx) # => #+END_SRC