Class: Attrify::VariantRegistry

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/attrify/variant_registry.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#compute_attributes, #deep_merge_hashes, #deep_merge_hashes!, #execute_operation

Constructor Details

#initialize(base: {}, variants: {}, defaults: {}, compounds: []) ⇒ VariantRegistry

Returns a new instance of VariantRegistry.



17
18
19
20
21
22
23
# File 'lib/attrify/variant_registry.rb', line 17

def initialize(base: {}, variants: {}, defaults: {}, compounds: [])
  self.base = base
  self.variants = variants
  self.defaults = defaults
  self.compounds = compounds
  @cache = {}
end

Instance Attribute Details

#baseObject

Returns the value of attribute base.



15
16
17
# File 'lib/attrify/variant_registry.rb', line 15

def base
  @base
end

#compoundsObject

Returns the value of attribute compounds.



15
16
17
# File 'lib/attrify/variant_registry.rb', line 15

def compounds
  @compounds
end

#defaultsObject

Returns the value of attribute defaults.



15
16
17
# File 'lib/attrify/variant_registry.rb', line 15

def defaults
  @defaults
end

#variantsObject

Returns the value of attribute variants.



15
16
17
# File 'lib/attrify/variant_registry.rb', line 15

def variants
  @variants
end

Instance Method Details

#fetch(**args) ⇒ Object

Fetch the correct variant, with caching



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/attrify/variant_registry.rb', line 42

def fetch(**args)
  # Split args into variant and operations
  variant_keys = variants.keys

  variant_args = {}
  operation_args = {}

  args.each do |key, value|
    if variant_keys.include?(key)
      variant_args[key] = value #Array(value).join("_").to_sym
    else
      operation_args[key] = value
    end
  end

  operations = Parser.parse_slots(operation_args)

  cache_key = generate_cache_key(variant_args)

  # Return the cached result if it exists
  unless @cache.key?(cache_key)
    @cache[cache_key] = compute_variant(variant: variant_args)
  end

  @cache[cache_key].adjust(operations)
end

#initialize_copy(orig) ⇒ Object



69
70
71
72
73
74
75
76
# File 'lib/attrify/variant_registry.rb', line 69

def initialize_copy(orig)
  super
  @base = @base.dup
  @variants = @variants.dup
  @defaults = @defaults.dup
  @compounds = @compounds.dup
  @cache = {}
end