Class: Hamloft::StyleBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/hamloft/style_builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, styles = []) ⇒ StyleBuilder

Returns a new instance of StyleBuilder.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/hamloft/style_builder.rb', line 6

def initialize(options, styles = [])
  @options = {}
  @styles = {}

  # expand margins
  if styles.include?(:margin)
    styles |= %i[margin_top margin_right margin_bottom margin_left]
    styles.reject! { |_style| styles === :margin }
  end

  # expand paddings
  if styles.include?(:padding)
    styles |= %i[padding_top padding_right padding_bottom padding_left]
    styles.reject! { |_style| styles === :padding }
  end

  # build sanitized options
  options.each do |k, v|
    @options[sanitize_style(k)] = v
  end

  # add initial styles
  add_multi(styles)
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/hamloft/style_builder.rb', line 3

def options
  @options
end

#stylesObject

Returns the value of attribute styles.



4
5
6
# File 'lib/hamloft/style_builder.rb', line 4

def styles
  @styles
end

Instance Method Details

#add(style, value = nil, template = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/hamloft/style_builder.rb', line 43

def add(style, value = nil, template = nil)
  style = sanitize_style(style)

  # handle empty value field
  if (!value || value.empty?) && !(!(@options[style]) || @options[style].empty?)
    value = @options[style]
  end

  # apply template
  if value && !value.empty? && template && !template.empty?
    value = ERB.new(template).result(binding)
  end

  @styles[style] = value if value && !value.empty?
end

#add_multi(styles) ⇒ Object



37
38
39
40
41
# File 'lib/hamloft/style_builder.rb', line 37

def add_multi(styles)
  styles.each do |style|
    add(style)
  end
end

#process(block = nil) ⇒ Object



31
32
33
34
35
# File 'lib/hamloft/style_builder.rb', line 31

def process(block = nil)
  block.call(self) if block
  result = @styles.map { |k, v| "#{k}: #{v};" }.join(' ')
  result.empty? ? nil : result
end

#sanitize_style(value) ⇒ Object



59
60
61
62
63
# File 'lib/hamloft/style_builder.rb', line 59

def sanitize_style(value)
  value.to_s.gsub(/([A-Z]+)([A-Z][a-z])/, '\1-\2')
       .gsub(/([a-z\d])([A-Z])/, '\1-\2')
       .tr('_', '-').downcase
end