Skip to content

Instantly share code, notes, and snippets.

@sirupsen
Created June 12, 2010 13:12
Show Gist options
  • Save sirupsen/435728 to your computer and use it in GitHub Desktop.
Save sirupsen/435728 to your computer and use it in GitHub Desktop.
Explanation of attr_* in Ruby.
# Explanation of attr_* to Noxn
# Let's start with an example class using attr_acessor:
class Klass
attr_acessor :variable
def initialize(content)
@variable = content
end
end
klass = Klass.new("Variable's content")
# So now, Klass̈́' instance variable called "variable"'s (@variable)
# value is the string "Variable's content"
# attr_acessor defined two methods (shown later),
# it allows us to "access" the variable in two ways,
# one being to change the value:
klass.variable = "New content"
# Other one being retrieving the value:
klass.variable
#=> "New content"
# As I said before, attr_acessor simply is a shortcut for two methods:
class Klass
def initialize(content)
@variable = content
end
def variable=(content)
@variable = content
end
def variable
@variable
end
end
# But because these are so common tasks, the shortcut is provided.
# There is also:
# attr_reader (read only)
#
# And
# attr_writer (write only)
# So attr_acessor is just a method, it could be written like this:
def attr_acessor(*instance_variables)
instance_variables.each do |instance_variable|
define_method(instance_variable) do
self.instance_variable_get(instance_variable)
end
define_method(instance_variable + "=") do |new_value|
self.instance_variable_set(instance_variable, new_value)
end
end
end
# And with that method, it would be pretty easy to write attr_writer and
# attr_reader, of course :) (And attr_acessor should actually just call these
# methods, but we do it like this for the sake of example)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment