Class: Apropos::Variant

Inherits:
Object
  • Object
show all
Defined in:
lib/apropos/variant.rb

Overview

A Variant represents a single image file that should be displayed instead of the base image in one or more conditions. These conditions are parsed from the codes in the provided code fragment. If none of the available parsers can understand the Variant’s codes, then the Variant is not considered valid.

A valid Variant can generate a CSS rule from its matching conditions, and can be compared to other Variants based on the aggregate sort values of its matching conditions.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code_fragment, path) ⇒ Variant

Returns a new instance of Variant.



14
15
16
17
18
# File 'lib/apropos/variant.rb', line 14

def initialize(code_fragment, path)
  @code_fragment = code_fragment
  @path = path
  @_invalid_codes = []
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



12
13
14
# File 'lib/apropos/variant.rb', line 12

def path
  @path
end

Instance Method Details

#<=>(other) ⇒ Object



63
64
65
# File 'lib/apropos/variant.rb', line 63

def <=>(other)
  aggregate_sort_value <=> other.aggregate_sort_value
end

#aggregate_sort_valueObject



57
58
59
60
61
# File 'lib/apropos/variant.rb', line 57

def aggregate_sort_value
  conditions.inject(0) do |total, query_or_selector|
    total + query_or_selector.sort_value
  end
end

#codesObject



20
21
22
# File 'lib/apropos/variant.rb', line 20

def codes
  @_codes ||= @code_fragment.split(SEPARATOR)
end

#conditionsObject



24
25
26
# File 'lib/apropos/variant.rb', line 24

def conditions
  parse_codes && @_conditions
end

#conditions_by_typeObject



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/apropos/variant.rb', line 32

def conditions_by_type
  @_conditions_by_type ||= {}.tap do |combination|
    conditions.each do |condition|
      combination[condition.type] = if combination[condition.type]
        combination[condition.type].combine(condition)
      else
        condition
      end
    end
  end
end

#invalid_codesObject



28
29
30
# File 'lib/apropos/variant.rb', line 28

def invalid_codes
  parse_codes && @_invalid_codes
end

#ruleObject



48
49
50
51
52
53
54
55
# File 'lib/apropos/variant.rb', line 48

def rule
  sorted_selector_types = conditions_by_type.keys.sort
  condition_css = sorted_selector_types.map do |rule_type|
    conditions_by_type[rule_type].to_css
  end
  key = sorted_selector_types.join('+')
  [key] + condition_css + [path]
end

#valid?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/apropos/variant.rb', line 44

def valid?
  !conditions.empty? && @_invalid_codes.empty?
end