I've been trying to insert a few new associations into an existing model using the insert_into_file
method in a custom generator. For aesthetic reasons, and to avoid hard-coding anything, I would like to insert them after the last ones found. I tried to implement this with a regexp that works in Rubular, but not when I run the generator:
def add_associations_to_other_things
content = <<-CONTENT
has_many :things
CONTENT
inject_into_file "app/models/other_things.rb", \
content, \
:after => /(?:(has_and_belongs_to_many|has_many|has_one|belongs_to)[^\n]*$)(?!.*has_and_belongs_to_many|has_many|has_one|belongs_to.*\z)/m
end
In words, this should find the last association out to a newline that is not followed by any more associations. The m
option means that the dots in the negative lookahead should be treated as newlines and so should look out to the end of the file. In Rubular, the final association is selected, but when the generator is run, the content is inserted after every association.
What's wrong with my regexp?