Class: Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/nginx-conf/compiler.rb

Constant Summary collapse

@@spaces =
' ' * 4

Instance Method Summary collapse

Constructor Details

#initialize(repeats) ⇒ Compiler

Returns a new instance of Compiler.



4
5
6
# File 'lib/nginx-conf/compiler.rb', line 4

def initialize repeats
  @repeats = repeats
end

Instance Method Details

#compile(hash) ⇒ Object



8
9
10
11
# File 'lib/nginx-conf/compiler.rb', line 8

def compile hash
  @indents = 0
  compile_hash_without_brackets hash
end

#compile_elem(object) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/nginx-conf/compiler.rb', line 13

def compile_elem object
  case object
  when Hash
    compile_hash object
  when Array
    object.map{ |o| compile_elem(o) }.join(' ')
  when -> (o) { o.respond_to? :to_s }
    object.to_s
  else
    raise "The object doesn't respond to to_s method.: #{o}"
  end
end

#compile_hash(hash) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/nginx-conf/compiler.rb', line 26

def compile_hash hash
  s = "{\n"
  @indents += 1
  s += compile_hash_without_brackets hash
  @indents -= 1
  s + indent('}')
end

#compile_hash_item(key, values) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/nginx-conf/compiler.rb', line 46

def compile_hash_item key, values
  values = [values] if not values.is_a? Array
  values[0] = "(#{values[0]})" if key == :if

  values_str = compile_elem(values)
  indent(key.to_s + (values_str != '' ? ' ' + values_str : '') \
         + (values[-1].is_a?(Hash) ? "" : ";")) + "\n"
end

#compile_hash_without_brackets(hash) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nginx-conf/compiler.rb', line 34

def compile_hash_without_brackets hash
  hash.map do |key, values|
    if @repeats.include? key
      values.map do |values_per_item|
        compile_hash_item key, values_per_item
      end.join
    else
      compile_hash_item key, values
    end
  end.join
end

#indent(line) ⇒ Object



55
56
57
# File 'lib/nginx-conf/compiler.rb', line 55

def indent line
  @@spaces * @indents + line
end