Thor - inject into file at end
Asked Answered
L

1

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.

Lett answered 7/11, 2013 at 12:21 Comment(0)
M
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....

Meza answered 7/11, 2013 at 13:40 Comment(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.Lett
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.Meza
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.Meza
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.Lett

© 2022 - 2024 — McMap. All rights reserved.