Ruby can be scary simple sometimes. No looping in sight!
class Weekend < Struct.new(:start_date, :end_date, :title, :description, :location)
# params: Hash with symbols as keys
def initialize(params)
# arg splatting to the rescue
super( * params.values_at( * self.class.members ) )
end
end
Note that you don't even need to use inheritance - a new Struct
can be customized during creation:
Weekend = Struct.new(:start_date, :end_date, :title, :description, :location) do
def initialize(params)
# same as above
end
end
Test:
weekend = Weekend.new(
:start_date => 'start_date value',
:end_date => 'end_date value',
:title => 'title value',
:description => 'description value',
:location => 'location value'
)
p [:start_date , weekend.start_date ]
p [:end_date , weekend.end_date ]
p [:title , weekend.title ]
p [:description, weekend.description ]
p [:location , weekend.location ]
Note that this doesn't actually set instance variables. You class will have opaque getters and setters. If you'd rather not expose them, you can wrap another class around it. Here's an example:
# this gives you more control over readers/writers
require 'forwardable'
class Weekend
MyStruct = ::Struct.new(:start_date, :end_date, :title, :description, :location)
extend Forwardable
# only set up readers
def_delegators :@struct, *MyStruct.members
# params: Hash with symbols as keys
def initialize(params)
# arg splatting to the rescue
@struct = MyStruct.new( * params.values_at( * MyStruct.members ) )
end
end