I’ve been writing a couple of very struct-like classes, and got annoyed
at having to write:
class MyStructLikeThing
attr_accessor :one, :two, :three, :four, :five
def initialize (one, two, three, four, five)
@one, @two, @three, @four, @five = one, two, three, four, five
end
end
And how ugly that looked in the code, so I decided to try my hand at
whipping up an attr_constructor statement.
class Module
private
def attr_constructor(*args)
self.class_eval %Q{
def initialize(#{args.join(’, ')})
#{args.collect{ |setting|
“instance_variable_set(”@#{setting}", #{setting})" }}
end
}
end
end
class MyStructLikeThing
attr_accessor :one, :two, :three, :four, :five
attr_constructor :one, :two, :three, :four, :five
end
It strikes me as a little cludgy. Is there a better way of doing this?
Is there a way to get the args variable so that it can be read from
within a module_eval block?
(Note also, that I know about the Struct module, this is just a
simplified example)
Daniel Sheppard
http://jroller.net/page/soxbox
···
#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################