Module: Main::Util::Methods

Defined in:
lib/main/util.rb

Instance Method Summary collapse

Instance Method Details

#columnize(buf, opts = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/main/util.rb', line 40

def columnize buf, opts = {}
  width = Util.getopt 'width', opts, 80
  indent = Util.getopt 'indent', opts
  indent = Fixnum === indent ? (' ' * indent) : "#{ indent }"
  column = []
  words = buf.split %r/\s+/o
  row = "#{ indent }"
  while((word = words.shift))
    if((row.size + word.size) < (width - 1))
      row << word
    else
      column << row
      row = "#{ indent }"
      row << word
    end
    row << ' ' unless row.size == (width - 1)
  end
  column << row unless row.strip.empty?
  column.join "\n"
end

#getopt(opt, hash, default = nil) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/main/util.rb', line 61

def getopt opt, hash, default = nil
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return hash[key] if hash.has_key? key
    key = "#{ key }"
    return hash[key] if hash.has_key? key
    key = key.intern
    return hash[key] if hash.has_key? key
  end

  return default
end

#indent(chunk, n = 2) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/main/util.rb', line 14

def indent chunk, n = 2
  lines = chunk.split %r/\n/
  re = nil
  s = ' ' * n
  lines.map! do |line|
    unless re
      margin = line[%r/^\s*/]
      re = %r/^#{ margin }/
    end
    line.gsub re, s 
  end.join("\n")
end

#mcp(obj) ⇒ Object



10
11
12
# File 'lib/main/util.rb', line 10

def mcp obj
  Marshal.load(Marshal.dump(obj))
end

#unindent(chunk) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/main/util.rb', line 27

def unindent chunk
  lines = chunk.split %r/\n/
  indent = nil
  re = %r/^/ 
  lines.map! do |line|
    unless indent 
      indent = line[%r/^\s*/]
      re = %r/^#{ indent }/
    end
    line.gsub re, ''
  end.join("\n")
end