Module: Eco::Language::Klass::InheritableClassVars
- Includes:
- Naming
- Included in:
- HelpersBuilt
- Defined in:
- lib/eco/language/klass/inheritable_class_vars.rb
Instance Method Summary collapse
-
#inheritable_attrs(*attrs) ⇒ Object
Builds the attr_reader and attr_writer of
attrsand registers the associated instance variable as inheritable. -
#inheritable_class_vars(*vars) ⇒ Object
Keeps track on class instance variables that should be inherited by child classes.
-
#inherited(subclass) ⇒ Object
This callback method is called whenever a subclass of the current class is created.
Methods included from Naming
#instance_variable_name, #to_constant
Instance Method Details
#inheritable_attrs(*attrs) ⇒ Object
Builds the attr_reader and attr_writer of attrs and registers
the associated instance variable as inheritable.
19 20 21 22 23 24 25 26 27 |
# File 'lib/eco/language/klass/inheritable_class_vars.rb', line 19 def inheritable_attrs(*attrs) attrs.each do |attr| class_eval %( class << self; attr_accessor :#{attr} end ), __FILE__, __LINE__ - 2 end inheritable_class_vars(*attrs) end |
#inheritable_class_vars(*vars) ⇒ Object
Note:
- subclasses will inherit the value as is at that moment
- any change afterwards will be only on the specific class (in line with class instance variables)
- adapted from https://stackoverflow.com/a/10729812/4352306
Keeps track on class instance variables that should be inherited by child classes. TODO: this separates the logic of the method to the instance var. Think if would be possible to join them somehow.
12 13 14 15 |
# File 'lib/eco/language/klass/inheritable_class_vars.rb', line 12 def inheritable_class_vars(*vars) @inheritable_class_vars ||= [:inheritable_class_vars] @inheritable_class_vars += vars end |
#inherited(subclass) ⇒ Object
Note:
- values of the instance variables are copied as they are (no dups or clones)
- the above means: avoid methods that change the state of the mutable object on it
- mutating methods would reflect the changes on other classes as well
- therefore,
freezewill be called on the values that are inherited.
This callback method is called whenever a subclass of the current class is created.
35 36 37 38 39 40 41 42 43 |
# File 'lib/eco/language/klass/inheritable_class_vars.rb', line 35 def inherited(subclass) super inheritable_class_vars.each do |var| instance_var = instance_variable_name(var) value = instance_variable_get(instance_var) subclass.instance_variable_set(instance_var, value.freeze) end end |