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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Rails’ scaffold generator does this when it adds a route to
config/routes.rbIt does this by calling a very simple method: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_pathis 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:You’re finding the specific line in the file, the class opener, and adding your
has_manyline 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.