Class: Wunderbar::BuilderClass

Inherits:
BuilderBase show all
Defined in:
lib/wunderbar/builder.rb

Direct Known Subclasses

JsonBuilder, TextBuilder, XmlMarkup

Instance Method Summary collapse

Methods inherited from BuilderBase

#get_binding, #set_variables_from_params

Instance Method Details

#system(*args) {|:stdin, echo| ... } ⇒ Object

execute a system command, echoing stdin, stdout, and stderr

Yields:

  • (:stdin, echo)


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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/wunderbar/builder.rb', line 43

def system(*args)
  opts = {}
  opts = args.pop if Hash === args.last
  command = args
  command = args.first if args.length == 1 and Array === args.first

  if command.respond_to? :flatten
    flat = command.flatten
    secret = command - flat
    begin
      # if available, use escape as it does prettier quoting
      raise LoadError if $SAFE > 0 and not defined? Escape
      require 'escape'
      echo = Escape.shell_command(command.compact - secret)
    rescue LoadError
      # std-lib function that gets the job done
      echo = Shellwords.join(command.compact - secret)
    end
    command = flat.compact.map(&:dup).map(&:untaint)
  else
    echo = command
    command = [command]
  end

  patterns = opts[:hilite] || []
  patterns=[patterns] if String === patterns or Regexp === patterns
  patterns.map! do |pattern|
    String === pattern ? Regexp.new(Regexp.escape(pattern)) : pattern
  end

  yield :stdin, echo unless opts[:echo] == false

  semaphore = Mutex.new
  env = {'LC_CTYPE' => 'en_US.UTF-8'}
  Open3.popen3(env, *command) do |pin, pout, perr, wait|
    [
      Thread.new do
        until pout.eof?
          out_line = pout.readline.chomp
          semaphore.synchronize do
            if patterns.any? {|pattern| out_line =~ pattern}
              yield :hilite, out_line
            else
              yield :stdout, out_line
            end
          end
        end
      end,

      Thread.new do
        until perr.eof?
          err_line = perr.readline.chomp
          semaphore.synchronize do
            yield :stderr, err_line
          end
        end
      end,

      Thread.new do
        if opts[:stdin].respond_to? :read
          require 'fileutils'
          FileUtils.copy_stream opts[:stdin], pin
        elsif opts[:stdin]
          pin.write opts[:stdin].to_s
        end
        pin.close
      end
    ].each {|thread| thread.join}
    wait and wait.value.exitstatus
  end
end

#websocket(*args, &block) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/wunderbar/builder.rb', line 34

def websocket(*args, &block)
  if Hash === args.last
    args.last[:locals] = Hash[instance_variables.
      map { |name| [name.to_s.sub('@',''), instance_variable_get(name)] } ]
  end
  Wunderbar.websocket(*args, &block)
end