Skip to content
thomasklemm edited this page Jan 6, 2013 · 8 revisions

Tip: Automatically annotate models after each run of rake db:migrate and rake db:rollback

Version A

In Rails 3 using as gem - also see the discussion on this issue

# lib/tasks/auto_annotate_models
# Annotate models on each run of rake db:migrate
Dir["#{Gem::Specification.find_by_name("annotate").full_gem_path}/**/tasks/**/*.rake"].each {|ext| load ext} if Rails.env.development?

Version B

This way was tested with the current master version of annotate (2.6.0.beta1), as the one propose in Version A) did not work properly.

# Gemfile
# Annotate models in the current master version from github
gem 'annotate', github: 'ctran/annotate_models' # This syntax works with Bundler 1.2+
# lib/tasks/auto_annotate_models.rake
if(Rails.env.development?)
  task :set_annotation_options do
    # Just some example settings from annotate 2.6.0.beta1
    Annotate.set_defaults({
      'position_in_routes'   => "before",
      'position_in_class'    => "before",
      'position_in_test'     => "before",
      'position_in_fixture'  => "before",
      'position_in_factory'  => "before",
      'show_indexes'         => "true",
      'simple_indexes'       => "false",
      'model_dir'            => "app/models",
      'include_version'      => "false",
      'require'              => "",
      'exclude_tests'        => "false",
      'exclude_fixtures'     => "false",
      'exclude_factories'    => "false",
      'ignore_model_sub_dir' => "false",
      'skip_on_db_migrate'   => "false",
      'format_bare'          => "true",
      'format_rdoc'          => "false",
      'format_markdown'      => "false",
      'sort'                 => "true",
      'force'                => "false",
      'trace'                => "false",
    })
  end

  # Comes with the current master when running `rails g annotate:install`
  # But somehow won't annotate my models correctly (only one)
  # Thus commented out
  # Annotate.load_tasks

  # Annotate models
  task :annotate do
    puts 'Annotating models...'
    system 'bundle exec annotate'
  end

  # Run annotate task after db:migrate
  #  and db:rollback tasks
  Rake::Task['db:migrate'].enhance do
    Rake::Task['annotate'].invoke
  end

  Rake::Task['db:rollback'].enhance do
    Rake::Task['annotate'].invoke
  end
end