| Class | AutomateIt::EditManager::EditSession |
| In: |
lib/automateit/edit_manager.rb
|
| Parent: | AutomateIt::Common |
EditSession provides a way to edit files and strings.
For example, here‘s how to edit a string from the Interpreter:
edit(:text => "# hello") do
uncomment "llo"
append "world"
end
# => "hello\nworld"
The above example edits a text string containing "# hello". The editing session uncomments the line containing "llo" and then appends a line with the word "world". The edited result is returned, containing two lines: "hello" and "world".
The edit session only makes changes if they‘re needed. In the above example, once the "hello" line is uncommented, the "uncomment" command won‘t do anything. Similarly, once the word "world" has been appended, it won‘t be appended again. So if you re-edit the resulting string, it won‘t be changed because it‘s already in the desired state.
This approach simplifies editing because you only need to specify the commands that are needed to change the file, and the session will figure out which ones to run.
| comment_prefix | [RW] | Comment prefix, e.g., "/*" |
| comment_suffix | [RW] | Comment suffix, e.g., "*/" |
| contents | [RW] | Current contents of the editing buffer. |
| filename | [RW] | File that was read for editing. |
| original_contents | [RW] | Original contents of the editing buffer before any changes were made. |
| params | [RW] | Hash of parameters to make available to the editing session. |
Create an EditSession.
Options:
Edit a file or string.
Requires a filename argument or options hash — e.g.,. edit("foo") and edit(:file => "foo") will both edit a file called foo.
Options:
Edit a string:
edit(:text => "foo") do
replace "o", "@"
end
# => "f@@"
Edit a file and pass parameters to the editing session:
edit(:file => "myfile", :params => {:greet => "world"} do
prepend "MyHeader"
append "Hello "+params[:greet]
end
Edit a file, create it and set permissions if necessary:
edit("/tmp/foo", :create => true, :mode => 0600, :user => :root) do
prepend "Hello world!"
end
Manipulate the buffer. The result of your block will replace the buffer. This is very useful for complex edits.
Example:
manipulate do |buffer|
buffer.gsub(/foo/, "bar")
end
Prepend line to the top of the buffer, but only if it‘s not in this file already.
Options:
Example:
# Buffer's contents are 'add this line'
# This will prepend a line because they're not identical.
prepend("add this line")
# Won't prepend line because Regexp matches exisint line in buffer.
prepend("add this line", :unless => /add\s*this\*line/)