[Ruby on Rails] How to Implement Setters and Getters in ActiveRecord

Tadashi Shigeoka ·  Sun, May 6, 2012

I researched how to implement setters and getters in Ruby on Rails ActiveRecord, so here’s a memo.

Using define_method, you can write it as follows:

class MyModel < ActiveRecord::Base
  define_method("hoge"){
    read_attribute "hoge"
  }
  define_method("hoge="){ |hoge|
    write_attribute "hoge", hoge
  }
end

Or, you can also write it as follows:

class MyModel < ActiveRecord::Base
  define_method("hoge"){
    self["hoge"]
  }
  define_method("hoge="){ |hoge|
    self["hoge"] = hoge
  }
end

That’s all from the Gemba.

【Reference】

Notes When Implementing Setters and Getters in ActiveRecord (Using define_method) - Mediocre Engineer’s Work Memo

define_method (Module) - Ruby Reference