Brajesh KS wrote in post #1160408:
every object of my model will inherit of class Stuff
class Stuff
…
end
a=Stuff.new(…)
Each object will have a list of associations ( “links” ),
each association will have a name. this dictionary of associations will
be build on constructor :
class Stuff
def intialize(id)
@links= Hash.new
@id=id
end
…
end
I suppose that each entity will have a unique identity( ‘id’ ) ,
so i declare a accessor for reading access of the id of one entity,
and give this id at construction
class Stuff
attr_reader :id
def intialize(id)
…
self.id=id
end
…
end
a= Stuff.new(900984324)
a.id
-> 900984324
Then each each association will contain a list of object which is
‘linked’ to my entity. I choose to use a Hash for this list. so at
construction, each association must point to a empty hash when the
association will
be created:
class Stuff
attr_reader :id
def intialize(id)
@links= Hash.new {|h,role| h[role]={} }
self.id=id
end
…
end
Now we can add a method for associate a object to my stuff.
I give the name of the association, and the object to be linked :
class Stuff
…
def add(role,object)
@links[role][object.id]=object
end
end
a=Stuff.new(3234324)
b=Stuff.new(5243334)
a.add(:parent,b)
So in object a, @links[:parent] while contain a reference of b object
with his id : @links[:parent]={ 5243334 => b }
Then you can append some methods in Stuff for doing some
algorithm.
Suppose your model represent a family structure,
let create a sub-class of Stuff, with some algorithm specific to
family model :
class Person < Stuff
def children() @links[:child].values end
def parent() @links[:parent].values end
def check_family()
self.parent.each { |par|
raise “Incoherence” unless par.children.keys?(self.id)
}
self.children.values.each { |child| child.check_family }
end
end
a=Person.new(“John”)
b=Person.new(“Mary”)
b.add(:parent,a)
a.add(:child,b)
a.check_family
NOTA : by using Hash for association, the check is more efficient
( Hash member search) than if i had use a Array ( link.find ),
and i can have the array of object with link.values()
… pointer …
in Ruby, a variable are a reference (handle) of an object.
you can’t have direct access of data structure if the object.
So a variable is always a ‘pointer’ to an object :
- Stuff is a const variable which reference a class object
- in c=22, c reference a Integer variable which is immutable
(22 is always 22, it can’t be 23 !)
so c=22
c=c+1 ; c referene a new Integer instance, which value is
the value of 22 object and the value of 1 object.
22 is not refeeced, it will be garbage collected…
Sorry for my english 