うちのいぬ Tech Blog

Tech Blog of Uchinoinu/My dog

annotate gem: write schema or routing on model file, routes file

http://whyzat.com/wp-content/uploads/2014/04/Useful-Dog.jpg (source: http://whyzat.com/wp-content/uploads/2014/04/Useful-Dog.jpg)

Version

Ruby # 2.2.1
Rails # 4.2.0

Install

$ vi Gemfile
-------- 
  # add
  gem 'annotate'
--------
$ bundle install

Make Config File(Task File)

$ bundle exec rails g annotate:install
$ vi lib/tasks/auto_annotate_models.rake
---
# NOTE: only doing this in development as some production environments (Heroku)
# NOTE: are sensitive to local FS writes, and besides -- it's just not proper
# NOTE: to have a dev-mode tool do its thing in production.
if Rails.env.development?
  task :set_annotation_options do
    # You can override any of these by setting an environment variable of the
    # same name.
    Annotate.set_defaults({
      'position_in_routes'   => "before", # before/after
      '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", # model_directory_path
      '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'                 => "false",
      'force'                => "false",
      'trace'                => "false",
    })
  end

  Annotate.load_tasks
end

Check Task

$ rake -T
---

rake annotate_models         # Add schema information (as comments) to model and fixture files
rake annotate_routes         # Adds the route map to routes.rb

Write

Model

$ cd project_root
$ bundle install annotate
---
Annotated (27): HogeModelName, FugaModelName, OtherModelName......
---

Route

$ rake annotate_routes
---
Route file annotated.
# == Route Map
#
# Starting up a new ElasticSearch client with
#                              Prefix Verb     URI Pattern                                                          Controller#Action
# hoge GET /hoge(.:format) hoges#index
  ・
  ・
  ・
Rails.application.routes.draw do
  get 'hoge' => 'hoge#index'
  scope 'hoge' do
  ・
  ・
  ・

update

if you change schema or routing, command above agin and the updated code is reflected.