Class: Styles::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/styles/rule.rb

Constant Summary collapse

SPECIAL_SELECTORS =

Special Selectors are Symbols that describe common special cases.

{
  blank: /^\s*$/,
  empty: /^$/,
  any: /^/,
  all: /^/ # Synonym of :any
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(selector, properties_hash) ⇒ Rule

Returns a new instance of Rule.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/styles/rule.rb', line 16

def initialize(selector, properties_hash)
  @selector = selector
  @unrecognized_properties = {}

  @properties = properties_hash.keys.map do |name|
    property_class = ::Styles::Properties.find_class_by_property_name(name)
    if property_class
      property_class.new(selector, name, properties_hash[name])
    else
      unrecognized_properties[name] = properties_hash[name]
      nil
    end
  end.compact
end

Instance Attribute Details

#propertiesObject

Returns the value of attribute properties.



14
15
16
# File 'lib/styles/rule.rb', line 14

def properties
  @properties
end

#selectorObject

Returns the value of attribute selector.



14
15
16
# File 'lib/styles/rule.rb', line 14

def selector
  @selector
end

#unrecognized_propertiesObject

Returns the value of attribute unrecognized_properties.



14
15
16
# File 'lib/styles/rule.rb', line 14

def unrecognized_properties
  @unrecognized_properties
end

Instance Method Details

#applicable?(line) ⇒ Boolean

Indicates whether this Rule is applicable to the given line, according to the selector. You could say the selector ‘matches’ the line for an applicable rule.

A String selector matches if it appears anywhere in the line. A Regexp selector matches if it matches the line.

ANSI color codes are ignored when matching to avoid false positives or negatives.

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/styles/rule.rb', line 38

def applicable?(line)
  uncolored_line = color.uncolor(line.chomp)
  case selector
    when String
      uncolored_line.include?(selector)
    when Regexp
      selector.match(uncolored_line)
    when Symbol
      SPECIAL_SELECTORS[selector].match(uncolored_line)
    else
      false
  end
end

#apply(line) ⇒ Object

Apply the rule to the given line

If the line is nil then it has been hidden before this rule has been applied. Just return nil and leave it as hidden.



56
57
58
59
# File 'lib/styles/rule.rb', line 56

def apply(line)
  return nil if line.nil?
  properties.inject(line.dup) {|result, property| property.apply(result) }
end