Class: Crowbar::Client::Util::Editor

Inherits:
Object
  • Object
show all
Defined in:
lib/crowbar/client/util/editor.rb

Overview

Launch an editor and return the edited content

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Editor

Returns a new instance of Editor.



30
31
32
# File 'lib/crowbar/client/util/editor.rb', line 30

def initialize(options = {})
  self.options = options
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



27
28
29
# File 'lib/crowbar/client/util/editor.rb', line 27

def content
  @content
end

#optionsObject

Returns the value of attribute options.



28
29
30
# File 'lib/crowbar/client/util/editor.rb', line 28

def options
  @options
end

Instance Method Details

#edit!Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 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

#resultObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 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