Module: GraphQL::Language::BlockString

Defined in:
lib/graphql/language/block_string.rb

Class Method Summary collapse

Class Method Details



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/graphql/language/block_string.rb', line 46

def self.print(str, indent: '')
  lines = str.split("\n")

  block_str = "#{indent}\"\"\"\n".dup

  lines.each do |line|
    if line == ''
      block_str << "\n"
    else
      sublines = break_line(line, 120 - indent.length)
      sublines.each do |subline|
        block_str << "#{indent}#{subline}\n"
      end
    end
  end

  block_str << "#{indent}\"\"\"\n".dup
end

.trim_whitespace(str) ⇒ Object

Remove leading and trailing whitespace from a block string. See “Block Strings” in https://github.com/facebook/graphql/blob/master/spec/Section%202%20–%20Language.md



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/graphql/language/block_string.rb', line 7

def self.trim_whitespace(str)
  lines = str.split("\n")
  common_indent = nil

  # find the common whitespace
  lines.each_with_index do |line, idx|
    if idx == 0
      next
    end
    line_length = line.size
    line_indent = line[/\A */].size
    if line_indent < line_length && (common_indent.nil? || line_indent < common_indent)
      common_indent = line_indent
    end
  end

  # Remove the common whitespace
  if common_indent
    lines.each_with_index do |line, idx|
      if idx == 0
        next
      else
        line[0, common_indent] = ""
      end
    end
  end

  # Remove leading & trailing blank lines
  while lines.first.empty?
    lines.shift
  end
  while lines.last.empty?
    lines.pop
  end

  # Rebuild the string
  lines.join("\n")
end