Class: ClassVariants::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/class_variants/instance.rb

Instance Method Summary collapse

Constructor Details

#initializeInstance



3
4
5
6
7
8
9
# File 'lib/class_variants/instance.rb', line 3

def initialize(...)
  @bases = []
  @variants = []
  @defaults = {}

  merge(...)
end

Instance Method Details

#dupObject



11
12
13
14
15
16
17
# File 'lib/class_variants/instance.rb', line 11

def dup
  self.class.new.tap do |copy|
    copy.instance_variable_set(:@bases, @bases.dup)
    copy.instance_variable_set(:@variants, @variants.dup)
    copy.instance_variable_set(:@defaults, @defaults.dup)
  end
end

#merge(**options, &block) ⇒ Object

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/class_variants/instance.rb', line 19

def merge(**options, &block)
  raise ArgumentError, "Use of hash config and code block is not supported" if !options.empty? && block_given?

  (base = options.fetch(:base, nil)) && @bases << {class: base, slot: :default}
  @variants += [
    expand_variants(options.fetch(:variants, {})),
    expand_compound_variants(options.fetch(:compound_variants, []))
  ].inject(:+)
  @defaults.merge!(options.fetch(:defaults, {}))

  instance_eval(&block) if block_given?

  self
end

#render(slot = :default, **overrides) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/class_variants/instance.rb', line 34

def render(slot = :default, **overrides)
  classes = overrides.delete(:class)
  result = []

  # Start with our default classes
  @bases.each do |base|
    result << base[:class] if base[:slot] == slot
  end

  # Then merge the passed in overrides on top of the defaults
  criteria = @defaults.merge(overrides)

  @variants.each do |candidate|
    next unless candidate[:slot] == slot

    if (candidate.keys - [:class, :slot]).all? { |key| criteria[key] == candidate[key] }
      result << candidate[:class]
    end
  end

  # add the passed in classes to the result
  result << classes

  # Compact out any nil values we may have dug up
  result.compact!

  # Return the final token list
  with_classess_processor(result.join(" "))
end