Anybody know any slick techniques for automatically prototyping
classes so they can interact with each other in top-level code? I’ve
run through two methods, but I’m not real wild about either of them.
Say for example, classes represent some security label and I want to
allow things with one label to access those of another label. So,
these hypothetical classes all descent from Sec…
class Sec
class <<self
def allow©
(@allowed_classes||=[]) <<c
end
end
end
And I want to ultimately just indescriminately run stuff like this:
class Documents < Sec
allow Downloads
end
class Downloads < Sec
allow Documents
end
But this is a run-time error unless the classes are prototyped somehow.
Like:
class Downloads < Sec; end
class Documents < Sec
allow Downloads
end
class Downloads < Sec
allow Documents
end
As a framework, this would be so much nicer for the end-user if it
does that automatically, so she doesnt have to thing about declaration
order. So thats the problem. Possible solutions I’ve tried:
-
Grep-prototyping:
File.grep out all class defs and eval them before I actually require
the code. I don’t like this because it chokes on classes defined
inside of modules or other classes. Grep has no idea about the
structure of the ruby code. -
Delayed execution of the ‘allow’ statements.
I dump allow statements off into proc’s then after all the definitions
are loaded, I run them. This works great, but syntactically its
clunky.
class Documents < Sec
later do
allow Downloads
end
end
class Downloads < Sec
later do
allow Documents
end
end
with:
class Sec
class << self
def later(&code)
(@code_for_later||=[]) << code
end
end
And I go back and exec all the @code_for_later blocks when all the
files are require’d. So, if any of you have questions about this code
or have any ideas for a prettier way to do it, I’d love to hear it.