Class: BabelBridge::Tools

Inherits:
Object
  • Object
show all
Defined in:
lib/babel_bridge/tools.rb

Class Method Summary collapse

Class Method Details

.array_to_anchored_or_regexp(array) ⇒ Object



55
56
57
# File 'lib/babel_bridge/tools.rb', line 55

def array_to_anchored_or_regexp(array)
  Regexp.new "^"+array_to_or_regexp_string(array)+"$"
end

.array_to_or_regexp(array) ⇒ Object



59
60
61
# File 'lib/babel_bridge/tools.rb', line 59

def array_to_or_regexp(array)
  Regexp.new array_to_or_regexp_string(array)
end

.array_to_or_regexp_string(array) ⇒ Object

Takes an array of Strings and Regexp and generates a new Regexp that matches the or (“|”) of all strings and Regexp



47
48
49
50
51
52
53
# File 'lib/babel_bridge/tools.rb', line 47

def array_to_or_regexp_string(array)
  array = symbols_to_strings array.flatten
  array = sort_operator_patterns array
  array = regexp_and_strings_to_regexpstrings array

  array.collect {|op| "(#{op})"}.join('|')
end

.indent(string, first_indent = " ", rest_indent = first_indent) ⇒ Object



5
6
7
# File 'lib/babel_bridge/tools.rb', line 5

def indent(string, first_indent = "  ", rest_indent = first_indent)
  first_indent + string.gsub("\n", "\n#{rest_indent}")
end

.line_column(string, offset) ⇒ Object

return the line and column of a given offset into this string line and column are 1-based



24
25
26
27
28
# File 'lib/babel_bridge/tools.rb', line 24

def line_column(string, offset)
  return 1,1 if string.length==0 || offset==0
  lines = (string[0..offset-1] + " ").split("\n")
  return lines.length, lines[-1].length
end

.regexp_and_strings_to_regexpstrings(array) ⇒ Object



34
35
36
# File 'lib/babel_bridge/tools.rb', line 34

def regexp_and_strings_to_regexpstrings(array)
  array.collect {|op| op.kind_of?(Regexp) ? op.source : Regexp.escape(op)}
end

.sort_operator_patterns(array) ⇒ Object

sort strings first, regexp second sort strings by lenght, longest first will then match first to last



41
42
43
# File 'lib/babel_bridge/tools.rb', line 41

def sort_operator_patterns(array)
  array.sort_by {|a| a.kind_of?(Regexp) ? 0 : -a.length}
end

.symbols_to_strings(array) ⇒ Object



30
31
32
# File 'lib/babel_bridge/tools.rb', line 30

def symbols_to_strings(array)
  array.collect {|op| op.kind_of?(Symbol) ? op.to_s : op}
end

.uniform_tabs(string) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/babel_bridge/tools.rb', line 9

def uniform_tabs(string)
  lines = string.split("\n").collect{|line|line.split("\t")}
  max_fields = lines.collect {|line| line.length}.max
  max_fields.times do |field|
    max_field_length = lines.collect {|line| (line[field]||"").length}.max
    formatter = "%-#{max_field_length}s"
    lines.each_with_index do |line,i|
      lines[i][field] = formatter%line[field] if line[field]
    end
  end
  lines.collect {|line|line.join.rstrip}.join("\n")
end