On Jun 2, 2006, at 6:01 AM, Gareth Adams wrote:
> What''s the best way to go about writing a generator that can add
> text into an
> existing file?
>
> The point in the file is marked with a unique token, I want to
> insert a few
> lines after the line with the token on it.
>
> Is this possible/easy/already done by someone?
>
> Thanks
>
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
It is a bit dangerous to add code to a file like that already has
content. But it can be done. I don''t think there is any direct
support for it in the generator stuff. But you could do something
like this:
# in app/models/foo.rb
class Foo
def initialize
end
#REPLACEME
end
# in generator or script
def add_to_file(filename, placeholder, replacement_code)
finished_product = IO.read(filename).gsub! /#{Regexp.quote
(placeholder)}/, replacement_code
File.open(filename, ''w+'') { |f| f.write finished_product }
end
code =<<-EOF
def additional_method
# whatever here
end
EOF
placeholder = "#REPLACEME"
file = "#{RAILS_ROOT}/app/models/foo.rb"
add_to_file(file, placeholder, code)
# foo.rb after the code is added to it
class Foo
def initialize
end
def additional_method
# whatever here
end
end
Cheers-
-Ezra