Class: RubyCms::CommandRunner

Inherits:
Object
  • Object
show all
Defined in:
app/services/ruby_cms/command_runner.rb

Overview

Runs whitelisted Rake tasks and reads log tails for the admin Commands UI.

Class Method Summary collapse

Class Method Details

.run_rake(task) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/services/ruby_cms/command_runner.rb', line 9

def run_rake(task)
  raise ArgumentError, "rake task blank" if task.to_s.strip.blank?

  env = { "RAILS_ENV" => Rails.env.to_s }
  argv = ["bundle", "exec", "rake", task.to_s]
  stdout_and_stderr, status = Open3.capture2e(env, *argv, chdir: Rails.root.to_s)
  <<~TEXT.strip
    $ #{argv.join(' ')}
    (exit #{status.exitstatus})

    #{stdout_and_stderr}
  TEXT
rescue Errno::ENOENT => e
  <<~TEXT.strip
    Failed to run command: #{e.message}
  TEXT
end

.tail_log(lines: 400, max_bytes: 512 * 1024) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/services/ruby_cms/command_runner.rb', line 27

def tail_log(lines: 400, max_bytes: 512 * 1024)
  path = Rails.root.join("log", "#{Rails.env}.log")
  return "(Log file not found: #{path})" unless path.file?

  File.open(path, "rb") do |f|
    size = f.size
    f.seek([0, size - max_bytes].max)
    chunk = f.read
    chunk.lines.last(lines.to_i.clamp(1, 10_000)).join
  end
rescue StandardError => e
  "(Could not read log: #{e.message})"
end