try ruby online here

In ruby, there many ways to define getter and setter methods.

simple way

class A
  @@attributes = {}

  def self.title
    @@attributes[:title]
  end

  def self.title= value
    @@attributes[:title] = value
  end
end

   

using method_missing

class B
  @@attributes = {}

  class << self
    def method_missing method_name, *params
      method_name = method_name.to_s

      if method_name =~ /=$/
        @@attributes[method_name.sub('=', '')] = params.first
      else
        @@attributes[method_name]
      end
    end
  end
end

   

define_method

in ruby, when we use enum, we can code like this

user_a.is_pending?
user_a.is_activated?

now let’s use define_method to implement this.

class User < ActiveRecord::Base
  STATUS = %w[pending activated suspended]

  STATUS.each do |status|
    define_method "is_#{status}" do
      self.status == status
    end
  end
end