Module: Eco::Language::Klass::InheritableClassVars

Includes:
Naming
Included in:
HelpersBuilt
Defined in:
lib/eco/language/klass/inheritable_class_vars.rb

Instance Method Summary collapse

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.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/eco/language/klass/inheritable_class_vars.rb', line 20

def inheritable_attrs(*attrs)
  attrs.each do |attr|
    class_eval <<-DEF_CLSS_ATTR, __FILE__, __LINE__ + 1
      class << self            # class << self
        attr_accessor :#{attr} #   attr_accessor :coolio
      end                      # end
    DEF_CLSS_ATTR
  end

  inheritable_class_vars(*attrs)
end

#inheritable_class_vars(*vars) ⇒ Object

TODO:

this separates the logic of the method to the instance var. Think if would be possible to join them somehow.

Note:

Keeps track on class instance variables that should be inherited by child classes.



13
14
15
16
# File 'lib/eco/language/klass/inheritable_class_vars.rb', line 13

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, freeze will be called on the values that are inherited.

This callback method is called whenever a subclass of the current class is created.



38
39
40
41
42
43
44
45
46
# File 'lib/eco/language/klass/inheritable_class_vars.rb', line 38

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