module Flows::Util::InheritableSingletonVars::DupStrategy

Strategy which uses `#dup` to copy variables to a child class.

Can be applied several times to the same class.

Can be applied in the middle of inheritance chain.

When your value is a custom class you may need to adjust `#dup` behaviour. It can be done using `initialize_dup` method. Unfortunately it's not documented well in the standard library. So, [this will help you](blog.appsignal.com/2019/02/26/diving-into-dup-and-clone.html).

@note If you change variables in a parent class after a child being defined

it will have no effect on a child. Remember this when working in environments
with tricky or experimental autoload mechanism.

@see InheritableSingletonVars the parent module's documentation describes the problem this module solves.

@since 0.4.0

Constants

VAR_LIST_VAR_NAME

Public Class Methods

make_module(vars_with_default = {}) click to toggle source

Generates a module which applies behaviour and defaults for singleton variables.

@example

class MyClass
  SingletonVarsSetup = Flows::Util::InheritableSingletonVars::DupStrategy.make_module(
    :@my_list => []
  )

  include SingletonVarsSetup
end

@note Variable names should look like `:@var` or `'@var'`.

@param vars_with_default [Hash<Symbol, String => Object>] keys are variable names,

values are default values.
# File lib/flows/util/inheritable_singleton_vars/dup_strategy.rb, line 81
def make_module(vars_with_default = {})
  Module.new.tap do |mod|
    mod.instance_variable_set(VAR_LIST_VAR_NAME, vars_with_default.keys.map(&:to_sym))
    init_vars(mod, vars_with_default)
    mod.extend Injector
  end
end

Private Class Methods

init_vars(mod, vars_with_default) click to toggle source
# File lib/flows/util/inheritable_singleton_vars/dup_strategy.rb, line 91
def init_vars(mod, vars_with_default)
  vars_with_default.each do |name, value|
    mod.instance_variable_set(name, value)
  end
end