Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a file with a rails generator

How do you make a generator that alters a file.

Im trying to make it so that it finds a pattern in a file and adds come content to the line below it.

like image 440
Arcath Avatar asked Jan 18 '10 18:01

Arcath


1 Answers

Rails' scaffold generator does this when it adds a route to config/routes.rb It does this by calling a very simple method:

def gsub_file(relative_destination, regexp, *args, &block)
  path = destination_path(relative_destination)
  content = File.read(path).gsub(regexp, *args, &block)
  File.open(path, 'wb') { |file| file.write(content) }
end

What it's doing is taking a path/file as the first argument, followed by a regexp pattern, gsub arguments, and the block. This is a protected method that you'll have to recreate in order to use. I'm not sure if destination_path is something you'll have access to, so you'll probably want to pass in the exact path and skip any conversion.

To use gsub_file, let's say you want to add tags to your user model. Here's how you would do it:

line = "class User < ActiveRecord::Base"
gsub_file 'app/models/user.rb', /(#{Regexp.escape(line)})/mi do |match|
  "#{match}\n  has_many :tags\n"
end

You're finding the specific line in the file, the class opener, and adding your has_many line right underneath.

Beware though, because this is the most brittle way to add content, which is why routing is one of the only places that uses it. The example above would normally be handled with a mix-in.

like image 68
Jaime Bellmyer Avatar answered Nov 15 '22 17:11

Jaime Bellmyer