New gem 'thor-ext' with addons and patches for updating the Gemfile

I know the code could be much improved, fx the add_gem has so far no
support for an options hash.
Perhaps this could be integrated into the original
Rails::Generators::Actions in a new fork?
I will also work on a 'txt-mutator' gem with a DSL for general-purpose
code (text file) refactorings.

'thor-ext' updates and extends Rails::Generators::Actions with the

module ThorExtensions
  def append_line_to_file(path, *args, &block)
    if block_given?
      data = block
      data = args.shift
    append_file path, "#{data}\n"

  # add newline between each gem statement in Gemfile
  # Use Rails.root ?
  def cleanup_gemfile
    gsub_file 'Gemfile', /('|")gem/, "\1\ngem"

  def has_gem?(text, gem_name)
    if /\n[^#]*gem\s*('|")\s*#{Regexp.escape(gem_name)}\s*('|")/

  def has_plugin?(plugin_name), "vendor/plugins/

  def add_gem(gem_name, gem_version = nil)
    if !has_gem?(gemfile_txt, gem_name)
      gem_version_str = gem_version ? ", '#{gem_version}'" : ''
      append_line_to_file 'Gemfile', "gem

  def add_gems(gem_names)
    gem_names.each{|gem_name| add_gem(gem_name) }

  # Use Rails.root here?
  def gemfile_txt
    @gemfile_txt ||='Gemfile').read

# patch to add newline after gem '..' so we avoid a Gemfile like this:
# gem 'abc' gem 'abd'... but instead have newlines after each.
# Also only adds gem statement if gem statement not already present
def gem(*args)
        in_root do
          if !has_gem?(gemfile_txt, gem_name)
            append_line_file "Gemfile", "gem #{parts.join(",
")}", :verbose => false