smashingboxes / boxcar-generator-archive

A tool for generating Rails applications with the best practices of the Smashing Boxes team.
MIT License
16 stars 2 forks source link

Add custom rails generators #136

Open dkniffin opened 5 years ago

dkniffin commented 5 years ago

For example, customize our model generator so that it generates specs with all the right it { is_expected.to respond_to(:attribute) } and such

dkniffin commented 5 years ago

One nice thing would be if generated files got # frozen_string_literal: true at the top by default

Edit: Here's the code to do that:

# https://gist.github.com/ta1kt0me/6a7058d16621785d4f7038bde6cd3b98

module AddFrozenStringLiteralComment
  def add_frozen_string_literal_comment(dist)
    if File.exist?(dist) && File.extname(dist) == '.rb'
      File.open(dist, 'r') do |f|
        body = f.read

        File.open(dist, 'w') do |new_f|
          new_f.write("# frozen_string_literal: true\n\n" + body)
        end
      end
    end
  end
end

module GeneratorPrepend
  include AddFrozenStringLiteralComment

  def invoke!
    res = super
    add_frozen_string_literal_comment(existing_migration)
    res
  end
end

module TemplatePrepend
  include AddFrozenStringLiteralComment

  def template(source, *args, &block)
    res = super
    add_frozen_string_literal_comment(args.first)
    res
  end
end

Rails::Generators::Migration
Rails::Generators::Actions::CreateMigration.send :prepend, GeneratorPrepend
Rails::Generators::NamedBase.send :prepend, TemplatePrepend

It can go in config/initializers/generators/frozen_string_literal.rb