accessor work in Ruby on Rails

Possible Duplicate:
What is attr_accessor in Ruby?

Here's the sample code:

class User
  attr_accessor :name, :email

  def initialize(attributes = {})
    @name = attributes[:name]
    @email = attributes[:email] 
  end 

....

end

When I do

example = User.new

it creates an empty user and I can assign its name and email by

example.name = "something"
example.email = "something" 

My question is, why this thing works? How does the computer know that example.name means the @name variable in the class? I'm assuming name and :name are different, and here in the code we have not explicitly told the computer that example.name is equivalent to :name symbol.


What attr_accessor does is it creates a couple of methods, a getter and a setter. It uses a symbol you pass to construct names of methods and instance variable. Look, this code:

class User
  attr_accessor :name
end

is equivalent to this code

class User
  def name
    @name
  end

  def name=(val)
    @name = val
  end
end

attr_accessor :field is the same as calling attr_reader :field and attr_writer :field . Those in turn are roughly the equal to:

def field
  @field
end

def field=(value)
  @field = value
end

Welcome to the magic of meta-programming. ;)

链接地址: http://www.djcxy.com/p/25772.html

上一篇: 读者在Ruby模块calss?

下一篇: 访问者在Ruby on Rails中工作