Module: Hiiro::Background

Defined in:
lib/hiiro/background.rb

Constant Summary collapse

SESSION =
'h-bg'

Class Method Summary collapse

Class Method Details

.ensure_sessionObject



28
29
30
31
32
# File 'lib/hiiro/background.rb', line 28

def self.ensure_session
  unless system('tmux', 'has-session', '-t', SESSION, out: File::NULL, err: File::NULL)
    system('tmux', 'new-session', '-d', '-s', SESSION, out: File::NULL, err: File::NULL)
  end
end

.inside_tmux?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/hiiro/background.rb', line 24

def self.inside_tmux?
  ENV['TMUX'] && !ENV['TMUX'].empty?
end

.run(*cmd, dir: nil) ⇒ Object

Run cmd asynchronously. Inside tmux, spins up a hidden window in the h-bg session so you can attach and inspect if needed. Outside tmux, falls back to a detached spawn.

dir: optional directory to cd into before running the command.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/hiiro/background.rb', line 10

def self.run(*cmd, dir: nil)
  if inside_tmux?
    ensure_session
    tmux_args = ['tmux', 'new-window', '-d', '-t', "#{SESSION}:", '-n', cmd.first.to_s]
    tmux_args += ['-c', dir] if dir
    system(*tmux_args, cmd.shelljoin)
  else
    spawn_opts = dir ? { chdir: dir } : {}
    Process.detach(spawn(*cmd, **spawn_opts))
  end
rescue
  nil
end