Class: InteractiveEditor

Inherits:
Object
  • Object
show all
Defined in:
lib/interactive_editor.rb

Defined Under Namespace

Modules: Editors, Exec

Constant Summary collapse

VERSION =
'0.0.11'
EDITORS =
Hash.new { |h,k| h[k] = InteractiveEditor.new(k) }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(editor) ⇒ InteractiveEditor

Returns a new instance of InteractiveEditor.



17
18
19
# File 'lib/interactive_editor.rb', line 17

def initialize(editor)
  @editor = editor.to_s
end

Instance Attribute Details

#editorObject

Returns the value of attribute editor.



15
16
17
# File 'lib/interactive_editor.rb', line 15

def editor
  @editor
end

Class Method Details

.edit(editor, self_, file = nil) ⇒ Object



58
59
60
# File 'lib/interactive_editor.rb', line 58

def self.edit(editor, self_, file=nil)
  find_editor[editor].edit(self_, file)
end

.find_editorObject



62
63
64
65
66
67
68
69
# File 'lib/interactive_editor.rb', line 62

def self.find_editor
  #maybe serialise last file to disk, for recovery
  if defined?(Pry) and IRB == Pry
    IRB.config.interactive_editors ||= EDITORS
  else
    IRB.conf[:interactive_editors] ||= EDITORS
  end
end

Instance Method Details

#edit(object, file = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/interactive_editor.rb', line 21

def edit(object, file=nil)
  object = object == TOPLEVEL_BINDING.eval('self') ? nil : object

  current_file = if file
    FileUtils.touch(file) unless File.exist?(file)
    File.new(file)
  else
    if @file && File.exist?(@file.path) && !object
      @file
    else
      Tempfile.new( object ? ["yobj_tempfile", ".yml"] : ["irb_tempfile", ".rb"] )
    end
  end

  if object
    File.open( current_file.path, 'w' ) { |f| f << object.to_yaml }
  else
    @file = current_file
    mtime = File.stat(@file.path).mtime
  end

  args = Shellwords.shellwords(@editor) #parse @editor as arguments could be complex
  args << current_file.path
  current_file.close rescue nil
  Exec.system(*args)

  if object
    File.exists?(current_file.path) ? YAML.load_file(current_file.path) : object
  elsif mtime < File.stat(@file.path).mtime
    execute
  end
end

#executeObject



54
55
56
# File 'lib/interactive_editor.rb', line 54

def execute
  eval(IO.read(@file.path), TOPLEVEL_BINDING)
end