Module: Bruhl

Defined in:
lib/bruhl.rb,
lib/bruhl/version.rb

Defined Under Namespace

Classes: Object, QuotedString, RawString, Relation

Constant Summary collapse

BOM =
"\xEF\xBB\xBF"
EMPTY_OBJECT =
Bruhl::Object.new([]).freeze
VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.bom_present?(filename) ⇒ Boolean

Returns:

  • (Boolean)


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

def self.bom_present?(filename)
  bom_range = File.open(filename, 'rb').read(BOM.bytesize)
  bom_range == BOM.force_encoding(bom_range.encoding)
end

.generate(root, indent = 0) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/bruhl.rb', line 5

def self.generate(root, indent = 0)
  case root
  when Bruhl::Object
    generate_object(root, indent)
  when Bruhl::Relation
    generate_relation(root, indent)
  when Bruhl::RawString
    root.to_s
  when Bruhl::QuotedString
    '"' + root.to_s + '"'
  when Integer, Float
    root.to_s
  when Enumerable
    root.map { |elem| Bruhl.generate(elem) }
  end
end

.generate_object(root, indent = 0) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bruhl.rb', line 22

def self.generate_object(root, indent = 0)
  str = ''
  str += "#{root.tag}: " if root.tag
  if root.contents.empty?
    str += '{}'
  elsif root.contents.none? { |elem| elem.is_a?(Bruhl::Object) || elem.is_a?(Bruhl::Relation) }
    str += '{ '
    str += root.contents.map { |elem| Bruhl.generate(elem) }.join(' ')
    str += ' }'
  else
    str += '{'
    str += "\n"
    root.contents.each do |elem|
      str += ((' ' * (indent + 2)) + Bruhl.generate(elem, indent + 2)) + "\n"
    end
    str += ' ' * indent
    str += '}'
  end
  str
end

.generate_relation(root, indent = 0) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/bruhl.rb', line 43

def self.generate_relation(root, indent = 0)
  [
    root.left.to_s,
    root.operator.to_s,
    Bruhl.generate(root.right, indent)
  ].join(' ')
end

.parse(str, opts = {}) ⇒ Object



51
52
53
# File 'lib/bruhl.rb', line 51

def self.parse(str, opts = {})
  self.parser.parse(str, opts).value
end

.parse_file(filename, opts = {}) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/bruhl.rb', line 61

def self.parse_file(filename, opts = {})
  file_body =
    if bom_present?(filename)
      File.open(filename, 'r:bom|utf-8')  { |f| f.read }
    else
      File.open(filename, 'r:utf-8') { |f| f.read }
    end
  self.parse(file_body, opts)
end

.parserObject



71
72
73
74
75
76
77
# File 'lib/bruhl.rb', line 71

def self.parser
  @@parser ||=
    begin
      Citrus.load(File.join(__dir__, 'bruhl', 'grammar'))
      @@parser = BruhlGrammar
    end
end