Forum: Ruby on Rails Generator that alters existing files

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
161680423be7c93cd4ce7dc3e080d642?d=identicon&s=25 Gareth Adams (Guest)
on 2006-06-02 15:02
(Received via mailing list)
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
6076c22b65b36f5d75c30bdcfb2fda85?d=identicon&s=25 Ezra Zygmuntowicz (Guest)
on 2006-06-03 08:45
(Received via mailing list)
On Jun 2, 2006, at 6:01 AM, Gareth Adams wrote:

> 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
This topic is locked and can not be replied to.