views:

43

answers:

2

I am trying to create a rails template that will add code to files at particular line numbers. For example I need to add a route to the config/routes.rb

I have tried sed, gsed(only cause I am on a mac and they say that sed has problems with insert and append), anyway, I was not able to achieve the result I want.

Any help on this will be greatly appreciated.

I have tried several permutations of this command, but none work, here is an example

run "gsed '3 a/This is it' config/routes.rb"

perhaps even another suggestion

EDIT::::::

ok I took a break and when I came back, after reading up on sed, I realized that I needed to write the stream back to the file, but I was doing this before with,

run  "gsed '2 a\
Add this line after 2nd line
' config/routes.rb > config/routes.rb"

but the routes file would be blank, so I tried using a different filename(new.routes.rb),

run  "gsed '2 a\
Add this line after 2nd line
' config/routes.rb > config/new.routes.rb"

and this worked, so I know what to do now.

+1  A: 

I have to wonder why you're using sed for this. Write a Ruby script to open up the file, read it in line by line, make your changes and write the file back out. About the only problem you're going to have with that is editing a file "in place." To get around that, open up a temporary file, write to that file, then move that file over the old file using File.move.

AboutRuby
+1 This is essentially was rails itself does to add routes when you generate a resource.
Shadwell
can this be done with a rails template?, please understand I am new to the ruby on rails world, just trying to swim out to this little ruby island, without a boat. lol
iAm
A: 

this will do the trick, just remember to delete the old one and rename the new on in its place

run  "gsed '2 a\
Add this line after 2nd line
' config/routes.rb > config/new.routes.rb"
iAm