One file or three files, … whatever number of files is not the point.
(Ie, the separation of code into multiple files has it’s own reasons, foremost is maintainability and organization.)
The key here is namespacing using modules, and having one shared module that holds the shared variables.
The sharing is activated using the Module
class’ include()
method.
So, for a single file example, using your module names …
# "Medeek_WallPlugin/WallPlugin_SharedVars.rb"
module Medeek_Engineering_Inc_Extensions
module MedeekWallPlugin
module SharedVars
@@some_var ||= ["string1","string2","string3"]
@@some_switch = false unless defined?(@@some_switch)
end
module Settings
include(SharedVars)
# THIS module can see other constants defined
# at the same scope it is defined
end
module Wall
include(SharedVars)
if !@@some_switch
# Create a menu item perhaps ?
# Actually change the var in the shared module:
@@some_switch = true # all mixee's see the change !
end
class MedeekMethods
# The grandparent namespace to this one:
GRANDPARENT = Module::nesting[2]
include(GRANDPARENT::SharedVars)
def self.get(index)
@@some_var[index]
end
end
end
end
end
Then at the the console after pasting in the above …
Medeek_Engineering_Inc_Extensions::MedeekWallPlugin::Wall::MedeekMethods.get(2)
#=> string3
Note, in order to use the Module::nesting
class method, you must define the modules in the normal nested manner (as shown above.) It will not work (in the file in which it is called,) if you use the shortcut manner as shown in your first post.
This only means that if you prefer the shortcut format, then you’d have to use a fully qualified module reference for the include()
call … ie …
include(Medeek_Engineering_Inc_Extensions::MedeekWallPlugin::SharedVars)
Once the SharedVars
module is defined within it’s parent module, you an then also include
the submodule in it’s parent, so that the parent module can share the variables as well as any other class or module. Ie …
# "Medeek_WallPlugin/WallPlugin_SharedVars.rb"
module Medeek_Engineering_Inc_Extensions
module MedeekWallPlugin
module SharedVars
@@some_var ||= ["string1","string2","string3"]
@@some_switch = false unless defined?(@@some_switch)
end
include(SharedVars)
# ... the rest as shown above ...
end
end
Then at the console …
Medeek_Engineering_Inc_Extensions::MedeekWallPlugin.class_variable_get(:@@some_var)[0]
#=> string1
If this seems weird, note that in the Ruby core it is common to have shared constants in submodules, that are mixed into their parent module or class, so that other custom namespaces can also include()
them.
An example is the class File
which has a mixin submodule File::Constants
that it itself includes. This allows coders to also include these constants into their own namespaces for use in making method calls to File
class objects.