8

I am working on a rails engine and I am trying to write a generator that will put this line

do_stuff (foo)

as the last statement in config/routes.rb, without breaking the file syntax.

Specifically, if my config/routes.rb looks like this currently

Rails.application.routes.draw do
    blah
    more blah
end

After running the generator I would like the config/routes.rb to look like this

Rails.application.routes.draw do
    blah
    more blah
    do_stuff (foo) # injected line
end

I looked at what ActiveAdmin does, but am unable to create a blanket last line rule. Any help is greatly appreciated.

1 Answer 1

14

i did not test that out, but i think from what you linked to in the ActiveAdmin generator it might work like this:

inject_into_file "config/routes.rb", "  do_stuff(foo)\n", :before => /^end/

this should insert your code right before an end token that starts at the beginning of a line. this only works for properly formatted routes files though....

4
  • I thought of that. But I was wondering if Thor could be more intelligent. Problem with such before is that it will inject the line before the first end which could be a block. Nov 7, 2013 at 13:53
  • 3
    thor would have to know about the code tree to do what you are thinking about. this is not a trivial thing, you can read about ruby AST and things like ripper, which is part of the STDLIB.
    – phoet
    Nov 7, 2013 at 13:56
  • 2
    the regular expression that i used will not insert it to any end. it will look for the one that is not indented. in a properly indented/formatted file this should work like a charm.
    – phoet
    Nov 7, 2013 at 13:57
  • Brilliant. I think I can live with that assumption. Thanks. I dont think I'd go the route of AST, seems too much for what I want to achieve. Nov 7, 2013 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.