rails / thor

Thor is a toolkit for building powerful command-line interfaces.
http://whatisthor.com/
MIT License
5.13k stars 552 forks source link

anyone needs insert_into_file(between: ___) ? #688

Closed xiaohui-zhangxh closed 1 year ago

xiaohui-zhangxh commented 4 years ago

Hi, I'm curious why nobody asking insert_into_file with between feature? I was get embarrassed many times without any solution to do this:

Here is a simplified webpacker.yml that we just focus on the key point.

# config/webpacker.yml
default: &default
  extract_css: false
development:
  <<: *default
test:
  <<: *default
production:
  <<: *default
  extract_css: true

I'm going to write a rails template that add extract_css: true to development section with this code:

inject_into_file 'config/webpacker.yml', after: /^development:\n *<<: \*default\n/ do
  <<~YAML.indent(2)
    extract_css: true
  YAML
end

unfortunately extract_css: true already exists after production section which also after development section, so inject_into_file will do nothing.

what if inject_into_file support option between or bi-options after + before, it should inserted successfully.

inject_into_file 'config/webpacker.yml', between: [/^development:\n *<<: \*default\n/, /^production:/] do
  <<~YAML.indent(2)
    extract_css: true
  YAML
end

or

inject_into_file 'config/webpacker.yml', after: /^development:\n *<<: \*default\n/, before: /^production:/ do
  <<~YAML.indent(2)
    extract_css: true
  YAML
end
xiaohui-zhangxh commented 4 years ago

My tricky solution is:

inject_into_file 'config/webpacker.yml', after: /^development:\n *<<: \*default\n/ do
  <<~YAML.indent(2)
    extract_css: true # this is for dev
  YAML
end