class Crowbar::Client::Util::Editor

Launch an editor and return the edited content

Attributes

content[RW]
options[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/crowbar/client/util/editor.rb, line 30
def initialize(options = {})
  self.options = options
end

Public Instance Methods

edit!() click to toggle source
# File lib/crowbar/client/util/editor.rb, line 49
def edit!
  file.write formatted
  file.rewind

  original_mtime = File.mtime file.path

  unless start
    raise EditorStartupError,
      "Failed to start a default editor"
  end

  updated_mtime = File.mtime file.path

  unless original_mtime < updated_mtime
    raise EditorAbortError,
      "Closed editor without saving"
  end

  self.content = file.read
  true
ensure
  file.close
  file.unlink
end
result() click to toggle source
# File lib/crowbar/client/util/editor.rb, line 34
def result
  case options.fetch(:format, :json)
  when :json
    begin
      JSON.load content
    rescue JSON::ParserError
      raise InvalidJsonError,
        "Failed to parse the JSON"
    end
  else
    raise InvalidFormatError,
      "This format is not supported by the editor"
  end
end

Protected Instance Methods

file() click to toggle source
# File lib/crowbar/client/util/editor.rb, line 76
def file
  @file ||= Tempfile.new(
    options.fetch(
      :prefix,
      "editor"
    )
  )
end
formatted() click to toggle source
# File lib/crowbar/client/util/editor.rb, line 85
def formatted
  case options.fetch(:format, :json)
  when :json
    JSON.pretty_generate(
      options.fetch(
        :content,
        {}
      )
    )
  else
    raise InvalidFormatError,
      "This format is not supported by the editor"
  end
end
program() click to toggle source
# File lib/crowbar/client/util/editor.rb, line 100
def program
  ENV["EDITOR"] || "vi"
end
start() click to toggle source
# File lib/crowbar/client/util/editor.rb, line 104
def start
  system(program, file.path) && file.open
end