C
Chris Eskow
------=_Part_18429_13903458.1128823698427
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
Hi, I'm semi-new to Ruby and I have a question.
I have a class, World, that basically looks like this:
class World
# Convenience method that takes one or more symbols and defines an
# accessor+mutator method for each one.
def self.att *atts
atts.each do |att|
class_eval %{
def #{att} val=3Dnil
val =3D=3D nil ? @#{att} : @#{att} =3D val
end
}
end
end
# Now I can define some attributes.
att :title, :author
# Other methods here...
end
...which allows me to do things like this:
world.title "My Title"
world.title #=3D> "My Title"
The att method creates an instance method that sets an attribute if
an argument is given, or returns it if no arguments are given. This
is nice and all, but now I want to use this att method with another
class. Since it's very short I could just copy and paste it, but I'd
rather use a module, Attributes, that I could include into any class:
class World
include Attributes
att :title, :author
end
class Thing
include Attributes
att :name, :desc
end
I'm having trouble getting it to work, however. I have a feeling I
have to use metaclasses or something, but I'm not quite sure how I'm
suppose to do that. Everything I tried resulted in "undefined method
`att'" errors. Any thoughts?
Chris
------=_Part_18429_13903458.1128823698427--
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
Hi, I'm semi-new to Ruby and I have a question.
I have a class, World, that basically looks like this:
class World
# Convenience method that takes one or more symbols and defines an
# accessor+mutator method for each one.
def self.att *atts
atts.each do |att|
class_eval %{
def #{att} val=3Dnil
val =3D=3D nil ? @#{att} : @#{att} =3D val
end
}
end
end
# Now I can define some attributes.
att :title, :author
# Other methods here...
end
...which allows me to do things like this:
world.title "My Title"
world.title #=3D> "My Title"
The att method creates an instance method that sets an attribute if
an argument is given, or returns it if no arguments are given. This
is nice and all, but now I want to use this att method with another
class. Since it's very short I could just copy and paste it, but I'd
rather use a module, Attributes, that I could include into any class:
class World
include Attributes
att :title, :author
end
class Thing
include Attributes
att :name, :desc
end
I'm having trouble getting it to work, however. I have a feeling I
have to use metaclasses or something, but I'm not quite sure how I'm
suppose to do that. Everything I tried resulted in "undefined method
`att'" errors. Any thoughts?
Chris
------=_Part_18429_13903458.1128823698427--