Accessing ruby variables in nested objects -
i have gem working on. in executable parses config file , instantiates couple of objects. 1 of these objects instantiates number of "handler" objects. parsing config file array, config
, settings within not accessible in of other objects. needed in handlers. when try use them, variable not exist.
i understand variable scope issue. not sure need make these accessible throughout entire program (including sub/nested objects) , not initial executable. while each of objects in program within module, actions in executable not.
constants global, live in namespace in defined.
if define config
in main context, global @ root-level. if define in class or module, must refer full name outside of context.
for example:
class foo config = file.read(...) end config # => error, not defined foo::config # => defined
it's bad form reference constants name, run against grain of proper object-oriented design. such, if define constants, should used internally only, , exposed via methods sub-classes can redefine or patch required.
a better example:
class foo config = file.read(...) def self.config config end end foo.config # => configuration
this simple abstraction important because sub-class can re-define configuration:
class bar < foo def self.config # ... different implementation end end bar.config # => different result
even better avoid constants altogether , lazy-load things required:
class foo def self.config @config ||= file.read(...) end end foo.config # => configuration
constants best reserved things not change, separator = ':'
, it's not possible or practical reconfigure them without breaking lot of code.
where have that's read in external source, might vary based on configuration or preference, it's more convenient have method intermediates this.
Comments
Post a Comment