class Pineapples::Actions::InsertIntoFile
Attributes
behaviour[R]
flag[R]
new_content[R]
Public Class Methods
new(generator, target, new_content, options)
click to toggle source
Calls superclass method
Pineapples::Actions::EmptyDirectory::new
# File lib/pineapples/actions/insert_into_file.rb, line 63 def initialize(generator, target, new_content, options) super(generator, target, {verbose: true}.merge(options)) @behaviour = @options.key?(:after) ? :after : :before @flag = @options.delete(@behaviour) @new_content = new_content.is_a?(Proc) ? new_content.call : new_content @flag = Regexp.escape(@flag) if !@flag.is_a?(Regexp) end
Public Instance Methods
invoke!()
click to toggle source
# File lib/pineapples/actions/insert_into_file.rb, line 73 def invoke! say_status status(:invoke) content = if @behavior == :after '\0' + replacement else replacement + '\0' end regexp = /#{flag}/ replace!(regexp, content, options[:force]) end
revoke!()
click to toggle source
# File lib/pineapples/actions/insert_into_file.rb, line 87 def revoke! say_status status(:revoke) if @behavior == :after content = '\1\2' regexp = /(#{flag})(.*)(#{Regexp.escape(new_content)})/m else content = '\2\3' regexp = /(#{Regexp.escape(new_content)})(.*)(#{flag})/m end replace!(regexp, content, true) end
Protected Instance Methods
replace!(regexp, string, force)
click to toggle source
# File lib/pineapples/actions/insert_into_file.rb, line 119 def replace!(regexp, string, force) if execute? content = File.binread(target.fullpath) if force || !content.include?(new_content) content.gsub!(regexp, string) File.open(target.fullpath, 'wb') { |file| file.write(content) } end end end
status(execution_style)
click to toggle source
# File lib/pineapples/actions/insert_into_file.rb, line 105 def status(execution_style) if execution_style == :invoke if flag == /\A/ :prepend elsif flag == /\z/ :append else :insert end else :subtract end end