Class: ClassVariants::Instance
- Inherits:
-
Object
- Object
- ClassVariants::Instance
- Defined in:
- lib/class_variants/instance.rb
Instance Method Summary collapse
- #dup ⇒ Object
-
#initialize ⇒ Instance
constructor
A new instance of Instance.
- #merge(**options, &block) ⇒ Object
- #render(slot = :default, **overrides) ⇒ Object
Constructor Details
#initialize ⇒ Instance
Returns a new instance of Instance.
5 6 7 8 9 10 11 12 |
# File 'lib/class_variants/instance.rb', line 5 def initialize(...) @bases = [] @variants = [] @defaults = {} @slots = nil merge(...) end |
Instance Method Details
#dup ⇒ Object
14 15 16 17 18 19 20 |
# File 'lib/class_variants/instance.rb', line 14 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
22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/class_variants/instance.rb', line 22 def merge(**, &block) raise ArgumentError, "Use of hash config and code block is not supported" if !.empty? && block (base = .fetch(:base, nil)) && @bases << {class: base, slot: :default} @variants += [ (.fetch(:variants, {})), (.fetch(:compound_variants, [])) ].inject(:+) @defaults.merge!(.fetch(:defaults, {})) instance_eval(&block) if block self end |
#render(slot = :default, **overrides) ⇒ Object
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 63 64 65 66 67 68 69 70 71 |
# File 'lib/class_variants/instance.rb', line 37 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 match = false candidate.each_key do |key| next if key == :class || key == :slot match = criteria[key] == candidate[key] break unless match end result << candidate[:class] if match 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 |