Robert Klemme
5/5/2009 6:25:00 AM
On 04.05.2009 23:39, Nick da G wrote:
> Hello, All.
>
> I'm trying to consuming an xml file and map it to a Ruby object that
> would describe that xml file.
>
> What would be the best way to implement the following scenario.
>
> Let's say I have several classes: Student, Course, Person, Tuition
> Xml for this would look like this:
> <Record>
> <Student status="good">
> <Person>
> <Name>Alice</Name>
> <BirthPlace>WonderLand</BirthPlace>
> </Person>
> <Course difficulty=">
> <CourseName>Math III</CourseName>
> <Grade>B+</Grade>
> </Course>
> <dt:Tuition>
> <dt:Currency>USD</dt:Currency>
> <dt:Amount>500</dt:Amount>
> <dt:Period>3 months</dt:Period>
> </dt:Tuition>
> </Student>
> </Record>
> So basically I can parse the xml file using rexml and access all of my
> xml tags and stuff.
>
> Here is the Object I want to map it to:
>
>
> class Student
> @status
> @person - access Person
> end
>
> class Person
> end
>
> class Course
> end
>
> class Tution
> end
>
>
>
> So the question is how do I access from class Student - class Person? So
> that when I down the line later when I parse the file and do:
>
> r = Record.new
>
> I want to be able to do things like:
> r.student.person.name
You can define attributes via attr_accessor, e.g.
class Student
attr_accessor :person
end
class Person
attr_accessor :name
end
st = Student.new
pe = Person.new
pe.name = "Nick"
st.person = pe
etc.
As a shortcut you can as well use Struct:
Student = Struct.new :person
Person = Struct.new :name
Kind regards
robert