LoginSignup
4
2

More than 5 years have passed since last update.

attr_accessorをメタプログラミングで実装

Last updated at Posted at 2013-03-20

概要

define_methodを用い、p self でスコープをたしかめながら実装します。
String.x = 10のように、クラスにもプロパティを持たせられることを確かめます。これはクラスもClassクラスのインスタンスであることによります。

実装

attr_a.rb
class Object
  def self.attr_a name
    p "out define_method :" + self.to_s
    define_method name do
      instance_variable_get "@#{name}"
    end
    define_method name.to_s + "=" do |x|
      p "in define_method :" + self.to_s
      instance_variable_set("@#{name}", x)
    end
  end
end

なおClassクラスはModule, ModuleはObjectを継承しています。

インスタンスでテスト

attr_a_instance_method.rb
class Foo
  attr_a :x # =>  "out define_method :Foo"
end
f = Foo.new 
f.x = "hoge" # =>  "in define_method :#<Foo:0x007fd722108898>"
p f.x # => "hoge"

クラスでテスト

特異クラスのコンテキストでメソッド定義をすると、クラスメソッドが定義されることを確かめます。

attr_a_class_method.rb
class Foo
  class << self
    attr_a :y # => "out define_method :#<Class:Foo>(特異クラス)"
  end
end
Foo.y = "hoge" # =>     "in define_method :Foo"
p Foo.y # => "hoge"
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2