attr_read, attr_writer, etc.

F

Frank Meyer

Hello,
are these keywords or are they methods which create get/set methods for
the given attribute?

I suppose it's a mix of both, because I tried to write my own
attr_accessor but I couldn't call it in the class definition, only on
an existing object.




Turing.
 
S

Stefano Crocco

Alle luned=C3=AC 13 agosto 2007, Frank Meyer ha scritto:
Hello,
are these keywords or are they methods which create get/set methods for
the given attribute?

I suppose it's a mix of both, because I tried to write my own
attr_accessor but I couldn't call it in the class definition, only on
an existing object.




Turing.

They're instance method of the Module class. You can write them, if you wan=
t:

class Module
=20
def my_attr_reader *args
args.each do |a|
define_method(a) do
puts 'this method was generated by my_attr_reader';
instance_variable_get("@#{a}")
end
end
end

end

class C
my_attr_reader :x

def initialize x
@x =3D x
end
end

res =3D C.new(2).x
=3D> this method was generated by my_attr_reader
puts res
=3D> 2

Defining my_attr_reader in class Module will make it availlable in all clas=
ses=20
and modules. You can define it in class Class to make it availlable only in=
=20
classes, or you can define them in a single class. In this case, however, i=
t=20
should be defined as a class method, not as an instance method:

class MyClass
def self.my_attr_reader
...

I hope this helps

Stefano
 
F

Frank Meyer

Thanks for your explanation, but how would you write a attr_writer
method?
I don't know how I can pass a parameter list to define_method.



Turing.
 
D

dblack

Hi --

Thanks for your explanation, but how would you write a attr_writer
method?
I don't know how I can pass a parameter list to define_method.

Give the block a parameter:

def my_attr_writer(*names)
names.each do |name|
define_method("#{name}=") {|x| instance_variable_set("@#{name}", x) }
end
end


David

--
* Books:
RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
& consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top