Ruby/Reflection/class eval

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

class_eval is ideal for adding methods to a class dynamically:

class Person
end
def add_accessor_to_person(accessor_name)
  Person.class_eval %Q{
    attr_accessor :#{accessor_name}
  }
end
person = Person.new
add_accessor_to_person :name
add_accessor_to_person :gender
person.name = "Peter Cooper"
person.gender = "male"
puts "#{person.name} is #{person.gender}"



Creating Your Own Version of attr_accessor

class Class
  def add_accessor(accessor_name)
    self.class_eval %Q{
      def #{accessor_name}
        @#{accessor_name}
      end
      def #{accessor_name}=(value)
        @#{accessor_name} = value
      end
    }
  end
end