How can I simulate class/method friendship in Ruby? -
i remember (barely) in c++ create friend classes or methods, capable of accessing private members. frankly, never found feature particularly useful.
now using ruby game development framework. i'm making simple node system (a node can contain other children nodes, , have parent node).
my node
class has #add_child(child)
. thing is, when a
node gets child b
node, need set b
's @parent
reference point a
. inside #add_child(child)
have call:
child.set_parent(self)
now b
's @parent
variable points a
. , works fine.
but, #set_parent(parent)
is meant used specific scenario. must called when #add_child(child)
called. if used #set_parent(parent)
out of context, node system may break.
now find class/method friendship thing useful. if make #set_parent(parent)
usable #add_child(child)
, system wouldn't break if random programmer decided call #set_parent(parent)
themselves.
from few searches doesn't seem ruby has feature explicitly.
does ruby offer class/method friendship features c++ does? if not, how else can work around described problem?
this should work:
class node def add_child(child) @children << child # or whatever child.instance_exec(self) { |parent| set_parent(parent) } end end
inside instance_exec
you're if inside other object, can invoke private methods, or directly set instance variables. child.instance_exec(self) { |parent| @parent = parent }
work well. child.send(:set_parent, self)
or child.instance_variable_set(:parent, self)
, think instance_exec
makes bit clearer you're doing. ymmv. :)
ruby nominally protects insides of classes, enough don't shoot in foot accident. introspection capabilities powerful enough can access anywhere if want to.
Comments
Post a Comment