Accessing one class from another class

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:



Alice
WonderLand

<Course difficulty=">
Math III
B+

dt:Tuition
dt:CurrencyUSD</dt:Currency>
dt:Amount500</dt:Amount>
dt:Period3 months</dt:Period>
</dt:Tuition>


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

???

Thank you

Also to clarify xml tag like can be repeated in my xml file,
so:

r.student.course
could return an array of objects of class Course.

To clarify Futhre I’m doing somethign like this right now:

class Base

attr_accessor :name, :value

def initialize
@name
@value
end
end

class Student
attr_accessor :person, :tuition

def initialize
@person = Person.new
@tuition = Tuition.new
end

end

… define Tuition & Person class. I’m just looking for a better way to
do it.

Also how would I properly define :course within Student, considering
that I might have a single Course or multiple - depending on the record.

Thank you

Also to clarify xml tag like can be repeated in my xml file,
so:

r.student.course
could return an array of objects of class Course.

Hi Nick,

There are some good libraries to accomplish this. You may want to have a
look at one of these (ordered by my own preferences):

xml-object:
http://github.com/jordi/xml-object/tree/master

happy-mapper:
http://happymapper.rubyforge.org/

xml-mapping:
http://xml-mapping.rubyforge.org/

Hope it helps
Cheers

On 04.05.2009 23:39, Nick da G wrote:

500 class Student class Tution 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

Thank you Alex, but no go :frowning:

I looked into all of them - they all lack in some respect:
happy-mapper - can’t build xml & handle namespaces
xml-object can’t handle namespaces - and some other issue - can’t
remember
xml-mapping - same thing
roxml - same problem.

So the solution is to just do it myself. However that wasn’t my question

  • it was more a of generic ruby class question.