Module: MadCat::Helpers::ClassMethods

Included in:
MadCat::Helpers
Defined in:
lib/madcat/helpers.rb

Instance Method Summary collapse

Instance Method Details

#exec!(argv, stdin = '') ⇒ Object

Run argv via Open4, optionally passing it stdin.

Parameters:

  • argv (Array)

    Command

  • stdin (String) (defaults to: '')

    Stdin data



12
13
14
15
16
# File 'lib/madcat/helpers.rb', line 12

def exec!(argv, stdin='')
  stdout, stderr = '', ''
  status = Open4::spawn argv, {'quiet' => true, 'raise' => true, 'stdin' => stdin, 'stdout' => stdout, 'stderr' => stderr}
  Hashie::Mash.new({ :status => status.exitstatus, :stdin => stdin, :stdout => stdout, :stderr => stderr, :cmd => argv })
end

#stream_as_array(stream = STDIN, delim = "\t") ⇒ Object

Read stream line-wise, yield line.split(delim)

Parameters:

  • stream (IO) (defaults to: STDIN)

    Stream to read from

  • delim (String) (defaults to: "\t")

    Field delimiter



22
23
24
25
26
# File 'lib/madcat/helpers.rb', line 22

def stream_as_array(stream=STDIN, delim="\t")
  stream.each do |line|
    yield line.split(delim)
  end
end

#yaml_preamble(text) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/madcat/helpers.rb', line 31

def yaml_preamble(text)
  preamble_lines = []
  body_lines = []

  state = :before_preamble

  text.split("\n").each do |line|
    stripped = line.strip

    case state
      when :before_preamble
        new_state = case stripped
          when "---" 
            :preamble
          when "" 
            :before_preamble
          else 
            raise "First line must begin with ---"
        end

      when :preamble
        new_state = case stripped
          when "---" 
            :after_preamble
          else 
            preamble_lines << line
            :preamble
        end

      when :after_preamble
        new_state = :after_preamble
        body_lines << line

      else raise "Invalid State: #{ state }"
    end

    state = new_state
  end
  return [YAML::load(preamble_lines.join), body_lines.join]
end