R
Ruby Nooby
Hi,
How do I create a ruby class that has mass assignment functionality? I
want it to work in a similar way to the way in which ActiveRecord does,
ie.
MyClass.new
=> #<MyClass:>
MyClass.new
name => "Cool class")
=> #<MyClass: @name="s">
MyClass.new
name => "Cool class",
ther_attribute => "some other")
=> #<MyClass: @name="s", @other_attribute="some other">
I have found the following code snippit which works for the mass
assignment part but doesn't work if I initialize the class without any
arguments:
class MyClass
attr_accessor :name
attr_accessor
ther_attribute
def initialize(args)
args.keys.each { |name| instance_variable_set "@" + name.to_s,
args[name] }
end
end
MyClass.new
ArgumentError: wrong number of arguments (0 for 1)
from (irb):19:in `initialize'
from (irb):19:in `new'
from (irb):19
What is the best way of achieving mass assignment whilst still allowing
to initialize without parameters?
How do I create a ruby class that has mass assignment functionality? I
want it to work in a similar way to the way in which ActiveRecord does,
ie.
MyClass.new
=> #<MyClass:>
MyClass.new
=> #<MyClass: @name="s">
MyClass.new
=> #<MyClass: @name="s", @other_attribute="some other">
I have found the following code snippit which works for the mass
assignment part but doesn't work if I initialize the class without any
arguments:
class MyClass
attr_accessor :name
attr_accessor
def initialize(args)
args.keys.each { |name| instance_variable_set "@" + name.to_s,
args[name] }
end
end
MyClass.new
ArgumentError: wrong number of arguments (0 for 1)
from (irb):19:in `initialize'
from (irb):19:in `new'
from (irb):19
What is the best way of achieving mass assignment whilst still allowing
to initialize without parameters?