Class: Scriptor::Script

Inherits:
Object
  • Object
show all
Defined in:
app/models/scriptor/script.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ Script

コンストラクタでファイル名を受け取る



8
9
10
11
# File 'app/models/scriptor/script.rb', line 8

def initialize(filename)
  @filename = filename
  @content = load_content
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



5
6
7
# File 'app/models/scriptor/script.rb', line 5

def content
  @content
end

#filenameObject (readonly)

Returns the value of attribute filename.



5
6
7
# File 'app/models/scriptor/script.rb', line 5

def filename
  @filename
end

Class Method Details

.allObject

クラスメソッドで全スクリプトを取得



14
15
16
17
18
19
# File 'app/models/scriptor/script.rb', line 14

def self.all
  scripts_path = Rails.root.join("script")
  Dir.glob("#{scripts_path}/**/*.rb").map do |file|
    new(file.sub("#{scripts_path}/", "")) # 各スクリプトをインスタンス化
  end
end

.find(filename) ⇒ Object

クラスメソッドで特定のスクリプトを検索してインスタンス化



22
23
24
25
26
27
# File 'app/models/scriptor/script.rb', line 22

def self.find(filename)
  scripts_path = Rails.root.join("script", "#{filename}.rb")
  return nil unless File.exist?(scripts_path)

  new(filename)
end

Instance Method Details

#run(*args) ⇒ Object

スクリプトの実行メソッド



30
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
# File 'app/models/scriptor/script.rb', line 30

def run(*args)
  raise "Script content is empty" if content.blank?

  script_path = Rails.root.join("script", "#{filename}.rb")
  raise "Script file does not exist: #{script_path}" unless File.exist?(script_path)

  escaped_args = args.map(&:shellescape).join(" ")
  command = "ruby #{script_path} #{escaped_args}"
  # Rails 環境が正しくロードされるように Rails.root をカレントディレクトリに設定
  execution = Execution.create!(
    script_filename: filename,
    status: :running,
    executed_command: command,
    started_at: Time.current
  )
  Dir.chdir(Rails.root) do
    _, err, status = Open3.capture3(command)
    if status.success?
      # コマンド成功時の処理
      execution.update!(status: :success, finished_at: Time.current)
    else
      error_message = err.presence || "Command failed with exit status #{status.exitstatus}"
      execution.update!(status: :error, error_message: error_message.strip, finished_at: Time.current)
      raise error_message
    end
  end
end