Commit 43e11856 by Cuong Tran

Merge branch 'release/3.2.0'

parents 111640d0 d3a135de
Dockerfile
coverage
spec/**/*.rb
lib/**/*.rb
-
README.rdoc
CHANGELOG.rdoc
TODO.rdoc
README.md
CHANGELOG.md
TODO.md
template: |
## What's Changed
$CHANGES
name: CI
on:
pull_request:
branches:
- '*'
push:
branches:
- '*'
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
ruby: ['2.4', '2.5', '2.6']
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Install sqlite
run: |
sudo apt-get install libsqlite3-dev
- name: Run Tests
run: INTEGRATION_TESTS=1 bundle exec rspec
- name: Rubocop
run: bundle exec rubocop
name: "Code scanning - action"
on:
push:
branches-ignore:
- pr/*
- scratch/*
pull_request:
schedule:
- cron: '0 20 * * 7'
jobs:
CodeQL-Build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
name: Release Drafter
on:
push:
branches:
- develop
jobs:
update_release_draft:
runs-on: ubuntu-latest
steps:
# Drafts your next Release notes as Pull Requests are merged into "develop"
- uses: release-drafter/release-drafter@v5
with:
config-name: release-drafter.yml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Setup Ruby
uses: actions/setup-ruby@v1
with:
ruby-version: 2.6.x
- name: Bundle
run: |
gem update --system
gem update bundler
bundle install --jobs 4 --retry 3
- name: Publish to GPR
run: |
mkdir -p $HOME/.gem
touch $HOME/.gem/credentials
chmod 0600 $HOME/.gem/credentials
printf -- "---\n:github: Bearer ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials
gem build *.gemspec
gem push --KEY github --host https://rubygems.pkg.github.com/${OWNER} *.gem
env:
GEM_HOST_API_KEY: ${{ secrets.GPR_AUTH_TOKEN }}
OWNER: ctran
!/spec/integration/*/log/.gitkeep
!/spec/integration/*/tmp/.gitkeep
*.gem
.DS_Store
.bundle
......@@ -16,8 +14,4 @@
/doc/*
/pkg/*
/spec/debug.log
/spec/integration/*/bin/
/spec/integration/*/db/test.*
/spec/integration/*/log/*
/spec/integration/*/tmp/*
.byebug_history
......@@ -6,3 +6,8 @@ AllCops:
- 'vendor/**/*'
- 'spec/fixtures/**/*'
- 'tmp/**/*'
- 'spec/integration/**/*'
Metrics/BlockLength:
Exclude:
- 'spec/**/*.rb'
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2019-06-16 12:01:03 -0700 using RuboCop version 0.68.1.
# on 2020-04-06 10:26:11 +0900 using RuboCop version 0.68.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 9
# Configuration parameters: Include.
# Include: **/*.gemfile, **/Gemfile, **/gems.rb
Bundler/DuplicatedGem:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/Gemfile'
- 'spec/integration/rails_3.2.2/Gemfile'
- 'spec/integration/rails_3.2.8/Gemfile'
- 'spec/integration/rails_3.2_autoloading_factory_girl/Gemfile'
- 'spec/integration/rails_3.2_custom_inflections/Gemfile'
- 'spec/integration/rails_3.2_with_asset_pipeline/Gemfile'
- 'spec/integration/rails_4.1.1/Gemfile'
- 'spec/integration/rails_4.2.0/Gemfile'
- 'spec/integration/standalone/Gemfile'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: TreatCommentsAsGroupSeparators, Include.
# Include: **/*.gemfile, **/Gemfile, **/gems.rb
Bundler/OrderedGems:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/Gemfile'
- 'spec/integration/rails_3.2_with_asset_pipeline/Gemfile'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: TreatCommentsAsGroupSeparators, Include.
......@@ -45,13 +21,7 @@ Gemspec/RequiredRubyVersion:
Exclude:
- 'annotate.gemspec'
# Offense count: 2
# Cop supports --auto-correct.
Layout/AlignArray:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 104
# Offense count: 65
# Cop supports --auto-correct.
# Configuration parameters: EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle.
# SupportedHashRocketStyles: key, separator, table
......@@ -60,11 +30,7 @@ Layout/AlignArray:
Layout/AlignHash:
Exclude:
- 'lib/generators/annotate/templates/auto_annotate_models.rake'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/config/initializers/unified_initializer.rb'
- 'spec/integration/rails_4.1.1/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/rails_4.2.0/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/standalone/config/init.rb'
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -74,80 +40,22 @@ Layout/BlockAlignment:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 45
# Cop supports --auto-correct.
Layout/ClosingHeredocIndentation:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler.rb'
- 'spec/integration/rails_3.2.2.rb'
- 'spec/integration/rails_3.2.8.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl.rb'
- 'spec/integration/rails_3.2_custom_inflections.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline.rb'
- 'spec/integration/standalone.rb'
# Offense count: 14
# Offense count: 9
# Cop supports --auto-correct.
Layout/EmptyLineAfterGuardClause:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/integration_spec.rb'
# Offense count: 10
# Offense count: 2
# Cop supports --auto-correct.
Layout/EmptyLineAfterMagicComment:
Exclude:
- 'annotate.gemspec'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_3.2.2/db/schema.rb'
- 'spec/integration/rails_3.2.8/db/schema.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl/db/schema.rb'
- 'spec/integration/rails_3.2_custom_inflections/db/schema.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline/db/schema.rb'
- 'spec/integration/rails_4.1.1/db/schema.rb'
- 'spec/integration/rails_4.2.0/db/schema.rb'
- 'spec/integration/standalone/db/schema.rb'
# Offense count: 2
# Cop supports --auto-correct.
Layout/EmptyLines:
Exclude:
- 'spec/integration/rails_4.1.1/Gemfile'
- 'spec/integration/rails_4.2.0/Gemfile'
# Offense count: 1
# Cop supports --auto-correct.
Layout/EmptyLinesAroundAccessModifier:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 2
# Cop supports --auto-correct.
Layout/EmptyLinesAroundArguments:
Exclude:
- 'spec/annotate/annotate_routes_spec.rb'
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: empty_lines, no_empty_lines
Layout/EmptyLinesAroundBlockBody:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/db/schema.rb'
- 'spec/integration/rails_4.1.1/db/schema.rb'
- 'spec/integration/rails_4.2.0/db/schema.rb'
# Offense count: 1
# Cop supports --auto-correct.
Layout/EmptyLinesAroundExceptionHandlingKeywords:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 24
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment.
Layout/ExtraSpacing:
......@@ -155,67 +63,14 @@ Layout/ExtraSpacing:
- 'Guardfile'
- 'lib/annotate/annotate_models.rb'
- 'lib/tasks/annotate_routes.rake'
- 'spec/integration/rails_2.3_with_bundler/script/console'
- 'spec/integration/rails_3.2.2/script/rails'
- 'spec/integration/rails_3.2.8/script/rails'
- 'spec/integration/rails_3.2_autoloading_factory_girl/script/rails'
- 'spec/integration/rails_3.2_custom_inflections/script/rails'
- 'spec/integration/rails_3.2_with_asset_pipeline/script/rails'
- 'spec/integration/rails_4.1.1/Gemfile'
- 'spec/integration/rails_4.1.1/config.ru'
- 'spec/integration/rails_4.2.0/Gemfile'
- 'spec/integration/rails_4.2.0/config.ru'
# Offense count: 6
# Offense count: 16
# Cop supports --auto-correct.
# Configuration parameters: IndentationWidth.
# SupportedStyles: special_inside_parentheses, consistent, align_braces
Layout/IndentFirstHashElement:
# SupportedStyles: special_inside_parentheses, consistent, align_brackets
Layout/IndentFirstArrayElement:
EnforcedStyle: consistent
# Offense count: 54
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: auto_detection, squiggly, active_support, powerpack, unindent
Layout/IndentHeredoc:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/integration_spec.rb'
- 'spec/integration/rails_2.3_with_bundler.rb'
- 'spec/integration/rails_3.2.2.rb'
- 'spec/integration/rails_3.2.8.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl.rb'
- 'spec/integration/rails_3.2_custom_inflections.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline.rb'
- 'spec/integration/standalone.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: normal, rails
Layout/IndentationConsistency:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 5
# Cop supports --auto-correct.
# Configuration parameters: Width, IgnoredPatterns.
Layout/IndentationWidth:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/integration/rails_4.1.1/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.1.1/app/models/task.rb'
- 'spec/integration/rails_4.2.0/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.2.0/app/models/task.rb'
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, IndentationWidth.
# SupportedStyles: aligned, indented, indented_relative_to_receiver
Layout/MultilineMethodCallIndentation:
Exclude:
- 'spec/annotate/annotate_routes_spec.rb'
# Offense count: 5
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, IndentationWidth.
......@@ -224,30 +79,15 @@ Layout/MultilineOperationIndentation:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 3
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: space, no_space
Layout/SpaceAroundEqualsInParameterDefault:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 9
# Cop supports --auto-correct.
Layout/SpaceAroundKeyword:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/Gemfile'
- 'spec/integration/rails_3.2.2/Gemfile'
- 'spec/integration/rails_3.2.8/Gemfile'
- 'spec/integration/rails_3.2_autoloading_factory_girl/Gemfile'
- 'spec/integration/rails_3.2_custom_inflections/Gemfile'
- 'spec/integration/rails_3.2_with_asset_pipeline/Gemfile'
- 'spec/integration/rails_4.1.1/Gemfile'
- 'spec/integration/rails_4.2.0/Gemfile'
- 'spec/integration/standalone/Gemfile'
# Offense count: 5
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: AllowForAlignment.
Layout/SpaceAroundOperators:
......@@ -270,15 +110,6 @@ Layout/SpaceBeforeComment:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets.
# SupportedStyles: space, no_space, compact
# SupportedStylesForEmptyBrackets: space, no_space
Layout/SpaceInsideArrayLiteralBrackets:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/environment.rb'
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters.
......@@ -313,63 +144,18 @@ Layout/SpaceInsideStringInterpolation:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: IndentationWidth.
Layout/Tab:
Exclude:
- 'spec/integration/rails_4.1.1/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.1.1/app/models/task.rb'
- 'spec/integration/rails_4.2.0/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.2.0/app/models/task.rb'
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: final_newline, final_blank_line
Layout/TrailingBlankLines:
Exclude:
- 'spec/integration/rails_4.1.1/app/models/task_observer.rb'
- 'spec/integration/rails_4.1.1/config/initializers/cookies_serializer.rb'
- 'spec/integration/rails_4.2.0/app/models/task_observer.rb'
- 'spec/integration/rails_4.2.0/config/initializers/cookies_serializer.rb'
# Offense count: 3
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowInHeredoc.
Layout/TrailingWhitespace:
Exclude:
- 'spec/annotate/annotate_routes_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/db/schema.rb'
- 'spec/lib/annotate/annotate_routes_spec.rb'
# Offense count: 3
# Offense count: 2
# Configuration parameters: AllowSafeAssignment.
Lint/AssignmentInCondition:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 2
# Cop supports --auto-correct.
Lint/BigDecimalNew:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 6
# Cop supports --auto-correct.
Lint/DeprecatedClassMethods:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/rails_3.2.2/config/boot.rb'
- 'spec/integration/rails_3.2.8/config/boot.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl/config/boot.rb'
- 'spec/integration/rails_3.2_custom_inflections/config/boot.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline/config/boot.rb'
# Offense count: 1
Lint/DuplicateMethods:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 1
Lint/HandleExceptions:
......@@ -384,89 +170,69 @@ Lint/InheritException:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 3
# Offense count: 1
# Configuration parameters: MaximumRangeSize.
Lint/MissingCopEnableDirective:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 2
Lint/RescueException:
Exclude:
- 'Rakefile'
# Offense count: 5
# Cop supports --auto-correct.
Lint/ScriptPermission:
Exclude:
- 'spec/integration/rails_3.2.2/Rakefile'
- 'spec/integration/rails_3.2.8/Rakefile'
- 'spec/integration/rails_3.2_autoloading_factory_girl/Rakefile'
- 'spec/integration/rails_3.2_custom_inflections/Rakefile'
- 'spec/integration/rails_3.2_with_asset_pipeline/Rakefile'
# Offense count: 1
Lint/ShadowingOuterLocalVariable:
Exclude:
- 'Rakefile'
# Offense count: 7
# Cop supports --auto-correct.
# Configuration parameters: IgnoreEmptyBlocks, AllowUnusedKeywordArguments.
Lint/UnusedBlockArgument:
Exclude:
- 'bin/annotate'
# Offense count: 19
# Offense count: 22
Metrics/AbcSize:
Max: 138
Max: 103
# Offense count: 27
# Offense count: 7
# Configuration parameters: CountComments, ExcludedMethods.
# ExcludedMethods: refine
Metrics/BlockLength:
Max: 244
Max: 53
# Offense count: 1
# Configuration parameters: CountBlocks.
Metrics/BlockNesting:
Max: 4
# Offense count: 10
# Offense count: 12
Metrics/CyclomaticComplexity:
Max: 36
Max: 25
# Offense count: 29
# Offense count: 30
# Configuration parameters: CountComments, ExcludedMethods.
Metrics/MethodLength:
Max: 75
Max: 40
# Offense count: 8
# Offense count: 9
Metrics/PerceivedComplexity:
Max: 42
Max: 28
# Offense count: 1
Naming/AccessorMethodName:
Exclude:
- 'lib/annotate.rb'
# Offense count: 76
# Offense count: 103
# Configuration parameters: Blacklist.
# Blacklist: (?-mix:(^|\s)(EO[A-Z]{1}|END)(\s|$))
Naming/HeredocDelimiterNaming:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/annotate/annotate_routes_spec.rb'
- 'spec/lib/annotate/annotate_models_spec.rb'
- 'spec/lib/annotate/annotate_routes_spec.rb'
# Offense count: 2
# Offense count: 1
# Configuration parameters: EnforcedStyleForLeadingUnderscores.
# SupportedStylesForLeadingUnderscores: disallowed, required, optional
Naming/MemoizedInstanceVariableName:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 1
# Configuration parameters: MinNameLength, AllowNamesEndingInNumbers, AllowedNames, ForbiddenNames.
......@@ -475,56 +241,26 @@ Naming/UncommunicativeMethodParamName:
Exclude:
- 'Rakefile'
# Offense count: 1
# Offense count: 2
# Configuration parameters: EnforcedStyle.
# SupportedStyles: inline, group
Style/AccessModifierDeclarations:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: percent_q, bare_percent
Style/BarePercentLiterals:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: braces, no_braces, context_dependent
Style/BracesAroundHashParameters:
Exclude:
- 'spec/integration/rails_4.1.1/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/rails_4.2.0/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/standalone/config/init.rb'
- 'lib/annotate/annotate_routes/header_generator.rb'
# Offense count: 1
Style/CaseEquality:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 14
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AutoCorrect, EnforcedStyle.
# SupportedStyles: nested, compact
Style/ClassAndModuleChildren:
Exclude:
- 'lib/annotate/active_record_patch.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/integration/rails_2.3_with_bundler/test/test_helper.rb'
- 'spec/integration/rails_3.2.2/test/test_helper.rb'
- 'spec/integration/rails_3.2.8/test/test_helper.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl/test/test_helper.rb'
- 'spec/integration/rails_3.2_custom_inflections/test/test_helper.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline/test/test_helper.rb'
- 'spec/integration/rails_4.1.1/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.1.1/app/models/sub1/user.rb'
- 'spec/integration/rails_4.1.1/test/test_helper.rb'
- 'spec/integration/rails_4.2.0/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.2.0/app/models/sub1/user.rb'
- 'spec/integration/rails_4.2.0/test/test_helper.rb'
# Offense count: 2
Style/ClassVars:
......@@ -533,19 +269,11 @@ Style/ClassVars:
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SingleLineConditionsOnly, IncludeTernaryExpressions.
# SupportedStyles: assign_to_condition, assign_inside_condition
Style/ConditionalAssignment:
Exclude:
- 'bin/annotate'
# Offense count: 1
# Cop supports --auto-correct.
Style/Dir:
Exclude:
- 'bin/annotate'
# Offense count: 7
# Offense count: 10
Style/Documentation:
Exclude:
- 'spec/**/*'
......@@ -553,38 +281,33 @@ Style/Documentation:
- 'lib/annotate.rb'
- 'lib/annotate/active_record_patch.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'lib/annotate/annotate_routes/header_generator.rb'
- 'lib/annotate/annotate_routes/helpers.rb'
- 'lib/annotate/version.rb'
- 'lib/generators/annotate/install_generator.rb'
- 'lib/tasks/annotate_models_migrate.rake'
# Offense count: 10
# Offense count: 2
# Cop supports --auto-correct.
Style/Encoding:
Exclude:
- 'annotate.gemspec'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_3.2.2/db/schema.rb'
- 'spec/integration/rails_3.2.8/db/schema.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl/db/schema.rb'
- 'spec/integration/rails_3.2_custom_inflections/db/schema.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline/db/schema.rb'
- 'spec/integration/rails_4.1.1/db/schema.rb'
- 'spec/integration/rails_4.2.0/db/schema.rb'
- 'spec/integration/standalone/db/schema.rb'
# Offense count: 48
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/ExpandPathArguments:
Enabled: false
Exclude:
- 'annotate.gemspec'
# Offense count: 10
# Offense count: 9
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: format, sprintf, percent
Style/FormatString:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 23
# Configuration parameters: EnforcedStyle.
......@@ -593,36 +316,35 @@ Style/FormatStringToken:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 184
# Offense count: 30
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: when_needed, always, never
Style/FrozenStringLiteralComment:
Enabled: false
# Offense count: 5
# Offense count: 1
# Configuration parameters: MinBodyLength.
Style/GuardClause:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'lib/tasks/annotate_models_migrate.rake'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 57
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols.
# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys
Style/HashSyntax:
Enabled: false
Exclude:
- 'lib/tasks/annotate_routes.rake'
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 11
# Offense count: 7
# Cop supports --auto-correct.
Style/IfUnlessModifier:
Exclude:
- 'Rakefile'
- 'bin/annotate'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -641,30 +363,16 @@ Style/MissingRespondToMissing:
Exclude:
- 'lib/annotate/active_record_patch.rb'
# Offense count: 3
# Offense count: 1
Style/MixinUsage:
Exclude:
- 'Rakefile'
- 'spec/integration/integration_spec.rb'
# Offense count: 3
# Offense count: 2
Style/MultilineBlockChain:
Exclude:
- 'Rakefile'
- 'lib/annotate/annotate_models.rb'
- 'spec/spec_helper.rb'
# Offense count: 5
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: literals, strict
Style/MutableConstant:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/integration/rails_2.3_with_bundler/config/environment.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -674,12 +382,6 @@ Style/NestedParenthesizedCalls:
Exclude:
- 'bin/annotate'
# Offense count: 9
# Cop supports --auto-correct.
# Configuration parameters: Strict.
Style/NumericLiterals:
MinDigits: 15
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: AutoCorrect, EnforcedStyle, IgnoredMethods.
......@@ -690,32 +392,17 @@ Style/NumericPredicate:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
# Offense count: 24
# Offense count: 12
# Cop supports --auto-correct.
# Configuration parameters: PreferredDelimiters.
Style/PercentLiteralDelimiters:
Exclude:
- 'annotate.gemspec'
- 'bin/annotate'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'lib/tasks/annotate_models_migrate.rake'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_3.2.2/config/application.rb'
- 'spec/integration/rails_3.2.8/config/application.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl/config/application.rb'
- 'spec/integration/rails_3.2_custom_inflections/config/application.rb'
- 'spec/integration/rails_3.2_with_asset_pipeline/config/application.rb'
- 'spec/integration/rails_4.1.1/app/models/task.rb'
- 'spec/integration/rails_4.2.0/app/models/task.rb'
- 'spec/spec_helper.rb'
- 'spec/tasks/annotate_models_migrate_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/PerlBackrefs:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/lib/annotate/annotate_models_spec.rb'
- 'spec/lib/tasks/annotate_models_migrate_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -730,7 +417,7 @@ Style/RaiseArgs:
Style/RedundantBegin:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -743,7 +430,7 @@ Style/RedundantParentheses:
# Configuration parameters: AllowMultipleReturnValues.
Style/RedundantReturn:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'lib/annotate/annotate_routes/helpers.rb'
# Offense count: 2
# Cop supports --auto-correct.
......@@ -751,7 +438,7 @@ Style/RedundantSelf:
Exclude:
- 'lib/tasks/annotate_models_migrate.rake'
# Offense count: 13
# Offense count: 12
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, AllowInnerSlashes.
# SupportedStyles: slashes, percent_r, mixed
......@@ -759,14 +446,12 @@ Style/RegexpLiteral:
Exclude:
- 'Rakefile'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 2
# Offense count: 1
# Cop supports --auto-correct.
Style/RescueModifier:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -784,31 +469,29 @@ Style/SafeNavigation:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowAsExpressionSeparator.
Style/Semicolon:
Exclude:
- 'bin/annotate'
- 'spec/integration/rails_2.3_with_bundler/config/initializers/unified_initializer.rb'
# Offense count: 18
# Offense count: 15
# Cop supports --auto-correct.
Style/StderrPuts:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 243
# Offense count: 55
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline.
# SupportedStyles: single_quotes, double_quotes
Style/StringLiterals:
Enabled: false
Exclude:
- 'annotate.gemspec'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/parser.rb'
- 'lib/tasks/annotate_models_migrate.rake'
- 'lib/tasks/annotate_routes.rake'
- 'spec/lib/annotate/annotate_models_spec.rb'
- 'spec/lib/annotate/parser_spec.rb'
# Offense count: 1
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: single_quotes, double_quotes
......@@ -816,7 +499,7 @@ Style/StringLiteralsInInterpolation:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 10
# Offense count: 8
# Cop supports --auto-correct.
# Configuration parameters: MinSize.
# SupportedStyles: percent, brackets
......@@ -827,41 +510,25 @@ Style/SymbolArray:
# Cop supports --auto-correct.
Style/SymbolLiteral:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 1
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyleForMultiline.
# SupportedStylesForMultiline: comma, consistent_comma, no_comma
Style/TrailingCommaInArrayLiteral:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyleForMultiline.
# SupportedStylesForMultiline: comma, consistent_comma, no_comma
Style/TrailingCommaInHashLiteral:
Exclude:
- 'spec/integration/rails_4.1.1/lib/tasks/auto_annotate_models.rake'
- 'spec/integration/rails_4.2.0/lib/tasks/auto_annotate_models.rake'
- 'spec/lib/annotate/annotate_models_spec.rb'
# Offense count: 2
# Cop supports --auto-correct.
Style/UnneededInterpolation:
Exclude:
- 'bin/annotate'
# Offense count: 4
# Cop supports --auto-correct.
Style/UnneededPercentQ:
Exclude:
- 'annotate.gemspec'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 431
# Offense count: 381
# Cop supports --auto-correct.
# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
Max: 276
Max: 264
sudo: false
language: ruby
rvm:
- 2.2.10
- 2.3.8
- 2.4.6
- 2.5.5
- 2.6.0
- 2.6.1
- 2.6.2
- 2.6.3
- ruby-head
- 2.4.9
- 2.5.7
- 2.6.5
matrix:
allow_failures:
- rvm: ruby-head
env:
- RAILS_ENV=development RACK_ENV=development INTEGRATION_TESTS=1
cache: bundler
addons:
apt_packages:
- libsqlite3-dev
before_install:
- gem update --system || (gem i "rubygems-update:~>2.7" --no-document && update_rubygems)
- gem update bundler
- gem update --system --no-document --quiet
install:
- bundle install --jobs=3 --retry=3
script:
- bundle exec rubocop && bundle exec rspec
- bundle exec rspec
- bundle exec rubocop
jobs:
include:
- stage: gem release
if: tag =~ ^v
rvm: 2.6.0
script: echo "Deploying to rubygems.org ..."
rvm: 2.6.5
script: echo "Deploying to rubygems.org ..."
deploy:
provider: rubygems
api_key: $RUBYGEMS_API_KEY
......
== Authors
## Authors
- Original code by: Dave Thomas -- Pragmatic Programmers, LLC <http://agilewebdevelopment.com/plugins/annotate_models>
- Overhauled by: Alex Chaffee <http://alexch.github.com> alex@stinky.com
......@@ -6,7 +6,7 @@
- Maintained by: Alex Chaffee and Cuong Tran
- Homepage: http://github.com/ctran/annotate_models
With help from:
### With help from:
- Jack Danger - http://github.com/JackDanger
- Michael Bumann - http://github.com/bumi
......
## 3.1.1
Changes
- Bump required ruby version to >= 2.4 [#772](https://github.com/ctran/annotate_models/pull/772)
- [Revert #677] Fix column default annotations [#768](https://github.com/ctran/annotate_models/pull/768)
Project Improvements
- Refactor by adding AnnotateRoutes::Helpers [#770](https://github.com/ctran/annotate_models/pull/770)
- Bump puma from 4.3.1 to 4.3.3 in /spec/integration/rails_6.0.2.1 [#771](https://github.com/ctran/annotate_models/pull/771)
- Bump puma from 3.12.2 to 4.3.3 in /spec/integration/rails_5.2.4.1 [#769](https://github.com/ctran/annotate_models/pull/769)
- Bump nokogiri from 1.10.7 to 1.10.8 in /spec/integration/rails_5.2.4.1 [#766](https://github.com/ctran/annotate_models/pull/766)
- Bump nokogiri from 1.10.7 to 1.10.8 in /spec/integration/rails_6.0.2.1 [#765](https://github.com/ctran/annotate_models/pull/765)
- Refactor test cases of AnnotateRoutes [#760](https://github.com/ctran/annotate_models/pull/760)
- Rename FactoryGirl -> FactoryBot comment [#759](https://github.com/ctran/annotate_models/pull/759)
## 3.1.0
Changes
- Fix new lines after comments for rubocop compatibility [#757](https://github.com/ctran/annotate_models/pull/757)
- Fix messages from AnnotateRoutes [#737](https://github.com/ctran/annotate_models/pull/737)
- Support YARD notation [#724](https://github.com/ctran/annotate_models/pull/724)
- Refactor AnnotateRoutes.routes_file_exist? [#716](https://github.com/ctran/annotate_models/pull/716)
- Refactor namespace Annotate [#719](https://github.com/ctran/annotate_models/pull/719)
- Add columns managed by Globalize gem [#602](https://github.com/ctran/annotate_models/pull/602)
Bug Fixes
- Fix additional_file_patterns parsing [#756](https://github.com/ctran/annotate_models/pull/756)
- Fix typo in README [#752](https://github.com/ctran/annotate_models/pull/752)
- Fix bin/annotate NoMethodError [#745](https://github.com/ctran/annotate_models/pull/745)
- Fix README for YARD format [#740](https://github.com/ctran/annotate_models/pull/740)
- Fix constant names that were not renamed in #721 [#739](https://github.com/ctran/annotate_models/pull/739)
- Replace soft-deprecated constant `HashWithIndifferentAccess` to `ActiveSupport::HashWithIndifferentAccess` [#699](https://github.com/ctran/annotate_models/pull/699)
- [Fix #570](https://github.com/ctran/annotate_models/issues/570) Change of foreign key should be considered as a column change
- [Fix #430](https://github.com/ctran/annotate_models/issues/430) Handle columns from activerecord-postgis-adapter [#694](https://github.com/ctran/annotate_models/pull/694)
- Add ActiveAdmin option to template [#693](https://github.com/ctran/annotate_models/pull/693)
- Fix foreign key issue with Rails 6 and Sqlite3 [#695](https://github.com/ctran/annotate_models/pull/695)
- Fix Serializers Test Directory [#625](https://github.com/ctran/annotate_models/pull/625)
- [Fix #624](https://github.com/ctran/annotate_models/issues/624) Correct default values for columns when ActiveRecord::Enum is used [#677](https://github.com/ctran/annotate_models/pull/677)
- [Fix #675](https://github.com/ctran/annotate_models/issues/675) Correct indentation for double-byte characters [#676](https://github.com/ctran/annotate_models/pull/676)
- FIX: Ensure only one line is around the annotation [#669](https://github.com/ctran/annotate_models/pull/669)
- Fix shifted when format_markdown option enabled and used non-ascii [#650](https://github.com/ctran/annotate_models/pull/650)
Project improvements
- Refactor RSpec for AnnotateModels - structuralize test cases [#755](https://github.com/ctran/annotate_models/pull/755)
- Refactor test cases of AnnotateRoutes as for Rake versions [#754](https://github.com/ctran/annotate_models/pull/754)
- Add integration tests to project [#747](https://github.com/ctran/annotate_models/pull/747)
- Refactor test cases for AnnotateRoutes.remove_annotations [#748](https://github.com/ctran/annotate_models/pull/748)
- Refactor RSpec for AnnotateModels - with Globalize gem [#749](https://github.com/ctran/annotate_models/pull/749)
- Fixed CHANGELOG.md to add link to each PR [#751](https://github.com/ctran/annotate_models/pull/751)
- Delete integration test fixtures [#746](https://github.com/ctran/annotate_models/pull/746)
- Remove remaining integration test files [#744](https://github.com/ctran/annotate_models/pull/744)
- Remove unworking integration tests [#725](https://github.com/ctran/annotate_models/pull/725)
- Refactor Annotate::Parser [#742](https://github.com/ctran/annotate_models/pull/742)
- Refactor RSpec for AnnotateModels (4) - AnnotateModels.get_schema_info (without custom options) [#735](https://github.com/ctran/annotate_models/pull/735)
- Refactor RSpec for AnnotateRoutes (1) [#736](https://github.com/ctran/annotate_models/pull/736)
- Refactor AnnotateRoutes.rewrite_contents [#734](https://github.com/ctran/annotate_models/pull/734)
- AnnotateModels.get_schema_info (with custom options) [#732](https://github.com/ctran/annotate_models/pull/732)
- Fix typo in RSpec of AnnotateModels [#731](https://github.com/ctran/annotate_models/pull/731)
- Remove AnnotateRoutes.rewrite_contents_with_header [#730](https://github.com/ctran/annotate_models/pull/730)
- Refactor AnnotateRoutes.annotate_routes and .rewrite_contents_with_header [#729](https://github.com/ctran/annotate_models/pull/729)
- Refactor AnnotateModels::Parser [#728](https://github.com/ctran/annotate_models/pull/728)
- Remove invalid document of AnnotateRoutes.rewrite_contents [#727](https://github.com/ctran/annotate_models/pull/727)
- Refactor RSpec for AnnotateModels (1) [#726](https://github.com/ctran/annotate_models/pull/726)
- Refactor AnnotateModels::Helpers [#723](https://github.com/ctran/annotate_models/pull/723)
- Refactor AnnotateRoutes.remove_annotations [#715](https://github.com/ctran/annotate_models/pull/715)
- Fix AnnotateRoutes.extract_magic_comments_from_array [#712](https://github.com/ctran/annotate_models/pull/712)
- Rename FactoryGirl to FactoryBot [#721](https://github.com/ctran/annotate_models/pull/721)
- Refactor AnnotateRoutes.header [#714](https://github.com/ctran/annotate_models/pull/714)
- Freeze constant AnnotateRoutes::HEADER_ROW [#713](https://github.com/ctran/annotate_models/pull/713)
- Add constants MAGIC_COMMENT_MATCHER [#711](https://github.com/ctran/annotate_models/pull/711)
- Rename method and variable of AnnotateRoutes for readability [#709](https://github.com/ctran/annotate_models/pull/709)
- Refactor lib/annotate.rb [#707](https://github.com/ctran/annotate_models/pull/707)
- Delete TODO.md [#700](https://github.com/ctran/annotate_models/pull/700)
- Tidy README [#701](https://github.com/ctran/annotate_models/pull/701)
- Convert documentation files to Markdown [#697](https://github.com/ctran/annotate_models/pull/697)
- Upgrade and fix CI [#698](https://github.com/ctran/annotate_models/pull/698)
- Add upgrade instructions to README [#687](https://github.com/ctran/annotate_models/pull/687)
- Fix Github release action [#682](https://github.com/ctran/annotate_models/pull/682)
## 3.0.3
- Use a less error-prone way of specifying gem files [#662](https://github.com/ctran/annotate_models/pull/662)
- Update rake requirement from `>= 10.4, < 13.0` to `>= 10.4, < 14.0` [#659](https://github.com/ctran/annotate_models/pull/659)
- Bump nokogiri from 1.6.6.2 to 1.10.4 in /spec/integration/rails_4.2.0 [#655](https://github.com/ctran/annotate_models/pull/655)
- Default annotate models to true in config generated by `rails g annotate:install` [#671](https://github.com/ctran/annotate_models/pull/671)
- Bump loofah from 2.3.0 to 2.3.1 in /spec/integration/rails_4.2.0 [#681](https://github.com/ctran/annotate_models/pull/681)
## 3.0.2
- Fixes `LoadError` due to gemspec not referencing `parser.rb`, issue [#657](https://github.com/ctran/annotate_models/issues/657) [#660](https://github.com/ctran/annotate_models/pull/660)
- Changes `--additional_file_patterns` to use dashes `--additional-file-patterns` for consistency [#649](https://github.com/ctran/annotate_models/pull/649)
- Refactor: moving constants into `constants.rb` [#653](https://github.com/ctran/annotate_models/pull/653)
## 3.0.1
- Skipped as an official release, used the 3.0.1 patch for setting up Github Actions [#619](https://github.com/ctran/annotate_models/pull/619)
## 3.0.0
- **Breaking:** when option `models` is not set - models will not be annotated by default.
Add `'models'=>'true'` to your config manually or use `--models` option if using CLI.
- Added `--models` CLI option fixing issue [#563](https://github.com/ctran/annotate_models/issues/563) [#647](https://github.com/ctran/annotate_models/pull/647)
- Added `--additional_file_patterns` option for additional file patterns [#633](https://github.com/ctran/annotate_models/pull/633) [#636](https://github.com/ctran/annotate_models/pull/636) [#637](https://github.com/ctran/annotate_models/pull/637)
- Refactored CLI parser [#646](https://github.com/ctran/annotate_models/pull/646)
- Fixed `BigDecimal.new` deprecation warning [#634](https://github.com/ctran/annotate_models/pull/634)
- Fixed annotations for columns with long data types [#622](https://github.com/ctran/annotate_models/pull/622)
- Made methods private in AnnotateRoutes [#598](https://github.com/ctran/annotate_models/pull/598)
See https://github.com/ctran/annotate_models/releases/tag/v3.0.0
## 2.7.5
See https://github.com/ctran/annotate_models/releases/tag/v2.7.5
## 2.7.3
See https://github.com/ctran/annotate_models/releases/tag/v2.7.3
## 2.7.2
See https://github.com/ctran/annotate_models/releases/tag/v2.7.2
## 2.7.1
See https://github.com/ctran/annotate_models/releases/tag/v2.7.1
## 2.7.0
See https://github.com/ctran/annotate_models/releases/tag/v2.7.0
## 2.6.9
- Support foreigh key [#241](https://github.com/ctran/annotate_models/pull/241)
- Check if model has skip tag in annotate_model_file [#167](https://github.com/ctran/annotate_models/pull/167)
- Fix issue where serializer-related flags weren't being honored [#246](https://github.com/ctran/annotate_models/issues/246)
- Prefer SQL column type over normalized AR type [#231](https://github.com/ctran/annotate_models/issues/231)
## 2.6.8
- Nothing annotated unless `options[:model_dir]` is specified, [#234](https://github.com/ctran/annotate_models/pull/234)
## 2.6.7
- Nothing annotated unless `options[:model_dir]` is specified, [#234](https://github.com/ctran/annotate_models/pull/234)
## 2.6.6
- Makes it possible to wrap annotations, [#225](https://github.com/ctran/annotate_models/pull/225)
- Fix single model generation, [#214](https://github.com/ctran/annotate_models/pull/214)
- Fix default value for Rails 4.2, [#212](https://github.com/ctran/annotate_models/issues/212)
- Don't crash on inherited models in subdirectories, [#232](https://github.com/ctran/annotate_models/issues/232)
- Process model_dir in rake task, [#197](https://github.com/ctran/annotate_models/pull/197)
## 2.6.4
- Skip "models/concerns", [#194](https://github.com/ctran/annotate_models/pull/194)
- Fix [#173](https://github.com/ctran/annotate_models/issues/173) where annotate says "Nothing to annotate" in rails 4.2
- Display an error message if not run from the root of the project, [#186](https://github.com/ctran/annotate_models/pull/186)
- Support rails 4.0 new default test directory, [#182](https://github.com/ctran/annotate_models/issues/182)
- Add an option to show timestamp in routes "-timestamp", [#136](https://github.com/ctran/annotate_models/issues/136)
- Skip plain ruby objects if they have the same class name as an ActiveRecord object, [#121](https://github.com/ctran/annotate_models/issues/121)
## 2.6.3
- Fix bug of annotate position in routes [#158](https://github.com/ctran/annotate_models/issues/158)
## 2.6.2
- Retain the current annotate block unless --force is specified
- Always load models, since they may not be autoloaded by Rails
- The pg array type is now detected (see [#158](https://github.com/ctran/annotate_models/pull/158))
## 2.6.0.beta2
- support for composite_primary_keys (garysweaver)
- bug fix for annotate_one_file (vlado)
## 2.6.0.beta1
- It's now possible to use Annotate in standalone ActiveRecord (non-Rails) projects again.
- Adding note that Markdown is actually MultiMarkdown, and recommending the use
of the `kramdown` engine for parsing it.
- Improved Markdown formatting considerably.
- Bugfix: Needed to use inline-code tag for column and table names,
otherwise underscores would cause havok with the formatting.
- Bugfix: Markdown syntax was incorrect
(can't have trailing spaces before the closing marker for an emphasis tag).
- Bugfix: Remove-annotations wasn't properly finding test/spec files,
and wasn't even looking for FactoryGirl factories under the new naming convention.
- Bugfix: Load the Rakefile from the current directory, not the first
Rakefile in our load path.
- Added support for new FactoryGirl naming convention.
- Fix behavior of route annotations in newer versions of Rake that don't
spit out the CWD as their first line of output.
- Overhauled integration testing system to be much easier to work with,
better compartmentalized, and so forth -- at the cost that you must be
using RVM to utilize it. (It'll spit out appropriate pending messages if
you don't.) Also includes a mode for "tinkering" by hand with a scenario,
and won't let you run it through rspect if the repo is in a dirty state.
Added appropriate rake tasks to help with all of this.
- Routes can now be appended, pre-pended, or removed -- and do sane things in all cases.
- Expose all `position_*` variables as CLI params.
- Make `ENV ['position']` work as a default for all the `ENV ['position_*']` variables.
- Make rake tasks more resilient to unusual circumstances / code loading behavior.
- Resolve annotate vs. annotate_models ambiguity once and for all by
settling on `annotate_models` *and* `annotate_routes`. This avoids a name
collision with RMagick while not needlessly overloading the term.
- Fixed that schema kept prepending additional newlines
- Updates to make annotate smarter about when to touch a model
- Recognize column+type, and don't change a file unless the column+type
combination of the new schema are different than that of the old (i.e.,
don't regenerate if columns happen to be in a different order. That's just
how life is sometimes)
- Change annotate to use options hash instead of ENV.
## 2.5.0
- Works better with Rails 3
- Bugfix: schema kept prepending additional newlines
- Updates to make annotate smarter about when to touch a model
- Recognize column+type, and don't change a file unless the column+type
combination of the new schema are different than that of the old (i.e.,
don't regenerate if columns happen to be in a different order. That's just
how life is sometimes.)
- Grab old specification even if it has `\r\n` as line endings rather than pure `\n`s
- Various warning and specification fixes
- Fix "no such file to load -- annotate/annotate_models (MissingSourceFile)"
error (require statements in tasks now use full path to lib files)
- warn about macros, to mitigate when we're included during a production
run, not just a rakefile run -- possibly at the expense of too much noise
- Adding rake as a runtime dependency
- If the schema is already in the model file, it will be replaced into the same location.
If it didn't previously exist, it'll be placed according to the "position", as before.
- Allow task loading from Rakefile for gems (plugin installation already auto-detects).
- Add skip_on_db_migrate option as well for people that don't want it
- Fix options parsing to convert strings to proper booleans
- Add support for Fabrication fabricators
- Leave magic encoding comment intact
- Fix issue #14 - RuntimeError: Already memoized
- Count a model as 'annotated' if any of its tests/fixtures are annotated
- Support FactoryGirl
- Support :change migrations (Rails 3.1)
- Allow models with non-standard capitalization
- Widen type column so we can handle longtexts with chopping things off.
- Skip trying to get list of models from commandline when running via Rake
(was preventing the use of multiple rake tasks in one command if one of them was `db:migrate`).
- Add ability to skip annotations for a model by adding
`# -*- SkipSchemaAnnotations` anywhere in the file.
- Don't show column limits for integer and boolean types.
- Add sorting for columns and indexes.
(Helpful for out-of-order migration execution. Use `--sort` if you want this.)
- Annotate unit tests in subfolders.
- Add generator to install rakefile that automatically annotates on `db:migrate`.
- Correct Gemfile to clarify which environments need which gems.
- Add an .rvmrc to facilitate clean development.
- Refactor out ActiveRecord monkey-patch to permit extending without side-effects.
- Use ObjectSpace to locate models to facilitate handling of models with
non-standard capitalization.
Note that this still requires that the inflector be configured to understand
the special case.
- Shore up test cases a bit.
- Merge against many of the older branches on Github whose functionality is
already reflected to reduce confusion about what is and is not implemented here.
- Accept String or Symbol for :position (et al) options.
- Add RDoc output formatting as an option.
- Add Markdown output formatting as an option.
- Add option to force annotation regeneration.
- Add new configuration option for controlling where info is placed in
fixtures/factories.
- Fix for models without tables.
- Fix gemspec generation now that Jeweler looks at Gemfile.
- Fix warning: `NOTE: Gem::Specification#default_executable= is deprecated
with no replacement. It will be removed on or after 2011-10-01.`
- Fix handling of files with no trailing newline when putting annotations at
the end of the file.
- Now works on tables with no primary key.
- `--format=markdown` option
- `--trace` option to help debug "Unable to annotate" errors
- "Table name" annotation (if table name is different from model name)
- "Human name" annotation (enabling translation to non-English locales)
- Fix JRuby ObjectSpace compatibility bug (https://github.com/ctran/annotate_models/pull/85)
- Fix FactoryGirl compatibility bug (https://github.com/ctran/annotate_models/pull/82)
## 2.4.2 2009-11-21
- Annotates `(spec|test)/factories/<model>_factory.rb` files
## 2.4.1 2009-11-20
- Annotates thoughtbot's factory_girl factories (`test/factories/<model>_factory.rb`)
- Move default annotation position back to top
## 2.4.0 2009-12-13
- Incorporated lots of patches from the Github community,
including support for Blueprints fixtures
- Several bug fixes
## 2.1 2009-10-18
- New options
- `-R` to require additional files before loading the models
- `-i` to show database indexes in annotations
- `-e` to exclude annotating tests or fixtures
- `-m` to include the migration version number in the annotation
- `--model-dir` to annotate model files stored a different place than `app/models`
- Ignore unknown macros ('acts_as_whatever')
## 2.0 2009-02-03
- Add annotate_models plugin fork additions
- Annotates Rspec and Test Unit models
- Annotates Object Daddy exemplars
- Annotates geometrical columns
- Add AnnotateRoutes rake task
- Up gem structure to newgem defaults
## 1.0.4 2008-09-04
- Only update modified models since last run, thanks to sant0sk1
## 1.0.3 2008-05-02
- Add misc changes from Dustin Sallings and Henrik N
- Remove trailing whitespace
- More intuitive info messages
- Update README file with update-to-date example
## 1.0.2 2008-03-22
- Add contributions from Michael Bumann (http://github.com/bumi)
- added an option "position" to choose to put the annotation,
- spec/fixtures now also get annotated
- added a task to remove the annotations
- these options can be specified from command line as `-d` and `-p [before|after]`
== 2.7.5
See https://github.com/ctran/annotate_models/releases/tag/v2.7.5
== 2.7.3
See https://github.com/ctran/annotate_models/releases/tag/v2.7.3
== 2.7.2
See https://github.com/ctran/annotate_models/releases/tag/v2.7.2
== 2.7.1
See https://github.com/ctran/annotate_models/releases/tag/v2.7.1
== 2.7.0
See https://github.com/ctran/annotate_models/releases/tag/v2.7.0
== 2.6.9
* Support foreigh key (#241)
* Check if model has skip tag in annotate_model_file (#167)
* Fix issue where serializer-related flags weren't being honored (#246)
* Prefer SQL column type over normalized AR type (#231)
== 2.6.8
* Nothing annotated unless options[:model_dir] is specified, #234
== 2.6.7
* Nothing annotated unless options[:model_dir] is specified, #234
== 2.6.6
* Makes it possible to wrap annotations, #225
* Fix single model generation, #214
* Fix default value for Rails 4.2, #212
* Don't crash on inherited models in subdirectories, #232
* Process model_dir in rake task, #197
== 2.6.4
* Skip "models/concerns", #194
* Fix #173 where annotate says "Nothing to annotate" in rails 4.2
* Display an error message if not run from the root of the project, #186
* Support rails 4.0 new default test directory, #182
* Add an option to show timestamp in routes "-timestamp", #136
* Skip plain ruby objects if they have the same class name as an ActiveRecord object, #121
== 2.6.3
* Fix bug of annotate position in routes (#158)
== 2.6.2
* Retain the current annotate block unless --force is specified
* Always load models, since they may not be autoloaded by Rails
* The pg array type is now detected (see #158)
== 2.6.0.beta2
* support for composite_primary_keys (garysweaver)
* bug fix for annotate_one_file (vlado)
== 2.6.0.beta1
* It's now possible to use Annotate in standalone ActiveRecord (non-Rails)
projects again.
* Adding note that Markdown is actually MultiMarkdown, and recommending the use
of the `kramdown` engine for parsing it.
* Improved Markdown formatting considerably.
* Bugfix: Needed to use inline-code tag for column and table names, otherwise
underscores would cause havok with the formatting.
* Bugfix: Markdown syntax was incorrect (can't have trailing spaces before the
closing marker for an emphasis tag).
* Bugfix: Remove-annotations wasn't properly finding test/spec files, and
wasn't even looking for FactoryGirl factories under the new naming
convention.
* Bugfix: Load the Rakefile from the current directory, not the first Rakefile
in our load path.
* Added support for new FactoryGirl naming convention.
* Fix behavior of route annotations in newer versions of Rake that don't spit
out the CWD as their first line of output.
* Overhauled integration testing system to be much easier to work with, better
compartmentalized, and so forth -- at the cost that you must be using RVM to
utilize it. (It'll spit out appropriate pending messages if you don't.)
Also includes a mode for "tinkering" by hand with a scenario, and won't let
you run it through rspect if the repo is in a dirty state. Added appropriate
rake tasks to help with all of this.
* Routes can now be appended, pre-pended, or removed -- and do sane things in
all cases.
* Expose all `position_*` variables as CLI params.
* Make `ENV ['position']` work as a default for all the `ENV ['position_*']`
variables.
* Make rake tasks more resilient to unusual circumstances / code loading
behavior.
* Resolve annotate vs. annotate_models ambiguity once and for all by settling
on `annotate_models` _and_ `annotate_routes`. This avoids a name collision
with RMagick while not needlessly overloading the term.
* Fixed that schema kept prepending additional newlines
* Updates to make annotate smarter about when to touch a model
* Recognize column+type, and don't change a file unless the column+type
combination of the new schema are different than that of the old (i.e., don't
regenerate if columns happen to be in a different order. That's just how life
is sometimes)
* Change annotate to use options hash instead of ENV.
== 2.5.0
* Works better with Rails 3
* Bugfix: schema kept prepending additional newlines
* Updates to make annotate smarter about when to touch a model
* Recognize column+type, and don't change a file unless the column+type combination of the new schema are different than that of the old (i.e., don't regenerate if columns happen to be in a different order. That's just how life is sometimes.)
* Grab old specification even if it has \r\n as line endings rather than pure \ns
* Various warning and specification fixes
* Fix "no such file to load -- annotate/annotate_models (MissingSourceFile)"
error (require statements in tasks now use full path to lib files)
* warn about macros, to mitigate when we're included during a production run,
not just a rakefile run -- possibly at the expense of too much noise
* Adding rake as a runtime dependency
* If the schema is already in the model file, it will be replaced into the same
location. If it didn't previously exist, it'll be placed according to the
"position", as before.
* Allow task loading from Rakefile for gems (plugin installation already
auto-detects).
* Add skip_on_db_migrate option as well for people that don't want it
* Fix options parsing to convert strings to proper booleans
* Add support for Fabrication fabricators
* Leave magic encoding comment intact
* Fix issue #14 - RuntimeError: Already memoized
* Count a model as 'annotated' if any of its tests/fixtures are annotated
* Support FactoryGirl
* Support :change migrations (Rails 3.1)
* Allow models with non-standard capitalization
* Widen type column so we can handle longtexts with chopping things off.
* Skip trying to get list of models from commandline when running via Rake (was
preventing the use of multiple rake tasks in one command if one of them was
db:migrate).
* Add ability to skip annotations for a model by adding
'# -*- SkipSchemaAnnotations' anywhere in the file.
* Don't show column limits for integer and boolean types.
* Add sorting for columns and indexes. (Helpful for out-of-order migration
execution. Use --sort if you want this.)
* Annotate unit tests in subfolders.
* Add generator to install rakefile that automatically annotates on db:migrate.
* Correct Gemfile to clarify which environments need which gems.
* Add an .rvmrc to facilitate clean development.
* Refactor out ActiveRecord monkey-patch to permit extending without
side-effects.
* Use ObjectSpace to locate models to facilitate handling of models with
non-standard capitalization.
Note that this still requires that the inflector be configured to understand
the special case.
* Shore up test cases a bit.
* Merge against many of the older branches on Github whose functionality is
already reflected to reduce confusion about what is and is not implemented
here.
* Accept String or Symbol for :position (et al) options.
* Add RDoc output formatting as an option.
* Add Markdown output formatting as an option.
* Add option to force annotation regeneration.
* Add new configuration option for controlling where info is placed in
fixtures/factories.
* Fix for models without tables.
* Fix gemspec generation now that Jeweler looks at Gemfile.
* Fix warning: `NOTE: Gem::Specification#default_executable= is deprecated with
no replacement. It will be removed on or after 2011-10-01.`
* Fix handling of files with no trailing newline when putting annotations at
the end of the file.
* Now works on tables with no primary key.
* --format=markdown option
* --trace option to help debug "Unable to annotate" errors
* "Table name" annotation (if table name is different from model name)
* "Human name" annotation (enabling translation to non-English locales)
* Fix JRuby ObjectSpace compatibility bug (https://github.com/ctran/annotate_models/pull/85)
* Fix FactoryGirl compatibility bug (https://github.com/ctran/annotate_models/pull/82)
== 2.4.2 2009-11-21
* Annotates (spec|test)/factories/<model>_factory.rb files
== 2.4.1 2009-11-20
* Annotates thoughtbot's factory_girl factories (test/factories/<model>_factory.rb)
* Move default annotation position back to top
== 2.4.0 2009-12-13
* Incorporated lots of patches from the Github community, including support for
Blueprints fixtures
* Several bug fixes
== 2.1 2009-10-18
* New options
* -R to require additional files before loading the models
* -i to show database indexes in annotations
* -e to exclude annotating tests or fixtures
* -m to include the migration version number in the annotation
* --model-dir to annotate model files stored a different place than app/models
* Ignore unknown macros ('acts_as_whatever')
== 2.0 2009-02-03
* Add annotate_models plugin fork additions
* Annotates Rspec and Test Unit models
* Annotates Object Daddy exemplars
* Annotates geometrical columns
* Add AnnotateRoutes rake task
* Up gem structure to newgem defaults
== 1.0.4 2008-09-04
* Only update modified models since last run, thanks to sant0sk1
== 1.0.3 2008-05-02
* Add misc changes from Dustin Sallings and Henrik N
* Remove trailing whitespace
* More intuitive info messages
* Update README file with update-to-date example
== 1.0.2 2008-03-22
* Add contributions from Michael Bumann (http://github.com/bumi)
* added an option "position" to choose to put the annotation,
* spec/fixtures now also get annotated
* added a task to remove the annotations
* these options can be specified from command line as -d and -p [before|after]
source 'https://rubygems.org'
ruby '>= 2.2.0'
ruby '>= 2.4.0'
gem 'activerecord', '>= 4.2.5', require: false
gem 'activerecord', '>= 4.2.5', '< 6', require: false
gem 'rake', require: false
group :development do
......@@ -20,7 +20,10 @@ group :development, :test do
gem 'rspec', require: false
gem 'rubocop', '~> 0.68.1', require: false unless RUBY_VERSION =~ /^1.8/
gem 'simplecov', require: false
# gem 'rubocop', '~> 1.12', require: false
# gem 'rubocop-rake', require: false
# gem 'rubocop-rspec', require: false
# gem 'simplecov', require: false
gem 'terminal-notifier-guard', require: false
gem 'codeclimate-test-reporter'
......@@ -31,11 +34,11 @@ group :development, :test do
platforms :mri, :mingw do
gem 'pry', require: false
gem 'pry-coolline', require: false
gem 'pry-byebug', require: false
end
end
group :test do
gem 'files', require: false
gem 'wrong', require: false
gem 'git', require: false
end
# Note: The cmd option is now required due to the increasing number of ways
# NOTE: The cmd option is now required due to the increasing number of ways
# rspec may be run, below are examples of the most common uses.
# * bundler: 'bundle exec rspec'
# * bundler binstubs: 'bin/rspec'
......
## Annotate (aka AnnotateModels)
[![Gem Version](https://badge.fury.io/rb/annotate.svg)](http://badge.fury.io/rb/annotate)
[![Downloads count](https://img.shields.io/gem/dt/annotate.svg?style=flat)](https://rubygems.org/gems/annotate)
[![Build status](https://travis-ci.org/ctran/annotate_models.svg?branch=develop)](https://travis-ci.org/ctran/annotate_models)
[![CI Status](https://github.com/ctran/annotate_models/workflows/CI/badge.svg)](https://github.com/ctran/annotate_models/actions?workflow=CI)
[![Coveralls](https://coveralls.io/repos/ctran/annotate_models/badge.svg?branch=develop)](https://coveralls.io/r/ctran/annotate_models?branch=develop)
[![Maintenability](https://codeclimate.com/github/ctran/annotate_models/badges/gpa.svg)](https://codeclimate.com/github/ctran/annotate_models)
[![Inline docs](http://inch-ci.org/github/ctran/annotate_models.svg?branch=develop)](http://inch-ci.org/github/ctran/annotate_models)
Add a comment summarizing the current schema to the top or bottom of each of your...
- ActiveRecord models
- Fixture files
- Tests and Specs
- Object Daddy exemplars
- Machinist blueprints
- Fabrication fabricators
- Thoughtbot's factory_bot factories, i.e. the `(spec|test)/factories/<model>_factory.rb` files
- `routes.rb` file (for Rails projects)
The schema comment looks like this:
```ruby
# == Schema Info
#
# Table name: line_items
#
# id :integer(11) not null, primary key
# quantity :integer(11) not null
# product_id :integer(11) not null
# unit_price :float
# order_id :integer(11)
#
class LineItem < ActiveRecord::Base
belongs_to :product
. . .
```
It also annotates geometrical columns, `geom` type and `srid`,
when using `SpatialAdapter`, `PostgisAdapter` or `PostGISAdapter`:
```ruby
# == Schema Info
#
# Table name: trips
#
# local :geometry point, 4326
# path :geometry line_string, 4326
```
Also, if you pass the `-r` option, it'll annotate `routes.rb` with the output of `rake routes`.
## Upgrading to 3.X and annotate models not working?
In versions 2.7.X the annotate gem defaulted to annotating models if no arguments were passed in.
The annotate gem by default would not allow for routes and models to be annotated together.
A [change was added in #647](https://github.com/ctran/annotate_models/pull/647).
You [can read more here](https://github.com/ctran/annotate_models/issues/663).
There are a few ways of fixing this:
- If using CLI explicitly pass in models flag using `--models`
OR
a) Running `rails g annotate:install` will overwrite your defaults with the annotating `models` option set to `'true'`.
b) In `lib/tasks/auto_annotate_models.rake` add the `models` key-value option:
```ruby
Annotate.set_defaults(
...
'models' => 'true',
...
```
## Install
Into Gemfile from rubygems.org:
```ruby
group :development do
gem 'annotate'
end
```
Into Gemfile from Github:
```ruby
group :development do
gem 'annotate', git: 'https://github.com/ctran/annotate_models.git'
end
```
Into environment gems from rubygems.org:
gem install annotate
Into environment gems from Github checkout:
git clone https://github.com/ctran/annotate_models.git annotate_models
cd annotate_models
rake gem
gem install dist/annotate-*.gem
## Usage
(If you used the Gemfile install, prefix the below commands with `bundle exec`.)
### Usage in Rails
To annotate all your models, tests, fixtures, and factories:
cd /path/to/app
annotate
To annotate just your models, tests, and factories:
annotate --models --exclude fixtures
To annotate just your models:
annotate --models
To annotate routes.rb:
annotate --routes
To remove model/test/fixture/factory/serializer annotations:
annotate --delete
To remove routes.rb annotations:
annotate --routes --delete
To automatically annotate every time you run `db:migrate`,
either run `rails g annotate:install`
or add `Annotate.load_tasks` to your `Rakefile`.
See the [configuration in Rails](#configuration-in-rails) section for more info.
### Usage Outside of Rails
Everything above applies, except that `--routes` is not meaningful,
and you will probably need to explicitly set one or more `--require` option(s), and/or one or more `--model-dir` options
to inform `annotate` about the structure of your project and help it bootstrap and load the relevant code.
## Configuration
If you want to always skip annotations on a particular model, add this string
anywhere in the file:
# -*- SkipSchemaAnnotations
### Configuration in Rails
To generate a configuration file (in the form of a `.rake` file), to set
default options:
rails g annotate:install
Edit this file to control things like output format, where annotations are
added (top or bottom of file), and in which artifacts.
The generated rakefile `lib/tasks/auto_annotate_models.rake` also contains
`Annotate.load_tasks`. This adds a few rake tasks which duplicate command-line
functionality:
rake annotate_models # Add schema information (as comments) to model and fixture files
rake annotate_routes # Adds the route map to routes.rb
rake remove_annotation # Remove schema information from model and fixture files
By default, once you've generated a configuration file, annotate will be
executed whenever you run `rake db:migrate` (but only in development mode).
If you want to disable this behavior permanently,
edit the `.rake` file and change:
```ruby
'skip_on_db_migrate' => 'false',
```
To:
```ruby
'skip_on_db_migrate' => 'true',
```
If you want to run `rake db:migrate` as a one-off without running annotate,
you can do so with a simple environment variable, instead of editing the
`.rake` file:
ANNOTATE_SKIP_ON_DB_MIGRATE=1 rake db:migrate
## Options
Usage: annotate [options] [model_file]*
--additional-file-patterns Additional file paths or globs to annotate, separated by commas (e.g. `/foo/bar/%model_name%/*.rb,/baz/%model_name%.rb`)
-d, --delete Remove annotations from all model files or the routes.rb file
-p [before|top|after|bottom], Place the annotations at the top (before) or the bottom (after) of the model/test/fixture/factory/route/serializer file(s)
--position
--pc, --position-in-class [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of the model file
--pf, --position-in-factory [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of any factory files
--px, --position-in-fixture [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of any fixture files
--pt, --position-in-test [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of any test files
--pr, --position-in-routes [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of the routes.rb file
--ps, --position-in-serializer [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of the serializer files
--w, --wrapper STR Wrap annotation with the text passed as parameter.
If --w option is used, the same text will be used as opening and closing
--wo, --wrapper-open STR Annotation wrapper opening.
--wc, --wrapper-close STR Annotation wrapper closing
-r, --routes Annotate routes.rb with the output of 'rake routes'
--models Annotate ActiveRecord models
-a, --active-admin Annotate active_admin models
-v, --version Show the current version of this gem
-m, --show-migration Include the migration version number in the annotation
-k, --show-foreign-keys List the table's foreign key constraints in the annotation
--ck, --complete-foreign-keys
Complete foreign key names in the annotation
-i, --show-indexes List the table's database indexes in the annotation
-s, --simple-indexes Concat the column's related indexes in the annotation
--model-dir dir Annotate model files stored in dir rather than app/models, separate multiple dirs with commas
--root-dir dir Annotate files stored within root dir projects, separate multiple dirs with commas
--ignore-model-subdirects Ignore subdirectories of the models directory
--sort Sort columns alphabetically, rather than in creation order
--classified-sort Sort columns alphabetically, but first goes id, then the rest columns, then the timestamp columns and then the association columns
-R, --require path Additional file to require before loading models, may be used multiple times
-e [tests,fixtures,factories,serializers],
--exclude Do not annotate fixtures, test files, factories, and/or serializers
-f [bare|rdoc|yard|markdown], Render Schema Infomation as plain/RDoc/YARD/Markdown
--format
--force Force new annotations even if there are no changes.
--frozen Do not allow to change annotations. Exits non-zero if there are going to be changes to files.
--timestamp Include timestamp in (routes) annotation
--trace If unable to annotate a file, print the full stack trace, not just the exception message.
-I, --ignore-columns REGEX don't annotate columns that match a given REGEX (e.g. `annotate -I '^(id|updated_at|created_at)'`)
--ignore-routes REGEX don't annotate routes that match a given REGEX (e.g. `annotate -I '(mobile|resque|pghero)'`)_
--hide-limit-column-types VALUES
don't show limit for given column types, separated by commas (e.g. `integer,boolean,text`)
--hide-default-column-types VALUES
don't show default for given column types, separated by commas (e.g. `json,jsonb,hstore`)
--ignore-unknown-models don't display warnings for bad model files
--with-comment include database comments in model annotations
### Option: `additional_file_patterns`
CLI: `--additional-file-patterns`<br>
Ruby: `:additional_file_patterns`
Provide additional paths for the gem to annotate. These paths can include
globs. It is recommended to use absolute paths. Here are some examples:
* `/app/lib/decorates/%MODEL_NAME%/*.rb`
* `/app/lib/forms/%PLURALIZED_MODEL_NAME%/**/*.rb`
* `/app/lib/forms/%TABLE_NAME%/*.rb`
The appropriate model will be inferred using the `%*%` syntax, annotating any
matching files. It works with existing filename resolutions (options for which
can be found in the `resolve_filename` method of `annotate_models.rb`).
When using in a Rails config, you can use the following:
`File.join(Rails.application.root,
'app/lib/forms/%PLURALIZED_MODEL_NAME%/***/**.rb')`
## Sorting
By default, columns will be sorted in database order (i.e. the order in which
migrations were run).
If you prefer to sort alphabetically so that the results of annotation are
consistent regardless of what order migrations are executed in, use `--sort`.
## Markdown
The format produced is actually MultiMarkdown, making use of the syntax
extension for tables. It's recommended you use `kramdown` as your parser if
you want to use this format. If you're using `yard` to generate
documentation, specify a format of markdown with `kramdown` as the provider by
adding this to your `.yardopts` file:
--markup markdown
--markup-provider kramdown
Be sure to add this to your `Gemfile` as well:
gem 'kramdown', groups => [:development], require => false
## WARNING
**Don't add text after an automatically-created comment block.** This tool
will blow away the initial/final comment block in your models if it looks like
it was previously added by this gem.
Be sure to check the changes that this tool makes! If you are using Git, you
may simply check your project's status after running `annotate`:
$ git status
If you are not using a VCS (like Git, Subversion or similar), please tread
extra carefully, and consider using one.
## Links
* Factory Bot: http://github.com/thoughtbot/factory_bot
* Object Daddy: http://github.com/flogic/object_daddy
* Machinist: http://github.com/notahat/machinist
* Fabrication: http://github.com/paulelliott/fabrication
* SpatialAdapter: http://github.com/pdeffendol/spatial_adapter
* PostgisAdapter: http://github.com/nofxx/postgis_adapter
* PostGISAdapter: https://github.com/dazuma/activerecord-postgis-adapter
## License
Released under the same license as Ruby. No Support. No Warranty.
## Authors
[See AUTHORS.md](AUTHORS.md).
== Annotate (aka AnnotateModels)
{<img src="https://badge.fury.io/rb/annotate.svg" alt="Gem Version" />}[http://badge.fury.io/rb/annotate]
{<img src="https://img.shields.io/gem/dt/annotate.svg?style=flat" />}[https://rubygems.org/gems/annotate]
{<img src="https://travis-ci.org/ctran/annotate_models.svg?branch=develop" />}[https://travis-ci.org/ctran/annotate_models]
{<img src="https://coveralls.io/repos/ctran/annotate_models/badge.svg?branch=develop" />}[https://coveralls.io/r/ctran/annotate_models?branch=develop]
{<img src="https://codeclimate.com/github/ctran/annotate_models/badges/gpa.svg" />}[https://codeclimate.com/github/ctran/annotate_models]
{<img src="http://inch-ci.org/github/ctran/annotate_models.svg?branch=develop" alt="Inline docs" />}[http://inch-ci.org/github/ctran/annotate_models]
{<img src="https://gemnasium.com/ctran/annotate_models.png" />}[https://gemnasium.com/ctran/annotate_models]
Add a comment summarizing the current schema to the top or bottom of each of
your...
- ActiveRecord models
- Fixture files
- Tests and Specs
- Object Daddy exemplars
- Machinist blueprints
- Fabrication fabricators
- Thoughtbot's factory_bot factories, i.e. the (spec|test)/factories/<model>_factory.rb files
- routes.rb file (for Rails projects)
The schema comment looks like this:
# == Schema Info
#
# Table name: line_items
#
# id :integer(11) not null, primary key
# quantity :integer(11) not null
# product_id :integer(11) not null
# unit_price :float
# order_id :integer(11)
#
class LineItem < ActiveRecord::Base
belongs_to :product
. . .
It also annotates geometrical columns, geom type and srid, when using
+SpatialAdapter+, +PostgisAdapter+ or +PostGISAdapter+:
# == Schema Info
#
# Table name: trips
#
# local :geometry point, 4326
# path :geometry line_string, 4326
Also, if you pass the -r option, it'll annotate routes.rb with the output of
<code>rake routes</code>.
== Install
Into Gemfile from rubygems.org:
group :development do
gem 'annotate'
end
Into Gemfile from Github:
group :development do
gem 'annotate', git: 'https://github.com/ctran/annotate_models.git'
end
Into environment gems from rubygems.org:
gem install annotate
Into environment gems from Github checkout:
git clone https://github.com/ctran/annotate_models.git annotate_models
cd annotate_models
rake build
gem install pkg/annotate-*.gem
== Usage
(If you used the Gemfile install, prefix the below commands with <code>bundle exec</code>.)
=== Usage in Rails
To annotate all your models, tests, fixtures, and factories:
cd /path/to/app
annotate
To annotate just your models, tests, and factories:
annotate --exclude fixtures
To annotate just your models:
annotate --exclude tests,fixtures,factories,serializers
To annotate routes.rb:
annotate --routes
To remove model/test/fixture/factory/serializer annotations:
annotate --delete
To remove routes.rb annotations:
annotate --routes --delete
To automatically annotate every time you run <code>db:migrate</code>, either run <code>rails g annotate:install</code> or add +Annotate.load_tasks+ to your `Rakefile`. See the {configuration in Rails}[link:README.rdoc#configuration-in-rails] section for more info.
=== Usage Outside of Rails
Everything above applies, except that +--routes+ is not meaningful, and you will
probably need to explicitly set one or more +--require+ option(s), and/or one
or more +--model-dir+ options to inform annotate about the structure of your
project and help it bootstrap and load the relevant code.
== Configuration
If you want to always skip annotations on a particular model, add this string
anywhere in the file:
# -*- SkipSchemaAnnotations
=== Configuration in Rails
To generate a configuration file (in the form of a +.rake+ file), to set
default options:
rails g annotate:install
Edit this file to control things like output format, where annotations are
added (top or bottom of file), and in which artifacts.
The generated rakefile +lib/tasks/auto_annotate_models.rake+ also contains
`Annotate.load_tasks`. This adds a few rake tasks which duplicate command-line
functionality:
rake annotate_models # Add schema information (as comments) to model and fixture files
rake annotate_routes # Adds the route map to routes.rb
rake remove_annotation # Remove schema information from model and fixture files
By default, once you've generated a configuration file, annotate will be
executed whenever you run <code>rake db:migrate</code> (but only in development mode).
If you want to disable this behavior permanently, edit the +.rake+ file and
change:
'skip_on_db_migrate' => 'false',
To:
'skip_on_db_migrate' => 'true',
If you want to run <code>rake db:migrate</code> as a one-off without running annotate,
you can do so with a simple environment variable, instead of editing the
+.rake+ file:
ANNOTATE_SKIP_ON_DB_MIGRATE=1 rake db:migrate
== Options
Usage: annotate [options] [model_file]*
-d, --delete Remove annotations from all model files or the routes.rb file
-p [before|top|after|bottom], Place the annotations at the top (before) or the bottom (after) of the model/test/fixture/factory/route/serializer file(s)
--position
--pc, --position-in-class [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of the model file
--pf, --position-in-factory [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of any factory files
--px, --position-in-fixture [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of any fixture files
--pt, --position-in-test [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of any test files
--pr, --position-in-routes [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of the routes.rb file
--ps, --position-in-serializer [before|top|after|bottom]
Place the annotations at the top (before) or the bottom (after) of the serializer files
--w, --wrapper STR Wrap annotation with the text passed as parameter.
If --w option is used, the same text will be used as opening and closing
--wo, --wrapper-open STR Annotation wrapper opening.
--wc, --wrapper-close STR Annotation wrapper closing
-r, --routes Annotate routes.rb with the output of 'rake routes'
-a, --active-admin Annotate active_admin models
-v, --version Show the current version of this gem
-m, --show-migration Include the migration version number in the annotation
-k, --show-foreign-keys List the table's foreign key constraints in the annotation
--ck, --complete-foreign-keys
Complete foreign key names in the annotation
-i, --show-indexes List the table's database indexes in the annotation
-s, --simple-indexes Concat the column's related indexes in the annotation
--model-dir dir Annotate model files stored in dir rather than app/models, separate multiple dirs with commas
--root-dir dir Annotate files stored within root dir projects, separate multiple dirs with commas
--ignore-model-subdirects Ignore subdirectories of the models directory
--sort Sort columns alphabetically, rather than in creation order
--classified-sort Sort columns alphabetically, but first goes id, then the rest columns, then the timestamp columns and then the association columns
-R, --require path Additional file to require before loading models, may be used multiple times
-e [tests,fixtures,factories,serializers],
--exclude Do not annotate fixtures, test files, factories, and/or serializers
-f [bare|rdoc|markdown], Render Schema Infomation as plain/RDoc/Markdown
--format
--force Force new annotations even if there are no changes.
--frozen Do not allow to change annotations. Exits non-zero if there are going to be changes to files.
--timestamp Include timestamp in (routes) annotation
--trace If unable to annotate a file, print the full stack trace, not just the exception message.
-I, --ignore-columns REGEX don't annotate columns that match a given REGEX (i.e., `annotate -I '^(id|updated_at|created_at)'`
--ignore-routes REGEX don't annotate routes that match a given REGEX (i.e., `annotate -I '(mobile|resque|pghero)'`
--hide-limit-column-types VALUES
don't show limit for given column types, separated by commas (i.e., `integer,boolean,text`)
--hide-default-column-types VALUES
don't show default for given column types, separated by commas (i.e., `json,jsonb,hstore`)
--ignore-unknown-models don't display warnings for bad model files
--with-comment include database comments in model annotations
== Sorting
By default, columns will be sorted in database order (i.e. the order in which
migrations were run).
If you prefer to sort alphabetically so that the results of
annotation are consistent regardless of what order migrations are executed in,
use +--sort+.
== Markdown
The format produced is actually MultiMarkdown, making use of the syntax
extension for tables. It's recommended you use +kramdown+ as your parser if
you want to use this format. If you're using +yard+ to generate documentation,
specify a format of markdown with +kramdown+ as the provider by adding this to
your +.yardopts+ file:
--markup markdown
--markup-provider kramdown
Be sure to add this to your +Gemfile+ as well:
gem 'kramdown', :groups => [:development], :require => false
== WARNING
<b>Don't add text after an automatically-created comment block.</b> This tool
will blow away the initial/final comment block in your models if it looks like
it was previously added by this gem.
Be sure to check the changes that this tool makes! If you are using Git,
you may simply check your project's status after running +annotate+:
$ git status
If you are not using a VCS (like Git, Subversion or similar), please tread
extra carefully, and consider using one.
== Links
- Factory Bot: http://github.com/thoughtbot/factory_bot
- Object Daddy: http://github.com/flogic/object_daddy
- Machinist: http://github.com/notahat/machinist
- Fabrication: http://github.com/paulelliott/fabrication
- SpatialAdapter: http://github.com/pdeffendol/spatial_adapter
- PostgisAdapter: http://github.com/nofxx/postgis_adapter
- PostGISAdapter: https://github.com/dazuma/activerecord-postgis-adapter
== License
Released under the same license as Ruby. No Support. No Warranty.
== Authors
{See AUTHORS.rdoc}[link:AUTHORS.rdoc].
## Prerequisite
- Install "git-flow" (`brew install git-flow`)
- Install "bump" gem (`gem install bump`)
## Perform a release
- `git flow release start <release>`
- Update the `CHANGELOG.md` file
- `bump current`
- `bump patch`
- `rm -rf dist`
- `rake spec`
- `rake gem`
- `git flow release finish <release>`
- `rake gem:publish`
== Prerequisite
- Install "git-flow" (brew install git-flow)
- Install "bump" gem (gem install bump)
== Perform a release
- git flow release start <release>
- Update the CHANGELOG.rdoc file
- bump current
- bump patch
- rm -rf dist
- rake spec
- rake gem
- git flow release finish <release>
- rake gem:publish
......@@ -3,7 +3,7 @@ def exit_exception(e)
exit e.status_code
end
# Note : this causes annoying psych warnings under Ruby 1.9.2-p180; to fix, upgrade to 1.9.3
# NOTE: this causes annoying psych warnings under Ruby 1.9.2-p180; to fix, upgrade to 1.9.3
begin
require 'bundler'
Bundler.setup(:default, :development)
......@@ -60,7 +60,7 @@ namespace :gem do
end
gem.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
gem.extra_rdoc_files = ['README.rdoc', 'CHANGELOG.rdoc', 'TODO.rdoc']
gem.extra_rdoc_files = ['README.md', 'CHANGELOG.md', 'TODO.md']
gem.files = `git ls-files -- .`.split("\n").reject do |fn|
fn =~ /^Gemfile.*/ ||
......@@ -162,7 +162,7 @@ namespace :integration do
fixtures[Digest::MD5.hexdigest(File.read(fname))] = File.expand_path(fname)
end
candidates.keys.each do |digest|
candidates.each_key do |digest|
next unless fixtures.key?(digest)
candidates[digest].each do |fname|
# Double-check contents in case of hash collision...
......
== TODO
- clean up history
- change default position back to "top" for all annotations
- change 'exclude' to 'only' (double negatives are not unconfusing)
== TODO (proposed)
- push two identical gems, named 'annotate' and 'annotate_models'
- supply two binaries, named 'annotate' and 'annotate_models', since there's already a unix tool named 'annotate'
- test EVERYTHING
......@@ -7,42 +7,26 @@ Gem::Specification.new do |s|
s.name = 'annotate'
s.version = Annotate.version
s.required_ruby_version = '>= 2.2.0'
s.required_ruby_version = '>= 2.4.0'
s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version=
s.authors = ['Alex Chaffee', 'Cuong Tran', 'Marcos Piccinini', 'Turadg Aleahmad', 'Jon Frisby']
s.description = 'Annotates Rails/ActiveRecord Models, routes, fixtures, and others based on the database schema.'
s.email = ['alex@stinky.com', 'cuong.tran@gmail.com', 'x@nofxx.com', 'turadg@aleahmad.net', 'jon@cloudability.com']
s.executables = ['annotate']
s.extra_rdoc_files = ['README.rdoc', 'CHANGELOG.rdoc', 'TODO.rdoc']
s.files = [
'AUTHORS.rdoc',
'CHANGELOG.rdoc',
'LICENSE.txt',
'README.rdoc',
'TODO.rdoc',
'annotate.gemspec',
'bin/annotate',
'lib/annotate.rb',
'lib/annotate/active_record_patch.rb',
'lib/annotate/annotate_models.rb',
'lib/annotate/annotate_routes.rb',
'lib/annotate/tasks.rb',
'lib/annotate/version.rb',
'lib/generators/annotate/USAGE',
'lib/generators/annotate/install_generator.rb',
'lib/generators/annotate/templates/auto_annotate_models.rake',
'lib/tasks/annotate_models.rake',
'lib/tasks/annotate_routes.rake',
'lib/tasks/annotate_models_migrate.rake'
]
s.homepage = 'http://github.com/ctran/annotate_models'
s.extra_rdoc_files = ['README.md', 'CHANGELOG.md']
s.files = `git ls-files -z LICENSE.txt *.md *.gemspec bin lib`.split("\x0")
s.homepage = 'https://github.com/ctran/annotate_models'
s.licenses = ['Ruby']
s.require_paths = ['lib']
s.rubyforge_project = 'annotate'
s.rubygems_version = '2.1.11'
s.summary = 'Annotates Rails Models, routes, fixtures, and others based on the database schema.'
s.specification_version = 4 if s.respond_to? :specification_version
s.add_runtime_dependency(%q<rake>, ['>= 10.4', '< 13.0'])
s.add_runtime_dependency(%q<activerecord>, ['>= 3.2', '< 7.0'])
s.add_runtime_dependency(%q<rake>, '>= 10.4', '< 14.0')
s.add_runtime_dependency(%q<activerecord>, ['>= 3.2', '< 8.0'])
s.metadata = {
"bug_tracker_uri" => "https://github.com/ctran/annotate_models/issues/",
"source_code_uri" => "https://github.com/ctran/annotate_models.git"
}
end
......@@ -14,203 +14,19 @@ end
here = File.expand_path(File.dirname __FILE__)
$LOAD_PATH << "#{here}/../lib"
require 'optparse'
require 'annotate'
Annotate.bootstrap_rake
has_set_position = {}
target_action = :do_annotations
positions = %w(before top after bottom)
OptionParser.new do |opts|
opts.banner = 'Usage: annotate [options] [model_file]*'
opts.on('-d', '--delete', 'Remove annotations from all model files or the routes.rb file') do
target_action = :remove_annotations
end
opts.on('-p', '--position [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of the model/test/fixture/factory/route/serializer file(s)') do |p|
ENV['position'] = p
%w(position_in_class position_in_factory position_in_fixture position_in_test position_in_routes position_in_serializer).each do |key|
ENV[key] = p unless has_set_position[key]
end
end
opts.on('--pc', '--position-in-class [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of the model file') do |p|
ENV['position_in_class'] = p
has_set_position['position_in_class'] = true
end
opts.on('--pf', '--position-in-factory [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of any factory files') do |p|
ENV['position_in_factory'] = p
has_set_position['position_in_factory'] = true
end
opts.on('--px', '--position-in-fixture [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of any fixture files') do |p|
ENV['position_in_fixture'] = p
has_set_position['position_in_fixture'] = true
end
opts.on('--pt', '--position-in-test [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of any test files') do |p|
ENV['position_in_test'] = p
has_set_position['position_in_test'] = true
end
opts.on('--pr', '--position-in-routes [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of the routes.rb file') do |p|
ENV['position_in_routes'] = p
has_set_position['position_in_routes'] = true
end
opts.on('--ps', '--position-in-serializer [before|top|after|bottom]', positions,
'Place the annotations at the top (before) or the bottom (after) of the serializer files') do |p|
ENV['position_in_serializer'] = p
has_set_position['position_in_serializer'] = true
end
opts.on('--w', '--wrapper STR', 'Wrap annotation with the text passed as parameter.',
'If --w option is used, the same text will be used as opening and closing') do |p|
ENV['wrapper'] = p
end
opts.on('--wo', '--wrapper-open STR', 'Annotation wrapper opening.') do |p|
ENV['wrapper_open'] = p
end
opts.on('--wc', '--wrapper-close STR', 'Annotation wrapper closing') do |p|
ENV['wrapper_close'] = p
end
opts.on('-r', '--routes', "Annotate routes.rb with the output of 'rake routes'") do
ENV['routes'] = 'true'
end
opts.on('-a', '--active-admin', 'Annotate active_admin models') do
ENV['active_admin'] = 'true'
end
opts.on('-v', '--version', 'Show the current version of this gem') do
puts "annotate v#{Annotate.version}"; exit
end
opts.on('-m', '--show-migration', 'Include the migration version number in the annotation') do
ENV['include_version'] = 'yes'
end
opts.on('-k', '--show-foreign-keys',
"List the table's foreign key constraints in the annotation") do
ENV['show_foreign_keys'] = 'yes'
end
require 'annotate/parser'
opts.on('--ck',
'--complete-foreign-keys', 'Complete foreign key names in the annotation') do
ENV['show_foreign_keys'] = 'yes'
ENV['show_complete_foreign_keys'] = 'yes'
end
opts.on('-i', '--show-indexes',
"List the table's database indexes in the annotation") do
ENV['show_indexes'] = 'yes'
end
opts.on('-s', '--simple-indexes',
"Concat the column's related indexes in the annotation") do
ENV['simple_indexes'] = 'yes'
end
opts.on('--model-dir dir',
"Annotate model files stored in dir rather than app/models, separate multiple dirs with commas") do |dir|
ENV['model_dir'] = dir
end
opts.on('--root-dir dir',
"Annotate files stored within root dir projects, separate multiple dirs with commas") do |dir|
ENV['root_dir'] = dir
end
opts.on('--ignore-model-subdirects',
"Ignore subdirectories of the models directory") do |dir|
ENV['ignore_model_sub_dir'] = 'yes'
end
opts.on('--sort',
"Sort columns alphabetically, rather than in creation order") do |dir|
ENV['sort'] = 'yes'
end
opts.on('--classified-sort',
"Sort columns alphabetically, but first goes id, then the rest columns, then the timestamp columns and then the association columns") do |dir|
ENV['classified_sort'] = 'yes'
end
opts.on('-R', '--require path',
"Additional file to require before loading models, may be used multiple times") do |path|
if !ENV['require'].blank?
ENV['require'] = ENV['require'] + ",#{path}"
else
ENV['require'] = path
end
end
opts.on('-e', '--exclude [tests,fixtures,factories,serializers]', Array, "Do not annotate fixtures, test files, factories, and/or serializers") do |exclusions|
exclusions ||= %w(tests fixtures factories)
exclusions.each { |exclusion| ENV["exclude_#{exclusion}"] = 'yes' }
end
opts.on('-f', '--format [bare|rdoc|markdown]', %w(bare rdoc markdown), 'Render Schema Infomation as plain/RDoc/Markdown') do |fmt|
ENV["format_#{fmt}"] = 'yes'
end
opts.on('--force', 'Force new annotations even if there are no changes.') do |force|
ENV['force'] = 'yes'
end
opts.on('--frozen', 'Do not allow to change annotations. Exits non-zero if there are going to be changes to files.') do
ENV['frozen'] = 'yes'
end
opts.on('--timestamp', 'Include timestamp in (routes) annotation') do
ENV['timestamp'] = 'true'
end
opts.on('--trace', 'If unable to annotate a file, print the full stack trace, not just the exception message.') do |value|
ENV['trace'] = 'yes'
end
opts.on('-I', '--ignore-columns REGEX', "don't annotate columns that match a given REGEX (i.e., `annotate -I '^(id|updated_at|created_at)'`") do |regex|
ENV['ignore_columns'] = regex
end
opts.on('--ignore-routes REGEX', "don't annotate routes that match a given REGEX (i.e., `annotate -I '(mobile|resque|pghero)'`") do |regex|
ENV['ignore_routes'] = regex
end
opts.on('--hide-limit-column-types VALUES', "don't show limit for given column types, separated by commas (i.e., `integer,boolean,text`)") do |values|
ENV['hide_limit_column_types'] = "#{values}"
end
opts.on('--hide-default-column-types VALUES', "don't show default for given column types, separated by commas (i.e., `json,jsonb,hstore`)") do |values|
ENV['hide_default_column_types'] = "#{values}"
end
Annotate.bootstrap_rake
opts.on('--ignore-unknown-models', "don't display warnings for bad model files") do |values|
ENV['ignore_unknown_models'] = 'true'
end
options_result = Annotate::Parser.parse(ARGV)
opts.on('--with-comment', "include database comments in model annotations") do |values|
ENV['with_comment'] = 'true'
end
end.parse!
exit if options_result[:exit]
options = Annotate.setup_options(
is_rake: ENV['is_rake'] && !ENV['is_rake'].empty?
)
Annotate.eager_load(options) if Annotate.include_models?
Annotate.eager_load(options) if Annotate::Helpers.include_models?
AnnotateModels.send(target_action, options) if Annotate.include_models?
AnnotateRoutes.send(target_action, options) if Annotate.include_routes?
AnnotateModels.send(options_result[:target_action], options) if Annotate::Helpers.include_models?
AnnotateRoutes.send(options_result[:target_action], options) if Annotate::Helpers.include_routes?
machine:
ruby:
version: 2.2.6
test:
override:
- bundle exec rubocop && bundle exec rspec
# rubocop:disable Metrics/ModuleLength
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'annotate/version'
require 'annotate/annotate_models'
require 'annotate/annotate_routes'
require 'annotate/constants'
require 'annotate/helpers'
begin
# ActiveSupport 3.x...
......@@ -16,38 +16,6 @@ rescue StandardError
end
module Annotate
TRUE_RE = /^(true|t|yes|y|1)$/i
##
# The set of available options to customize the behavior of Annotate.
#
POSITION_OPTIONS = [
:position_in_routes, :position_in_class, :position_in_test,
:position_in_fixture, :position_in_factory, :position,
:position_in_serializer
].freeze
FLAG_OPTIONS = [
:show_indexes, :simple_indexes, :include_version, :exclude_tests,
:exclude_fixtures, :exclude_factories, :ignore_model_sub_dir,
:format_bare, :format_rdoc, :format_markdown, :sort, :force, :frozen,
:trace, :timestamp, :exclude_serializers, :classified_sort,
:show_foreign_keys, :show_complete_foreign_keys,
:exclude_scaffolds, :exclude_controllers, :exclude_helpers,
:exclude_sti_subclasses, :ignore_unknown_models, :with_comment
].freeze
OTHER_OPTIONS = [
:ignore_columns, :skip_on_db_migrate, :wrapper_open, :wrapper_close,
:wrapper, :routes, :hide_limit_column_types, :hide_default_column_types,
:ignore_routes, :active_admin
].freeze
PATH_OPTIONS = [
:require, :model_dir, :root_dir
].freeze
def self.all_options
[POSITION_OPTIONS, FLAG_OPTIONS, PATH_OPTIONS, OTHER_OPTIONS]
end
##
# Set default values that can be overridden via environment variables.
#
......@@ -55,9 +23,9 @@ module Annotate
return if @has_set_defaults
@has_set_defaults = true
options = HashWithIndifferentAccess.new(options)
options = ActiveSupport::HashWithIndifferentAccess.new(options)
all_options.flatten.each do |key|
Constants::ALL_ANNOTATE_OPTIONS.flatten.each do |key|
if options.key?(key)
default_value = if options[key].is_a?(Array)
options[key].join(',')
......@@ -75,68 +43,42 @@ module Annotate
# TODO: what is the difference between this and set_defaults?
#
def self.setup_options(options = {})
POSITION_OPTIONS.each do |key|
options[key] = fallback(ENV[key.to_s], ENV['position'], 'before')
Constants::POSITION_OPTIONS.each do |key|
options[key] = Annotate::Helpers.fallback(ENV[key.to_s], ENV['position'], 'before')
end
FLAG_OPTIONS.each do |key|
options[key] = true?(ENV[key.to_s])
Constants::FLAG_OPTIONS.each do |key|
options[key] = Annotate::Helpers.true?(ENV[key.to_s])
end
OTHER_OPTIONS.each do |key|
Constants::OTHER_OPTIONS.each do |key|
options[key] = !ENV[key.to_s].blank? ? ENV[key.to_s] : nil
end
PATH_OPTIONS.each do |key|
Constants::PATH_OPTIONS.each do |key|
options[key] = !ENV[key.to_s].blank? ? ENV[key.to_s].split(',') : []
end
options[:additional_file_patterns] ||= []
options[:additional_file_patterns] = options[:additional_file_patterns].split(',') if options[:additional_file_patterns].is_a?(String)
options[:model_dir] = ['app/models'] if options[:model_dir].empty?
options[:wrapper_open] ||= options[:wrapper]
options[:wrapper_close] ||= options[:wrapper]
# These were added in 2.7.0 but so this is to revert to old behavior by default
options[:exclude_scaffolds] = Annotate.true?(ENV.fetch('exclude_scaffolds', 'true'))
options[:exclude_controllers] = Annotate.true?(ENV.fetch('exclude_controllers', 'true'))
options[:exclude_helpers] = Annotate.true?(ENV.fetch('exclude_helpers', 'true'))
options[:exclude_scaffolds] = Annotate::Helpers.true?(ENV.fetch('exclude_scaffolds', 'true'))
options[:exclude_controllers] = Annotate::Helpers.true?(ENV.fetch('exclude_controllers', 'true'))
options[:exclude_helpers] = Annotate::Helpers.true?(ENV.fetch('exclude_helpers', 'true'))
options
end
def self.reset_options
all_options.flatten.each { |key| ENV[key.to_s] = nil }
end
def self.skip_on_migration?
ENV['ANNOTATE_SKIP_ON_DB_MIGRATE'] =~ TRUE_RE || ENV['skip_on_db_migrate'] =~ TRUE_RE
end
def self.include_routes?
ENV['routes'] =~ TRUE_RE
end
def self.include_models?
ENV['routes'] !~ TRUE_RE
end
def self.loaded_tasks=(val)
@loaded_tasks = val
end
def self.loaded_tasks
@loaded_tasks
end
def self.load_tasks
return if loaded_tasks
self.loaded_tasks = true
return if @tasks_loaded
Dir[File.join(File.dirname(__FILE__), 'tasks', '**/*.rake')].each do |rake|
load rake
end
end
def self.load_requires(options)
options[:require].count > 0 &&
options[:require].each { |path| require path }
@tasks_loaded = true
end
def self.eager_load(options)
......@@ -192,13 +134,12 @@ module Annotate
Rake::Task[:set_annotation_options].invoke
end
def self.fallback(*args)
args.detect { |arg| !arg.blank? }
end
class << self
private
def self.true?(val)
return false if val.blank?
return false unless val =~ TRUE_RE
true
def load_requires(options)
options[:require].count > 0 &&
options[:require].each { |path| require path }
end
end
end
......@@ -2,9 +2,10 @@
require 'bigdecimal'
module AnnotateModels
TRUE_RE = /^(true|t|yes|y|1)$/i
require 'annotate/constants'
require_relative 'annotate_models/file_patterns'
module AnnotateModels
# Annotate Models plugin use this header
COMPAT_PREFIX = '== Schema Info'.freeze
COMPAT_PREFIX_MD = '## Schema Info'.freeze
......@@ -16,50 +17,6 @@ module AnnotateModels
MATCHED_TYPES = %w(test fixture factory serializer scaffold controller helper).freeze
# File.join for windows reverse bar compat?
# I dont use windows, can`t test
UNIT_TEST_DIR = File.join('test', "unit")
MODEL_TEST_DIR = File.join('test', "models") # since rails 4.0
SPEC_MODEL_DIR = File.join('spec', "models")
FIXTURE_TEST_DIR = File.join('test', "fixtures")
FIXTURE_SPEC_DIR = File.join('spec', "fixtures")
# Other test files
CONTROLLER_TEST_DIR = File.join('test', "controllers")
CONTROLLER_SPEC_DIR = File.join('spec', "controllers")
REQUEST_SPEC_DIR = File.join('spec', "requests")
ROUTING_SPEC_DIR = File.join('spec', "routing")
# Object Daddy http://github.com/flogic/object_daddy/tree/master
EXEMPLARS_TEST_DIR = File.join('test', "exemplars")
EXEMPLARS_SPEC_DIR = File.join('spec', "exemplars")
# Machinist http://github.com/notahat/machinist
BLUEPRINTS_TEST_DIR = File.join('test', "blueprints")
BLUEPRINTS_SPEC_DIR = File.join('spec', "blueprints")
# Factory Girl http://github.com/thoughtbot/factory_girl
FACTORY_GIRL_TEST_DIR = File.join('test', "factories")
FACTORY_GIRL_SPEC_DIR = File.join('spec', "factories")
# Fabrication https://github.com/paulelliott/fabrication.git
FABRICATORS_TEST_DIR = File.join('test', "fabricators")
FABRICATORS_SPEC_DIR = File.join('spec', "fabricators")
# Serializers https://github.com/rails-api/active_model_serializers
SERIALIZERS_DIR = File.join('app', "serializers")
SERIALIZERS_TEST_DIR = File.join('test', "serializers")
SERIALIZERS_SPEC_DIR = File.join('spec', "serializers")
# Controller files
CONTROLLER_DIR = File.join('app', "controllers")
# Active admin registry files
ACTIVEADMIN_DIR = File.join('app', "admin")
# Helper files
HELPER_DIR = File.join('app', "helpers")
# Don't show limit (#) on these column types
# Example: show "integer" instead of "integer(4)"
NO_LIMIT_COL_TYPES = %w(integer bigint boolean).freeze
......@@ -82,6 +39,8 @@ module AnnotateModels
}
}.freeze
MAGIC_COMMENT_MATCHER = Regexp.new(/(^#\s*encoding:.*(?:\n|r\n))|(^# coding:.*(?:\n|\r\n))|(^# -\*- coding:.*(?:\n|\r\n))|(^# -\*- encoding\s?:.*(?:\n|\r\n))|(^#\s*frozen_string_literal:.+(?:\n|\r\n))|(^# -\*- frozen_string_literal\s*:.+-\*-(?:\n|\r\n))/).freeze
class << self
def annotate_pattern(options = {})
if options[:wrapper_open]
......@@ -108,83 +67,33 @@ module AnnotateModels
attr_writer :root_dir
def test_files(root_directory)
[
File.join(root_directory, UNIT_TEST_DIR, "%MODEL_NAME%_test.rb"),
File.join(root_directory, MODEL_TEST_DIR, "%MODEL_NAME%_test.rb"),
File.join(root_directory, SPEC_MODEL_DIR, "%MODEL_NAME%_spec.rb")
]
end
def fixture_files(root_directory)
[
File.join(root_directory, FIXTURE_TEST_DIR, "%TABLE_NAME%.yml"),
File.join(root_directory, FIXTURE_SPEC_DIR, "%TABLE_NAME%.yml"),
File.join(root_directory, FIXTURE_TEST_DIR, "%PLURALIZED_MODEL_NAME%.yml"),
File.join(root_directory, FIXTURE_SPEC_DIR, "%PLURALIZED_MODEL_NAME%.yml")
]
end
def scaffold_files(root_directory)
[
File.join(root_directory, CONTROLLER_TEST_DIR, "%PLURALIZED_MODEL_NAME%_controller_test.rb"),
File.join(root_directory, CONTROLLER_SPEC_DIR, "%PLURALIZED_MODEL_NAME%_controller_spec.rb"),
File.join(root_directory, REQUEST_SPEC_DIR, "%PLURALIZED_MODEL_NAME%_spec.rb"),
File.join(root_directory, ROUTING_SPEC_DIR, "%PLURALIZED_MODEL_NAME%_routing_spec.rb")
]
end
def skip_subdirectory_model_load
# This option is set in options[:skip_subdirectory_model_load]
# and stops the get_loaded_model method from loading a model from a subdir
def factory_files(root_directory)
[
File.join(root_directory, EXEMPLARS_TEST_DIR, "%MODEL_NAME%_exemplar.rb"),
File.join(root_directory, EXEMPLARS_SPEC_DIR, "%MODEL_NAME%_exemplar.rb"),
File.join(root_directory, BLUEPRINTS_TEST_DIR, "%MODEL_NAME%_blueprint.rb"),
File.join(root_directory, BLUEPRINTS_SPEC_DIR, "%MODEL_NAME%_blueprint.rb"),
File.join(root_directory, FACTORY_GIRL_TEST_DIR, "%MODEL_NAME%_factory.rb"), # (old style)
File.join(root_directory, FACTORY_GIRL_SPEC_DIR, "%MODEL_NAME%_factory.rb"), # (old style)
File.join(root_directory, FACTORY_GIRL_TEST_DIR, "%TABLE_NAME%.rb"), # (new style)
File.join(root_directory, FACTORY_GIRL_SPEC_DIR, "%TABLE_NAME%.rb"), # (new style)
File.join(root_directory, FACTORY_GIRL_TEST_DIR, "%PLURALIZED_MODEL_NAME%.rb"), # (new style)
File.join(root_directory, FACTORY_GIRL_SPEC_DIR, "%PLURALIZED_MODEL_NAME%.rb"), # (new style)
File.join(root_directory, FABRICATORS_TEST_DIR, "%MODEL_NAME%_fabricator.rb"),
File.join(root_directory, FABRICATORS_SPEC_DIR, "%MODEL_NAME%_fabricator.rb")
]
end
def serialize_files(root_directory)
[
File.join(root_directory, SERIALIZERS_DIR, "%MODEL_NAME%_serializer.rb"),
File.join(root_directory, SERIALIZERS_TEST_DIR, "%MODEL_NAME%_serializer_spec.rb"),
File.join(root_directory, SERIALIZERS_SPEC_DIR, "%MODEL_NAME%_serializer_spec.rb")
]
end
def files_by_pattern(root_directory, pattern_type)
case pattern_type
when 'test' then test_files(root_directory)
when 'fixture' then fixture_files(root_directory)
when 'scaffold' then scaffold_files(root_directory)
when 'factory' then factory_files(root_directory)
when 'serializer' then serialize_files(root_directory)
when 'controller'
[File.join(root_directory, CONTROLLER_DIR, "%PLURALIZED_MODEL_NAME%_controller.rb")]
when 'admin'
[File.join(root_directory, ACTIVEADMIN_DIR, "%MODEL_NAME%.rb")]
when 'helper'
[File.join(root_directory, HELPER_DIR, "%PLURALIZED_MODEL_NAME%_helper.rb")]
if @skip_subdirectory_model_load.blank?
false
else
[]
@skip_subdirectory_model_load
end
end
def get_patterns(pattern_types = [])
attr_writer :skip_subdirectory_model_load
def get_patterns(options, pattern_types = [])
current_patterns = []
root_dir.each do |root_directory|
Array(pattern_types).each do |pattern_type|
current_patterns += files_by_pattern(root_directory, pattern_type)
patterns = FilePatterns.generate(root_directory, pattern_type, options)
current_patterns += if pattern_type.to_sym == :additional_file_patterns
patterns
else
patterns.map { |p| p.sub(/^[\/]*/, '') }
end
end
end
current_patterns.map { |p| p.sub(/^[\/]*/, '') }
current_patterns
end
# Simple quoting for the default column value
......@@ -236,68 +145,24 @@ module AnnotateModels
info << "# #{ '-' * ( max_size + md_names_overhead ) } | #{'-' * md_type_allowance} | #{ '-' * 27 }\n"
end
cols = if ignore_columns = options[:ignore_columns]
klass.columns.reject do |col|
col.name.match(/#{ignore_columns}/)
end
else
klass.columns
end
cols = cols.sort_by(&:name) if options[:sort]
cols = classified_sort(cols) if options[:classified_sort]
cols = columns(klass, options)
cols.each do |col|
col_type = get_col_type(col)
attrs = []
attrs << "default(#{schema_default(klass, col)})" unless col.default.nil? || hide_default?(col_type, options)
attrs << 'unsigned' if col.respond_to?(:unsigned?) && col.unsigned?
attrs << 'not null' unless col.null
attrs << 'primary key' if klass.primary_key && (klass.primary_key.is_a?(Array) ? klass.primary_key.collect(&:to_sym).include?(col.name.to_sym) : col.name.to_sym == klass.primary_key.to_sym)
if col_type == 'decimal'
col_type << "(#{col.precision}, #{col.scale})"
elsif col_type != 'spatial'
if col.limit
if col.limit.is_a? Array
attrs << "(#{col.limit.join(', ')})"
else
col_type << "(#{col.limit})" unless hide_limit?(col_type, options)
end
end
end
# Check out if we got an array column
attrs << 'is an Array' if col.respond_to?(:array) && col.array
# Check out if we got a geometric column
# and print the type and SRID
if col.respond_to?(:geometry_type)
attrs << "#{col.geometry_type}, #{col.srid}"
elsif col.respond_to?(:geometric_type) && col.geometric_type.present?
attrs << "#{col.geometric_type.to_s.downcase}, #{col.srid}"
end
# Check if the column has indices and print "indexed" if true
# If the index includes another column, print it too.
if options[:simple_indexes] && klass.table_exists?# Check out if this column is indexed
indices = retrieve_indexes_from_table(klass)
if indices = indices.select { |ind| ind.columns.include? col.name }
indices.sort_by(&:name).each do |ind|
next if ind.columns.is_a?(String)
ind = ind.columns.reject! { |i| i == col.name }
attrs << (ind.empty? ? "indexed" : "indexed => [#{ind.join(", ")}]")
end
end
end
attrs = get_attributes(col, col_type, klass, options)
col_name = if with_comments?(klass, options) && col.comment
"#{col.name}(#{col.comment})"
"#{col.name}(#{col.comment.gsub(/\n/, "\\n")})"
else
col.name
end
if options[:format_rdoc]
info << sprintf("# %-#{max_size}.#{max_size}s<tt>%s</tt>", "*#{col_name}*::", attrs.unshift(col_type).join(", ")).rstrip + "\n"
elsif options[:format_yard]
info << sprintf("# @!attribute #{col_name}") + "\n"
ruby_class = col.respond_to?(:array) && col.array ? "Array<#{map_col_type_to_ruby_classes(col_type)}>": map_col_type_to_ruby_classes(col_type)
info << sprintf("# @return [#{ruby_class}]") + "\n"
elsif options[:format_markdown]
name_remainder = max_size - col_name.length
name_remainder = max_size - col_name.length - non_ascii_length(col_name)
type_remainder = (md_type_allowance - 2) - col_type.length
info << (sprintf("# **`%s`**%#{name_remainder}s | `%s`%#{type_remainder}s | `%s`", col_name, " ", col_type, " ", attrs.join(", ").rstrip)).gsub('``', ' ').rstrip + "\n"
else
......@@ -464,7 +329,10 @@ module AnnotateModels
foreign_keys = klass.connection.foreign_keys(klass.table_name)
return '' if foreign_keys.empty?
format_name = ->(fk) { options[:show_complete_foreign_keys] ? fk.name : fk.name.gsub(/(?<=^fk_rails_)[0-9a-f]{10}$/, '...') }
format_name = lambda do |fk|
return fk.options[:column] if fk.name.blank?
options[:show_complete_foreign_keys] ? fk.name : fk.name.gsub(/(?<=^fk_rails_)[0-9a-f]{10}$/, '...')
end
max_size = foreign_keys.map(&format_name).map(&:size).max + 1
foreign_keys.sort_by {|fk| [format_name.call(fk), fk.column]}.each do |fk|
......@@ -507,7 +375,7 @@ module AnnotateModels
old_header = old_content.match(header_pattern).to_s
new_header = info_block.match(header_pattern).to_s
column_pattern = /^#[\t ]+[\w\*`]+[\t ]+.+$/
column_pattern = /^#[\t ]+[\w\*\.`]+[\t ]+.+$/
old_columns = old_header && old_header.scan(column_pattern).sort
new_columns = new_header && new_header.scan(column_pattern).sort
......@@ -526,15 +394,15 @@ module AnnotateModels
# need to insert it in correct position
if old_annotation.empty? || options[:force]
magic_comments_block = magic_comments_as_string(old_content)
old_content.gsub!(magic_comment_matcher, '')
old_content.gsub!(MAGIC_COMMENT_MATCHER, '')
old_content.sub!(annotate_pattern(options), '')
new_content = if %w(after bottom).include?(options[position].to_s)
magic_comments_block + (old_content.rstrip + "\n\n" + wrapped_info_block)
elsif magic_comments_block.empty?
magic_comments_block + wrapped_info_block + "\n" + old_content
magic_comments_block + wrapped_info_block + old_content.lstrip
else
magic_comments_block + "\n" + wrapped_info_block + "\n" + old_content
magic_comments_block + "\n" + wrapped_info_block + old_content.lstrip
end
else
# replace the old annotation with the new one
......@@ -550,12 +418,8 @@ module AnnotateModels
true
end
def magic_comment_matcher
Regexp.new(/(^#\s*encoding:.*(?:\n|r\n))|(^# coding:.*(?:\n|\r\n))|(^# -\*- coding:.*(?:\n|\r\n))|(^# -\*- encoding\s?:.*(?:\n|\r\n))|(^#\s*frozen_string_literal:.+(?:\n|\r\n))|(^# -\*- frozen_string_literal\s*:.+-\*-(?:\n|\r\n))/)
end
def magic_comments_as_string(content)
magic_comments = content.scan(magic_comment_matcher).flatten.compact
magic_comments = content.scan(MAGIC_COMMENT_MATCHER).flatten.compact
if magic_comments.any?
magic_comments.join
......@@ -581,8 +445,9 @@ module AnnotateModels
end
def matched_types(options)
types = MATCHED_TYPES
types << 'admin' if options[:active_admin] =~ TRUE_RE && !types.include?('admin')
types = MATCHED_TYPES.dup
types << 'admin' if options[:active_admin] =~ Annotate::Constants::TRUE_RE && !types.include?('admin')
types << 'additional_file_patterns' if options[:additional_file_patterns].present?
types
end
......@@ -634,8 +499,11 @@ module AnnotateModels
end
next if options[exclusion_key]
get_patterns(key)
get_patterns(options, key)
.map { |f| resolve_filename(f, model_name, table_name) }
.map { |f| expand_glob_into_files(f) }
.flatten
.each do |f|
if annotate_one_file(f, info, position_key, options_with_position(options, position_key))
annotated << f
......@@ -731,14 +599,17 @@ module AnnotateModels
# Retrieve loaded model class
def get_loaded_model(model_path, file)
loaded_model_class = get_loaded_model_by_path(model_path)
return loaded_model_class if loaded_model_class
unless skip_subdirectory_model_load
loaded_model_class = get_loaded_model_by_path(model_path)
return loaded_model_class if loaded_model_class
end
# We cannot get loaded model when `model_path` is loaded by Rails
# auto_load/eager_load paths. Try all possible model paths one by one.
absolute_file = File.expand_path(file)
model_paths =
$LOAD_PATH.select { |path| absolute_file.include?(path) }
$LOAD_PATH.map(&:to_s)
.select { |path| absolute_file.include?(path) }
.map { |path| absolute_file.sub(path, '').sub(/\.rb$/, '').sub(/^\//, '') }
model_paths
.map { |path| get_loaded_model_by_path(path) }
......@@ -761,6 +632,7 @@ module AnnotateModels
def parse_options(options = {})
self.model_dir = split_model_dir(options[:model_dir]) if options[:model_dir]
self.root_dir = options[:root_dir] if options[:root_dir]
self.skip_subdirectory_model_load = options[:skip_subdirectory_model_load].present?
end
def split_model_dir(option_value)
......@@ -793,11 +665,15 @@ module AnnotateModels
end
end
def expand_glob_into_files(glob)
Dir.glob(glob)
end
def annotate_model_file(annotated, file, header, options)
begin
return false if /#{SKIP_ANNOTATION_PREFIX}.*/ =~ (File.exist?(file) ? File.read(file) : '')
klass = get_model_class(file)
do_annotate = klass &&
do_annotate = klass.is_a?(Class) &&
klass < ActiveRecord::Base &&
(!options[:exclude_sti_subclasses] || !(klass.superclass < ActiveRecord::Base && klass.table_name == klass.superclass.table_name)) &&
!klass.abstract_class? &&
......@@ -830,7 +706,7 @@ module AnnotateModels
model_file_name = file
deannotated_klass = true if remove_annotation_of_file(model_file_name, options)
get_patterns(matched_types(options))
get_patterns(options, matched_types(options))
.map { |f| resolve_filename(f, model_name, table_name) }
.each do |f|
if File.exist?(f)
......@@ -886,13 +762,15 @@ module AnnotateModels
end
def max_schema_info_width(klass, options)
cols = columns(klass, options)
if with_comments?(klass, options)
max_size = klass.columns.map do |column|
max_size = cols.map do |column|
column.name.size + (column.comment ? width(column.comment) : 0)
end.max || 0
max_size += 2
else
max_size = klass.column_names.map(&:size).max
max_size = cols.map(&:name).map(&:size).max
end
max_size += options[:format_rdoc] ? 5 : 1
......@@ -904,7 +782,7 @@ module AnnotateModels
end
def width(string)
string.chars.inject(0) { |acc, elem| acc + (elem.bytesize == 1 ? 1 : 2) }
string.chars.inject(0) { |acc, elem| acc + (elem.bytesize == 3 ? 2 : 1) }
end
def mb_chars_ljust(string, length)
......@@ -916,6 +794,119 @@ module AnnotateModels
string[0..length-1]
end
end
def non_ascii_length(string)
string.to_s.chars.reject(&:ascii_only?).length
end
def map_col_type_to_ruby_classes(col_type)
case col_type
when 'integer' then Integer.to_s
when 'float' then Float.to_s
when 'decimal' then BigDecimal.to_s
when 'datetime', 'timestamp', 'time' then Time.to_s
when 'date' then Date.to_s
when 'text', 'string', 'binary', 'inet', 'uuid' then String.to_s
when 'json', 'jsonb' then Hash.to_s
when 'boolean' then 'Boolean'
end
end
def columns(klass, options)
cols = klass.columns
cols += translated_columns(klass)
if ignore_columns = options[:ignore_columns]
cols = cols.reject do |col|
col.name.match(/#{ignore_columns}/)
end
end
cols = cols.sort_by(&:name) if options[:sort]
cols = classified_sort(cols) if options[:classified_sort]
cols
end
##
# Add columns managed by the globalize gem if this gem is being used.
def translated_columns(klass)
return [] unless klass.respond_to? :translation_class
ignored_cols = ignored_translation_table_colums(klass)
klass.translation_class.columns.reject do |col|
ignored_cols.include? col.name.to_sym
end
end
##
# These are the columns that the globalize gem needs to work but
# are not necessary for the models to be displayed as annotations.
def ignored_translation_table_colums(klass)
# Construct the foreign column name in the translations table
# eg. Model: Car, foreign column name: car_id
foreign_column_name = [
klass.table_name.to_s.singularize,
'_id'
].join.to_sym
[
:id,
:created_at,
:updated_at,
:locale,
foreign_column_name
]
end
##
# Get the list of attributes that should be included in the annotation for
# a given column.
def get_attributes(column, column_type, klass, options)
attrs = []
attrs << "default(#{schema_default(klass, column)})" unless column.default.nil? || hide_default?(column_type, options)
attrs << 'unsigned' if column.respond_to?(:unsigned?) && column.unsigned?
attrs << 'not null' unless column.null
attrs << 'primary key' if klass.primary_key && (klass.primary_key.is_a?(Array) ? klass.primary_key.collect(&:to_sym).include?(column.name.to_sym) : column.name.to_sym == klass.primary_key.to_sym)
if column_type == 'decimal'
column_type << "(#{column.precision}, #{column.scale})"
elsif !%w[spatial geometry geography].include?(column_type)
if column.limit && !options[:format_yard]
if column.limit.is_a? Array
attrs << "(#{column.limit.join(', ')})"
else
column_type << "(#{column.limit})" unless hide_limit?(column_type, options)
end
end
end
# Check out if we got an array column
attrs << 'is an Array' if column.respond_to?(:array) && column.array
# Check out if we got a geometric column
# and print the type and SRID
if column.respond_to?(:geometry_type)
attrs << [column.geometry_type, column.try(:srid)].compact.join(', ')
elsif column.respond_to?(:geometric_type) && column.geometric_type.present?
attrs << [column.geometric_type.to_s.downcase, column.try(:srid)].compact.join(', ')
end
# Check if the column has indices and print "indexed" if true
# If the index includes another column, print it too.
if options[:simple_indexes] && klass.table_exists?# Check out if this column is indexed
indices = retrieve_indexes_from_table(klass)
if indices = indices.select { |ind| ind.columns.include? column.name }
indices.sort_by(&:name).each do |ind|
next if ind.columns.is_a?(String)
ind = ind.columns.reject! { |i| i == column.name }
attrs << (ind.empty? ? "indexed" : "indexed => [#{ind.join(", ")}]")
end
end
end
attrs
end
end
class BadModelFileError < LoadError
......
module AnnotateModels
# This module provides module method to get file paths.
module FilePatterns
# Controller files
CONTROLLER_DIR = File.join('app', 'controllers')
# Active admin registry files
ACTIVEADMIN_DIR = File.join('app', 'admin')
# Helper files
HELPER_DIR = File.join('app', 'helpers')
# File.join for windows reverse bar compat?
# I dont use windows, can`t test
UNIT_TEST_DIR = File.join('test', 'unit')
MODEL_TEST_DIR = File.join('test', 'models') # since rails 4.0
SPEC_MODEL_DIR = File.join('spec', 'models')
FIXTURE_TEST_DIR = File.join('test', 'fixtures')
FIXTURE_SPEC_DIR = File.join('spec', 'fixtures')
# Other test files
CONTROLLER_TEST_DIR = File.join('test', 'controllers')
CONTROLLER_SPEC_DIR = File.join('spec', 'controllers')
REQUEST_SPEC_DIR = File.join('spec', 'requests')
ROUTING_SPEC_DIR = File.join('spec', 'routing')
# Object Daddy http://github.com/flogic/object_daddy/tree/master
EXEMPLARS_TEST_DIR = File.join('test', 'exemplars')
EXEMPLARS_SPEC_DIR = File.join('spec', 'exemplars')
# Machinist http://github.com/notahat/machinist
BLUEPRINTS_TEST_DIR = File.join('test', 'blueprints')
BLUEPRINTS_SPEC_DIR = File.join('spec', 'blueprints')
# Factory Bot https://github.com/thoughtbot/factory_bot
FACTORY_BOT_TEST_DIR = File.join('test', 'factories')
FACTORY_BOT_SPEC_DIR = File.join('spec', 'factories')
# Fabrication https://github.com/paulelliott/fabrication.git
FABRICATORS_TEST_DIR = File.join('test', 'fabricators')
FABRICATORS_SPEC_DIR = File.join('spec', 'fabricators')
# Serializers https://github.com/rails-api/active_model_serializers
SERIALIZERS_DIR = File.join('app', 'serializers')
SERIALIZERS_TEST_DIR = File.join('test', 'serializers')
SERIALIZERS_SPEC_DIR = File.join('spec', 'serializers')
class << self
def generate(root_directory, pattern_type, options)
case pattern_type
when 'test' then test_files(root_directory)
when 'fixture' then fixture_files(root_directory)
when 'scaffold' then scaffold_files(root_directory)
when 'factory' then factory_files(root_directory)
when 'serializer' then serialize_files(root_directory)
when 'additional_file_patterns'
[options[:additional_file_patterns] || []].flatten
when 'controller'
[File.join(root_directory, CONTROLLER_DIR, '%PLURALIZED_MODEL_NAME%_controller.rb')]
when 'admin'
[
File.join(root_directory, ACTIVEADMIN_DIR, '%MODEL_NAME%.rb'),
File.join(root_directory, ACTIVEADMIN_DIR, '%PLURALIZED_MODEL_NAME%.rb')
]
when 'helper'
[File.join(root_directory, HELPER_DIR, '%PLURALIZED_MODEL_NAME%_helper.rb')]
else
[]
end
end
private
def test_files(root_directory)
[
File.join(root_directory, UNIT_TEST_DIR, '%MODEL_NAME%_test.rb'),
File.join(root_directory, MODEL_TEST_DIR, '%MODEL_NAME%_test.rb'),
File.join(root_directory, SPEC_MODEL_DIR, '%MODEL_NAME%_spec.rb')
]
end
def fixture_files(root_directory)
[
File.join(root_directory, FIXTURE_TEST_DIR, '%TABLE_NAME%.yml'),
File.join(root_directory, FIXTURE_SPEC_DIR, '%TABLE_NAME%.yml'),
File.join(root_directory, FIXTURE_TEST_DIR, '%PLURALIZED_MODEL_NAME%.yml'),
File.join(root_directory, FIXTURE_SPEC_DIR, '%PLURALIZED_MODEL_NAME%.yml')
]
end
def scaffold_files(root_directory)
[
File.join(root_directory, CONTROLLER_TEST_DIR, '%PLURALIZED_MODEL_NAME%_controller_test.rb'),
File.join(root_directory, CONTROLLER_SPEC_DIR, '%PLURALIZED_MODEL_NAME%_controller_spec.rb'),
File.join(root_directory, REQUEST_SPEC_DIR, '%PLURALIZED_MODEL_NAME%_spec.rb'),
File.join(root_directory, ROUTING_SPEC_DIR, '%PLURALIZED_MODEL_NAME%_routing_spec.rb')
]
end
def factory_files(root_directory)
[
File.join(root_directory, EXEMPLARS_TEST_DIR, '%MODEL_NAME%_exemplar.rb'),
File.join(root_directory, EXEMPLARS_SPEC_DIR, '%MODEL_NAME%_exemplar.rb'),
File.join(root_directory, BLUEPRINTS_TEST_DIR, '%MODEL_NAME%_blueprint.rb'),
File.join(root_directory, BLUEPRINTS_SPEC_DIR, '%MODEL_NAME%_blueprint.rb'),
File.join(root_directory, FACTORY_BOT_TEST_DIR, '%MODEL_NAME%_factory.rb'), # (old style)
File.join(root_directory, FACTORY_BOT_SPEC_DIR, '%MODEL_NAME%_factory.rb'), # (old style)
File.join(root_directory, FACTORY_BOT_TEST_DIR, '%TABLE_NAME%.rb'), # (new style)
File.join(root_directory, FACTORY_BOT_SPEC_DIR, '%TABLE_NAME%.rb'), # (new style)
File.join(root_directory, FACTORY_BOT_TEST_DIR, '%PLURALIZED_MODEL_NAME%.rb'), # (new style)
File.join(root_directory, FACTORY_BOT_SPEC_DIR, '%PLURALIZED_MODEL_NAME%.rb'), # (new style)
File.join(root_directory, FABRICATORS_TEST_DIR, '%MODEL_NAME%_fabricator.rb'),
File.join(root_directory, FABRICATORS_SPEC_DIR, '%MODEL_NAME%_fabricator.rb')
]
end
def serialize_files(root_directory)
[
File.join(root_directory, SERIALIZERS_DIR, '%MODEL_NAME%_serializer.rb'),
File.join(root_directory, SERIALIZERS_TEST_DIR, '%MODEL_NAME%_serializer_test.rb'),
File.join(root_directory, SERIALIZERS_SPEC_DIR, '%MODEL_NAME%_serializer_spec.rb')
]
end
end
end
end
# rubocop:disable Metrics/ModuleLength
# == Annotate Routes
#
# Based on:
......@@ -10,7 +8,7 @@
# Yes, it's simple but I'm thick and often need a reminder of what my routes
# mean.
#
# Running this task will replace any exising route comment generated by the
# Running this task will replace any existing route comment generated by the
# task. Best to back up your routes file before running:
#
# Author:
......@@ -19,145 +17,73 @@
#
# Released under the same license as Ruby. No Support. No Warranty.
#
module AnnotateRoutes
PREFIX = '== Route Map'.freeze
PREFIX_MD = '## Route Map'.freeze
HEADER_ROW = ['Prefix', 'Verb', 'URI Pattern', 'Controller#Action']
require_relative './annotate_routes/helpers'
require_relative './annotate_routes/header_generator'
module AnnotateRoutes
class << self
def do_annotations(options = {})
return unless routes_exists?
existing_text = File.read(routes_file)
if rewrite_contents_with_header(existing_text, header(options), options)
puts "#{routes_file} annotated."
if routes_file_exist?
existing_text = File.read(routes_file)
content, header_position = Helpers.strip_annotations(existing_text)
new_content = annotate_routes(HeaderGenerator.generate(options), content, header_position, options)
new_text = new_content.join("\n")
if rewrite_contents(existing_text, new_text)
puts "#{routes_file} was annotated."
else
puts "#{routes_file} was not changed."
end
else
puts "#{routes_file} could not be found."
end
end
def remove_annotations(_options={})
return unless routes_exists?
existing_text = File.read(routes_file)
content, where_header_found = strip_annotations(existing_text)
new_content = strip_on_removal(content, where_header_found)
if rewrite_contents(existing_text, new_content)
puts "Removed annotations from #{routes_file}."
if routes_file_exist?
existing_text = File.read(routes_file)
content, header_position = Helpers.strip_annotations(existing_text)
new_content = strip_on_removal(content, header_position)
new_text = new_content.join("\n")
if rewrite_contents(existing_text, new_text)
puts "Annotations were removed from #{routes_file}."
else
puts "#{routes_file} was not changed (Annotation did not exist)."
end
else
puts "#{routes_file} could not be found."
end
end
private
def routes_exists?
routes_exists = File.exists?(routes_file)
puts "Can't find routes.rb" unless routes_exists
routes_exists
def routes_file_exist?
File.exist?(routes_file)
end
def routes_file
@routes_rb ||= File.join('config', 'routes.rb')
end
def rewrite_contents_with_header(existing_text, header, options = {})
content, where_header_found = strip_annotations(existing_text)
new_content = annotate_routes(header, content, where_header_found, options)
# Make sure we end on a trailing newline.
new_content << '' unless new_content.last == ''
new_text = new_content.join("\n")
if existing_text == new_text
puts "#{routes_file} unchanged."
false
else
File.open(routes_file, 'wb') { |f| f.puts(new_text) }
true
end
end
def header(options = {})
routes_map = app_routes_map(options)
magic_comments_map, routes_map = extract_magic_comments_from_array(routes_map)
out = []
magic_comments_map.each do |magic_comment|
out << magic_comment
end
out << '' if magic_comments_map.any?
out += ["# #{options[:wrapper_open]}"] if options[:wrapper_open]
out += ["# #{options[:format_markdown] ? PREFIX_MD : PREFIX}" + (options[:timestamp] ? " (Updated #{Time.now.strftime('%Y-%m-%d %H:%M')})" : '')]
out += ['#']
return out if routes_map.size.zero?
maxs = [HEADER_ROW.map(&:size)] + routes_map[1..-1].map { |line| line.split.map(&:size) }
if options[:format_markdown]
max = maxs.map(&:max).compact.max
out += ["# #{content(HEADER_ROW, maxs, options)}"]
out += ["# #{content(['-' * max, '-' * max, '-' * max, '-' * max], maxs, options)}"]
else
out += ["# #{content(routes_map[0], maxs, options)}"]
end
out += routes_map[1..-1].map { |line| "# #{content(options[:format_markdown] ? line.split(' ') : line, maxs, options)}" }
out += ["# #{options[:wrapper_close]}"] if options[:wrapper_close]
out
end
# TODO: write the method doc using ruby rdoc formats
# where_header_found => This will either be :before, :after, or
# a number. If the number is > 0, the
# annotation was found somewhere in the
# middle of the file. If the number is
# zero, no annotation was found.
def strip_annotations(content)
real_content = []
mode = :content
header_found_at = 0
content.split(/\n/, -1).each_with_index do |line, line_number|
if mode == :header && line !~ /\s*#/
mode = :content
real_content << line unless line.blank?
elsif mode == :content
if line =~ /^\s*#\s*== Route.*$/
header_found_at = line_number + 1 # index start's at 0
mode = :header
else
real_content << line
end
end
end
where_header_found(real_content, header_found_at)
end
def strip_on_removal(content, where_header_found)
if where_header_found == :before
def strip_on_removal(content, header_position)
if header_position == :before
content.shift while content.first == ''
elsif where_header_found == :after
elsif header_position == :after
content.pop while content.last == ''
end
# Make sure we end on a trailing newline.
content << '' unless content.last == ''
# TODO: If the user buried it in the middle, we should probably see about
# TODO: preserving a single line of space between the content above and
# TODO: below...
content
end
# @param [String, Array<String>]
def rewrite_contents(existing_text, new_content)
# Make sure we end on a trailing newline.
new_content << '' unless new_content.last == ''
new_text = new_content.join("\n")
def rewrite_contents(existing_text, new_text)
if existing_text == new_text
puts "#{routes_file} unchanged."
false
else
File.open(routes_file, 'wb') { |f| f.puts(new_text) }
......@@ -165,8 +91,8 @@ module AnnotateRoutes
end
end
def annotate_routes(header, content, where_header_found, options = {})
magic_comments_map, content = extract_magic_comments_from_array(content)
def annotate_routes(header, content, header_position, options = {})
magic_comments_map, content = Helpers.extract_magic_comments_from_array(content)
if %w(before top).include?(options[:position_in_routes])
header = header << '' if content.first != ''
magic_comments_map << '' if magic_comments_map.any?
......@@ -178,74 +104,15 @@ module AnnotateRoutes
# We're moving something from the top of the file to the bottom, so ditch
# the spacer we put in the first time around.
content.shift if where_header_found == :before && content.first == ''
content.shift if header_position == :before && content.first == ''
new_content = magic_comments_map + content + header
end
new_content
end
def app_routes_map(options)
routes_map = `rake routes`.chomp("\n").split(/\n/, -1)
# In old versions of Rake, the first line of output was the cwd. Not so
# much in newer ones. We ditch that line if it exists, and if not, we
# keep the line around.
routes_map.shift if routes_map.first =~ /^\(in \//
# Skip routes which match given regex
# Note: it matches the complete line (route_name, path, controller/action)
if options[:ignore_routes]
routes_map.reject! { |line| line =~ /#{options[:ignore_routes]}/ }
end
routes_map
end
# @param [Array<String>] content
# @return [Array<String>] all found magic comments
# @return [Array<String>] content without magic comments
def extract_magic_comments_from_array(content_array)
magic_comments = []
new_content = []
content_array.map do |row|
if row =~ magic_comment_matcher
magic_comments << row.strip
else
new_content << row
end
end
[magic_comments, new_content]
end
def content(line, maxs, options = {})
return line.rstrip unless options[:format_markdown]
line.each_with_index.map do |elem, index|
min_length = maxs.map { |arr| arr[index] }.max || 0
sprintf("%-#{min_length}.#{min_length}s", elem.tr('|', '-'))
end.join(' | ')
end
def where_header_found(real_content, header_found_at)
# By default assume the annotation was found in the middle of the file
# ... unless we have evidence it was at the beginning ...
return real_content, :before if header_found_at == 1
# ... or that it was at the end.
return real_content, :after if header_found_at >= real_content.count
# and the default
return real_content, header_found_at
end
# Make sure we end on a trailing newline.
new_content << '' unless new_content.last == ''
def magic_comment_matcher
Regexp.new(/(^#\s*encoding:.*)|(^# coding:.*)|(^# -\*- coding:.*)|(^# -\*- encoding\s?:.*)|(^#\s*frozen_string_literal:.+)|(^# -\*- frozen_string_literal\s*:.+-\*-)/)
new_content
end
end
end
require_relative './helpers'
module AnnotateRoutes
class HeaderGenerator
PREFIX = '== Route Map'.freeze
PREFIX_MD = '## Route Map'.freeze
HEADER_ROW = ['Prefix', 'Verb', 'URI Pattern', 'Controller#Action'].freeze
class << self
def generate(options = {})
new(options, routes_map(options)).generate
end
private :new
private
def routes_map(options)
result = `rake routes`.chomp("\n").split(/\n/, -1)
# In old versions of Rake, the first line of output was the cwd. Not so
# much in newer ones. We ditch that line if it exists, and if not, we
# keep the line around.
result.shift if result.first =~ %r{^\(in \/}
ignore_routes = options[:ignore_routes]
regexp_for_ignoring_routes = ignore_routes ? /#{ignore_routes}/ : nil
# Skip routes which match given regex
# Note: it matches the complete line (route_name, path, controller/action)
if regexp_for_ignoring_routes
result.reject { |line| line =~ regexp_for_ignoring_routes }
else
result
end
end
end
def initialize(options, routes_map)
@options = options
@routes_map = routes_map
end
def generate
magic_comments_map, contents_without_magic_comments = Helpers.extract_magic_comments_from_array(routes_map)
out = []
magic_comments_map.each do |magic_comment|
out << magic_comment
end
out << '' if magic_comments_map.any?
out << comment(options[:wrapper_open]) if options[:wrapper_open]
out << comment(markdown? ? PREFIX_MD : PREFIX) + timestamp_if_required
out << comment
return out if contents_without_magic_comments.size.zero?
maxs = [HEADER_ROW.map(&:size)] + contents_without_magic_comments[1..-1].map { |line| line.split.map(&:size) }
if markdown?
max = maxs.map(&:max).compact.max
out << comment(content(HEADER_ROW, maxs))
out << comment(content(['-' * max, '-' * max, '-' * max, '-' * max], maxs))
else
out << comment(content(contents_without_magic_comments[0], maxs))
end
out += contents_without_magic_comments[1..-1].map { |line| comment(content(markdown? ? line.split(' ') : line, maxs)) }
out << comment(options[:wrapper_close]) if options[:wrapper_close]
out
end
private
attr_reader :options, :routes_map
def comment(row = '')
if row == ''
'#'
else
"# #{row}"
end
end
def content(line, maxs)
return line.rstrip unless markdown?
line.each_with_index.map { |elem, index| format_line_element(elem, maxs, index) }.join(' | ')
end
def format_line_element(elem, maxs, index)
min_length = maxs.map { |arr| arr[index] }.max || 0
format("%-#{min_length}.#{min_length}s", elem.tr('|', '-'))
end
def markdown?
options[:format_markdown]
end
def timestamp_if_required(time = Time.now)
if options[:timestamp]
time_formatted = time.strftime('%Y-%m-%d %H:%M')
" (Updated #{time_formatted})"
else
''
end
end
end
end
module AnnotateRoutes
module Helpers
MAGIC_COMMENT_MATCHER = Regexp.new(/(^#\s*encoding:.*)|(^# coding:.*)|(^# -\*- coding:.*)|(^# -\*- encoding\s?:.*)|(^#\s*frozen_string_literal:.+)|(^# -\*- frozen_string_literal\s*:.+-\*-)/).freeze
class << self
# TODO: write the method doc using ruby rdoc formats
# This method returns an array of 'real_content' and 'header_position'.
# 'header_position' will either be :before, :after, or
# a number. If the number is > 0, the
# annotation was found somewhere in the
# middle of the file. If the number is
# zero, no annotation was found.
def strip_annotations(content)
real_content = []
mode = :content
header_position = 0
content.split(/\n/, -1).each_with_index do |line, line_number|
if mode == :header && line !~ /\s*#/
mode = :content
real_content << line unless line.blank?
elsif mode == :content
if line =~ /^\s*#\s*== Route.*$/
header_position = line_number + 1 # index start's at 0
mode = :header
else
real_content << line
end
end
end
real_content_and_header_position(real_content, header_position)
end
# @param [Array<String>] content
# @return [Array<String>] all found magic comments
# @return [Array<String>] content without magic comments
def extract_magic_comments_from_array(content_array)
magic_comments = []
new_content = []
content_array.each do |row|
if row =~ MAGIC_COMMENT_MATCHER
magic_comments << row.strip
else
new_content << row
end
end
[magic_comments, new_content]
end
private
def real_content_and_header_position(real_content, header_position)
# By default assume the annotation was found in the middle of the file
# ... unless we have evidence it was at the beginning ...
return real_content, :before if header_position == 1
# ... or that it was at the end.
return real_content, :after if header_position >= real_content.count
# and the default
return real_content, header_position
end
end
end
end
module Annotate
module Constants
TRUE_RE = /^(true|t|yes|y|1)$/i.freeze
##
# The set of available options to customize the behavior of Annotate.
#
POSITION_OPTIONS = [
:position_in_routes, :position_in_class, :position_in_test,
:position_in_fixture, :position_in_factory, :position,
:position_in_serializer
].freeze
FLAG_OPTIONS = [
:show_indexes, :simple_indexes, :include_version, :exclude_tests,
:exclude_fixtures, :exclude_factories, :ignore_model_sub_dir,
:format_bare, :format_rdoc, :format_yard, :format_markdown, :sort, :force, :frozen,
:trace, :timestamp, :exclude_serializers, :classified_sort,
:show_foreign_keys, :show_complete_foreign_keys,
:exclude_scaffolds, :exclude_controllers, :exclude_helpers,
:exclude_sti_subclasses, :ignore_unknown_models, :with_comment
].freeze
OTHER_OPTIONS = [
:additional_file_patterns, :ignore_columns, :skip_on_db_migrate, :wrapper_open, :wrapper_close,
:wrapper, :routes, :models, :hide_limit_column_types, :hide_default_column_types,
:ignore_routes, :active_admin
].freeze
PATH_OPTIONS = [
:require, :model_dir, :root_dir
].freeze
ALL_ANNOTATE_OPTIONS = [
POSITION_OPTIONS, FLAG_OPTIONS, OTHER_OPTIONS, PATH_OPTIONS
].freeze
end
end
module Annotate
# Class for holding helper methods. Done to make lib/annotate.rb less bloated.
class Helpers
class << self
def skip_on_migration?
ENV['ANNOTATE_SKIP_ON_DB_MIGRATE'] =~ Constants::TRUE_RE || ENV['skip_on_db_migrate'] =~ Constants::TRUE_RE
end
def include_routes?
ENV['routes'] =~ Constants::TRUE_RE
end
def include_models?
ENV['models'] =~ Constants::TRUE_RE
end
def true?(val)
val.present? && Constants::TRUE_RE.match?(val)
end
def fallback(*args)
args.detect(&:present?)
end
def reset_options(options)
options.flatten.each { |key| ENV[key.to_s] = nil }
end
end
end
end
require 'optparse'
module Annotate
# Class for handling command line arguments
class Parser # rubocop:disable Metrics/ClassLength
def self.parse(args, env = {})
new(args, env).parse
end
attr_reader :args, :options, :env
DEFAULT_OPTIONS = {
target_action: :do_annotations,
exit: false
}.freeze
ANNOTATION_POSITIONS = %w[before top after bottom].freeze
FILE_TYPE_POSITIONS = %w[position_in_class position_in_factory position_in_fixture position_in_test position_in_routes position_in_serializer].freeze
EXCLUSION_LIST = %w[tests fixtures factories serializers].freeze
FORMAT_TYPES = %w[bare rdoc yard markdown].freeze
def initialize(args, env)
@args = args
@options = DEFAULT_OPTIONS.dup
@env = env
end
def parse
# To split up because right now this method parses and commits
parser.parse!(args)
commit
options
end
private
def parser
OptionParser.new do |option_parser|
add_options_to_parser(option_parser)
end
end
def commit
env.each_pair do |key, value|
ENV[key] = value
end
end
def add_options_to_parser(option_parser) # rubocop:disable Metrics/MethodLength
has_set_position = {}
option_parser.banner = 'Usage: annotate [options] [model_file]*'
option_parser.on('--additional-file-patterns path1,path2,path3',
Array,
"Additional file paths or globs to annotate, separated by commas (e.g. `/foo/bar/%model_name%/*.rb,/baz/%model_name%.rb`)") do |additional_file_patterns|
ENV['additional_file_patterns'] = additional_file_patterns
end
option_parser.on('-d',
'--delete',
'Remove annotations from all model files or the routes.rb file') do
@options[:target_action] = :remove_annotations
end
option_parser.on('-p',
'--position [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of the model/test/fixture/factory/route/serializer file(s)') do |position|
env['position'] = position
FILE_TYPE_POSITIONS.each do |key|
env[key] = position unless has_set_position[key]
end
end
option_parser.on('--pc',
'--position-in-class [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of the model file') do |position_in_class|
env['position_in_class'] = position_in_class
has_set_position['position_in_class'] = true
end
option_parser.on('--pf',
'--position-in-factory [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of any factory files') do |position_in_factory|
env['position_in_factory'] = position_in_factory
has_set_position['position_in_factory'] = true
end
option_parser.on('--px',
'--position-in-fixture [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of any fixture files') do |position_in_fixture|
env['position_in_fixture'] = position_in_fixture
has_set_position['position_in_fixture'] = true
end
option_parser.on('--pt',
'--position-in-test [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of any test files') do |position_in_test|
env['position_in_test'] = position_in_test
has_set_position['position_in_test'] = true
end
option_parser.on('--pr',
'--position-in-routes [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of the routes.rb file') do |position_in_routes|
env['position_in_routes'] = position_in_routes
has_set_position['position_in_routes'] = true
end
option_parser.on('--ps',
'--position-in-serializer [before|top|after|bottom]',
ANNOTATION_POSITIONS,
'Place the annotations at the top (before) or the bottom (after) of the serializer files') do |position_in_serializer|
env['position_in_serializer'] = position_in_serializer
has_set_position['position_in_serializer'] = true
end
option_parser.on('--w',
'--wrapper STR',
'Wrap annotation with the text passed as parameter.',
'If --w option is used, the same text will be used as opening and closing') do |wrapper|
env['wrapper'] = wrapper
end
option_parser.on('--wo',
'--wrapper-open STR',
'Annotation wrapper opening.') do |wrapper_open|
env['wrapper_open'] = wrapper_open
end
option_parser.on('--wc',
'--wrapper-close STR',
'Annotation wrapper closing') do |wrapper_close|
env['wrapper_close'] = wrapper_close
end
option_parser.on('-r',
'--routes',
"Annotate routes.rb with the output of 'rake routes'") do
env['routes'] = 'true'
end
option_parser.on('--models',
"Annotate ActiveRecord models") do
env['models'] = 'true'
end
option_parser.on('-a',
'--active-admin',
'Annotate active_admin models') do
env['active_admin'] = 'true'
end
option_parser.on('-v',
'--version',
'Show the current version of this gem') do
puts "annotate v#{Annotate.version}"
@options[:exit] = true
end
option_parser.on('-m',
'--show-migration',
'Include the migration version number in the annotation') do
env['include_version'] = 'yes'
end
option_parser.on('-k',
'--show-foreign-keys',
"List the table's foreign key constraints in the annotation") do
env['show_foreign_keys'] = 'yes'
end
option_parser.on('--ck',
'--complete-foreign-keys',
'Complete foreign key names in the annotation') do
env['show_foreign_keys'] = 'yes'
env['show_complete_foreign_keys'] = 'yes'
end
option_parser.on('-i',
'--show-indexes',
"List the table's database indexes in the annotation") do
env['show_indexes'] = 'yes'
end
option_parser.on('-s',
'--simple-indexes',
"Concat the column's related indexes in the annotation") do
env['simple_indexes'] = 'yes'
end
option_parser.on('--model-dir dir',
"Annotate model files stored in dir rather than app/models, separate multiple dirs with commas") do |dir|
env['model_dir'] = dir
end
option_parser.on('--root-dir dir',
"Annotate files stored within root dir projects, separate multiple dirs with commas") do |dir|
env['root_dir'] = dir
end
option_parser.on('--ignore-model-subdirects',
"Ignore subdirectories of the models directory") do
env['ignore_model_sub_dir'] = 'yes'
end
option_parser.on('--sort',
"Sort columns alphabetically, rather than in creation order") do
env['sort'] = 'yes'
end
option_parser.on('--classified-sort',
"Sort columns alphabetically, but first goes id, then the rest columns, then the timestamp columns and then the association columns") do
env['classified_sort'] = 'yes'
end
option_parser.on('-R',
'--require path',
"Additional file to require before loading models, may be used multiple times") do |path|
env['require'] = if env['require'].present?
"#{env['require']},#{path}"
else
path
end
end
option_parser.on('-e',
'--exclude [tests,fixtures,factories,serializers]',
Array,
"Do not annotate fixtures, test files, factories, and/or serializers") do |exclusions|
exclusions ||= EXCLUSION_LIST
exclusions.each { |exclusion| env["exclude_#{exclusion}"] = 'yes' }
end
option_parser.on('-f',
'--format [bare|rdoc|yard|markdown]',
FORMAT_TYPES,
'Render Schema Infomation as plain/RDoc/Yard/Markdown') do |format_type|
env["format_#{format_type}"] = 'yes'
end
option_parser.on('--force',
'Force new annotations even if there are no changes.') do
env['force'] = 'yes'
end
option_parser.on('--frozen',
'Do not allow to change annotations. Exits non-zero if there are going to be changes to files.') do
env['frozen'] = 'yes'
end
option_parser.on('--timestamp',
'Include timestamp in (routes) annotation') do
env['timestamp'] = 'true'
end
option_parser.on('--trace',
'If unable to annotate a file, print the full stack trace, not just the exception message.') do
env['trace'] = 'yes'
end
option_parser.on('-I',
'--ignore-columns REGEX',
"don't annotate columns that match a given REGEX (i.e., `annotate -I '^(id|updated_at|created_at)'`") do |regex|
env['ignore_columns'] = regex
end
option_parser.on('--ignore-routes REGEX',
"don't annotate routes that match a given REGEX (i.e., `annotate -I '(mobile|resque|pghero)'`") do |regex|
env['ignore_routes'] = regex
end
option_parser.on('--hide-limit-column-types VALUES',
"don't show limit for given column types, separated by commas (i.e., `integer,boolean,text`)") do |values|
env['hide_limit_column_types'] = values.to_s
end
option_parser.on('--hide-default-column-types VALUES',
"don't show default for given column types, separated by commas (i.e., `json,jsonb,hstore`)") do |values|
env['hide_default_column_types'] = values.to_s
end
option_parser.on('--ignore-unknown-models',
"don't display warnings for bad model files") do
env['ignore_unknown_models'] = 'true'
end
option_parser.on('--with-comment',
"include database comments in model annotations") do
env['with_comment'] = 'true'
end
end
end
end
module Annotate
def self.version
'2.7.5'
'3.2.0'
end
end
......@@ -7,47 +7,51 @@ if Rails.env.development?
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults(
'routes' => 'false',
'position_in_routes' => 'before',
'position_in_class' => 'before',
'position_in_test' => 'before',
'position_in_fixture' => 'before',
'position_in_factory' => 'before',
'position_in_serializer' => 'before',
'show_foreign_keys' => 'true',
'show_complete_foreign_keys' => 'false',
'show_indexes' => 'true',
'simple_indexes' => 'false',
'model_dir' => 'app/models',
'root_dir' => '',
'include_version' => 'false',
'require' => '',
'exclude_tests' => 'false',
'exclude_fixtures' => 'false',
'exclude_factories' => 'false',
'exclude_serializers' => 'false',
'exclude_scaffolds' => 'true',
'exclude_controllers' => 'true',
'exclude_helpers' => 'true',
'exclude_sti_subclasses' => 'false',
'ignore_model_sub_dir' => 'false',
'ignore_columns' => nil,
'ignore_routes' => nil,
'ignore_unknown_models' => 'false',
'hide_limit_column_types' => '<%= AnnotateModels::NO_LIMIT_COL_TYPES.join(",") %>',
'hide_default_column_types' => '<%= AnnotateModels::NO_DEFAULT_COL_TYPES.join(",") %>',
'skip_on_db_migrate' => 'false',
'format_bare' => 'true',
'format_rdoc' => 'false',
'format_markdown' => 'false',
'sort' => 'false',
'force' => 'false',
'frozen' => 'false',
'classified_sort' => 'true',
'trace' => 'false',
'wrapper_open' => nil,
'wrapper_close' => nil,
'with_comment' => 'true'
'active_admin' => 'false',
'additional_file_patterns' => [],
'routes' => 'false',
'models' => 'true',
'position_in_routes' => 'before',
'position_in_class' => 'before',
'position_in_test' => 'before',
'position_in_fixture' => 'before',
'position_in_factory' => 'before',
'position_in_serializer' => 'before',
'show_foreign_keys' => 'true',
'show_complete_foreign_keys' => 'false',
'show_indexes' => 'true',
'simple_indexes' => 'false',
'model_dir' => 'app/models',
'root_dir' => '',
'include_version' => 'false',
'require' => '',
'exclude_tests' => 'false',
'exclude_fixtures' => 'false',
'exclude_factories' => 'false',
'exclude_serializers' => 'false',
'exclude_scaffolds' => 'true',
'exclude_controllers' => 'true',
'exclude_helpers' => 'true',
'exclude_sti_subclasses' => 'false',
'ignore_model_sub_dir' => 'false',
'ignore_columns' => nil,
'ignore_routes' => nil,
'ignore_unknown_models' => 'false',
'hide_limit_column_types' => '<%= AnnotateModels::NO_LIMIT_COL_TYPES.join(",") %>',
'hide_default_column_types' => '<%= AnnotateModels::NO_DEFAULT_COL_TYPES.join(",") %>',
'skip_on_db_migrate' => 'false',
'format_bare' => 'true',
'format_rdoc' => 'false',
'format_yard' => 'false',
'format_markdown' => 'false',
'sort' => 'false',
'force' => 'false',
'frozen' => 'false',
'classified_sort' => 'true',
'trace' => 'false',
'wrapper_open' => nil,
'wrapper_close' => nil,
'with_comment' => 'true'
)
end
......
......@@ -11,45 +11,47 @@ task annotate_models: :environment do
require "#{annotate_lib}/annotate/active_record_patch"
options = {is_rake: true}
ENV['position'] = options[:position] = Annotate.fallback(ENV['position'], 'before')
options[:position_in_class] = Annotate.fallback(ENV['position_in_class'], ENV['position'])
options[:position_in_fixture] = Annotate.fallback(ENV['position_in_fixture'], ENV['position'])
options[:position_in_factory] = Annotate.fallback(ENV['position_in_factory'], ENV['position'])
options[:position_in_test] = Annotate.fallback(ENV['position_in_test'], ENV['position'])
options[:position_in_serializer] = Annotate.fallback(ENV['position_in_serializer'], ENV['position'])
options[:show_foreign_keys] = Annotate.true?(ENV['show_foreign_keys'])
options[:show_complete_foreign_keys] = Annotate.true?(ENV['show_complete_foreign_keys'])
options[:show_indexes] = Annotate.true?(ENV['show_indexes'])
options[:simple_indexes] = Annotate.true?(ENV['simple_indexes'])
ENV['position'] = options[:position] = Annotate::Helpers.fallback(ENV['position'], 'before')
options[:additional_file_patterns] = ENV['additional_file_patterns'] ? ENV['additional_file_patterns'].split(',') : []
options[:position_in_class] = Annotate::Helpers.fallback(ENV['position_in_class'], ENV['position'])
options[:position_in_fixture] = Annotate::Helpers.fallback(ENV['position_in_fixture'], ENV['position'])
options[:position_in_factory] = Annotate::Helpers.fallback(ENV['position_in_factory'], ENV['position'])
options[:position_in_test] = Annotate::Helpers.fallback(ENV['position_in_test'], ENV['position'])
options[:position_in_serializer] = Annotate::Helpers.fallback(ENV['position_in_serializer'], ENV['position'])
options[:show_foreign_keys] = Annotate::Helpers.true?(ENV['show_foreign_keys'])
options[:show_complete_foreign_keys] = Annotate::Helpers.true?(ENV['show_complete_foreign_keys'])
options[:show_indexes] = Annotate::Helpers.true?(ENV['show_indexes'])
options[:simple_indexes] = Annotate::Helpers.true?(ENV['simple_indexes'])
options[:model_dir] = ENV['model_dir'] ? ENV['model_dir'].split(',') : ['app/models']
options[:root_dir] = ENV['root_dir']
options[:include_version] = Annotate.true?(ENV['include_version'])
options[:include_version] = Annotate::Helpers.true?(ENV['include_version'])
options[:require] = ENV['require'] ? ENV['require'].split(',') : []
options[:exclude_tests] = Annotate.true?(ENV['exclude_tests'])
options[:exclude_factories] = Annotate.true?(ENV['exclude_factories'])
options[:exclude_fixtures] = Annotate.true?(ENV['exclude_fixtures'])
options[:exclude_serializers] = Annotate.true?(ENV['exclude_serializers'])
options[:exclude_scaffolds] = Annotate.true?(ENV['exclude_scaffolds'])
options[:exclude_controllers] = Annotate.true?(ENV.fetch('exclude_controllers', 'true'))
options[:exclude_helpers] = Annotate.true?(ENV.fetch('exclude_helpers', 'true'))
options[:exclude_sti_subclasses] = Annotate.true?(ENV['exclude_sti_subclasses'])
options[:ignore_model_sub_dir] = Annotate.true?(ENV['ignore_model_sub_dir'])
options[:format_bare] = Annotate.true?(ENV['format_bare'])
options[:format_rdoc] = Annotate.true?(ENV['format_rdoc'])
options[:format_markdown] = Annotate.true?(ENV['format_markdown'])
options[:sort] = Annotate.true?(ENV['sort'])
options[:force] = Annotate.true?(ENV['force'])
options[:frozen] = Annotate.true?(ENV['frozen'])
options[:classified_sort] = Annotate.true?(ENV['classified_sort'])
options[:trace] = Annotate.true?(ENV['trace'])
options[:wrapper_open] = Annotate.fallback(ENV['wrapper_open'], ENV['wrapper'])
options[:wrapper_close] = Annotate.fallback(ENV['wrapper_close'], ENV['wrapper'])
options[:exclude_tests] = Annotate::Helpers.true?(ENV['exclude_tests'])
options[:exclude_factories] = Annotate::Helpers.true?(ENV['exclude_factories'])
options[:exclude_fixtures] = Annotate::Helpers.true?(ENV['exclude_fixtures'])
options[:exclude_serializers] = Annotate::Helpers.true?(ENV['exclude_serializers'])
options[:exclude_scaffolds] = Annotate::Helpers.true?(ENV['exclude_scaffolds'])
options[:exclude_controllers] = Annotate::Helpers.true?(ENV.fetch('exclude_controllers', 'true'))
options[:exclude_helpers] = Annotate::Helpers.true?(ENV.fetch('exclude_helpers', 'true'))
options[:exclude_sti_subclasses] = Annotate::Helpers.true?(ENV['exclude_sti_subclasses'])
options[:ignore_model_sub_dir] = Annotate::Helpers.true?(ENV['ignore_model_sub_dir'])
options[:format_bare] = Annotate::Helpers.true?(ENV['format_bare'])
options[:format_rdoc] = Annotate::Helpers.true?(ENV['format_rdoc'])
options[:format_yard] = Annotate::Helpers.true?(ENV['format_yard'])
options[:format_markdown] = Annotate::Helpers.true?(ENV['format_markdown'])
options[:sort] = Annotate::Helpers.true?(ENV['sort'])
options[:force] = Annotate::Helpers.true?(ENV['force'])
options[:frozen] = Annotate::Helpers.true?(ENV['frozen'])
options[:classified_sort] = Annotate::Helpers.true?(ENV['classified_sort'])
options[:trace] = Annotate::Helpers.true?(ENV['trace'])
options[:wrapper_open] = Annotate::Helpers.fallback(ENV['wrapper_open'], ENV['wrapper'])
options[:wrapper_close] = Annotate::Helpers.fallback(ENV['wrapper_close'], ENV['wrapper'])
options[:ignore_columns] = ENV.fetch('ignore_columns', nil)
options[:ignore_routes] = ENV.fetch('ignore_routes', nil)
options[:hide_limit_column_types] = Annotate.fallback(ENV['hide_limit_column_types'], '')
options[:hide_default_column_types] = Annotate.fallback(ENV['hide_default_column_types'], '')
options[:with_comment] = Annotate.true?(ENV['with_comment'])
options[:ignore_unknown_models] = Annotate.true?(ENV.fetch('ignore_unknown_models', 'false'))
options[:hide_limit_column_types] = Annotate::Helpers.fallback(ENV['hide_limit_column_types'], '')
options[:hide_default_column_types] = Annotate::Helpers.fallback(ENV['hide_default_column_types'], '')
options[:with_comment] = Annotate::Helpers.true?(ENV['with_comment'])
options[:ignore_unknown_models] = Annotate::Helpers.true?(ENV.fetch('ignore_unknown_models', 'false'))
AnnotateModels.do_annotations(options)
end
......@@ -63,6 +65,6 @@ task remove_annotation: :environment do
options[:model_dir] = ENV['model_dir']
options[:root_dir] = ENV['root_dir']
options[:require] = ENV['require'] ? ENV['require'].split(',') : []
options[:trace] = Annotate.true?(ENV['trace'])
options[:trace] = Annotate::Helpers.true?(ENV['trace'])
AnnotateModels.remove_annotations(options)
end
......@@ -4,7 +4,20 @@
# Append annotations to Rake tasks for ActiveRecord, so annotate automatically gets
# run after doing db:migrate.
%w(db:migrate db:migrate:up db:migrate:down db:migrate:reset db:migrate:redo db:rollback).each do |task|
migration_tasks = %w(db:migrate db:migrate:up db:migrate:down db:migrate:reset db:migrate:redo db:rollback)
if defined?(Rails::Application) && Rails.version.split('.').first.to_i >= 6
require 'active_record'
databases = ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml
ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name|
migration_tasks.concat(%w(db:migrate db:migrate:up db:migrate:down).map { |task| "#{task}:#{spec_name}" })
end
end
migration_tasks.each do |task|
next unless Rake::Task.task_defined?(task)
Rake::Task[task].enhance do
Rake::Task[Rake.application.top_level_tasks.last].enhance do
annotation_options_task = if Rake::Task.task_defined?('app:set_annotation_options')
......@@ -23,11 +36,11 @@ module Annotate
@@working = false
def self.update_annotations
unless @@working || Annotate.skip_on_migration?
unless @@working || Annotate::Helpers.skip_on_migration?
@@working = true
self.update_models if Annotate.include_models?
self.update_routes if Annotate.include_routes?
self.update_models if Annotate::Helpers.include_models?
self.update_routes if Annotate::Helpers.include_routes?
end
end
......
annotate_lib = File.expand_path(File.dirname(File.dirname(__FILE__)))
unless ENV['is_cli']
task :set_annotation_options
task annotate_routes: :set_annotation_options
end
desc "Adds the route map to routes.rb"
task :annotate_routes => :environment do
annotate_lib = File.expand_path(File.dirname(File.dirname(__FILE__)))
require "#{annotate_lib}/annotate/annotate_routes"
options={}
ENV['position'] = options[:position] = Annotate.fallback(ENV['position'], 'before')
options[:position_in_routes] = Annotate.fallback(ENV['position_in_routes'], ENV['position'])
options[:ignore_routes] = Annotate.fallback(ENV['ignore_routes'], nil)
ENV['position'] = options[:position] = Annotate::Helpers.fallback(ENV['position'], 'before')
options[:position_in_routes] = Annotate::Helpers.fallback(ENV['position_in_routes'], ENV['position'])
options[:ignore_routes] = Annotate::Helpers.fallback(ENV['ignore_routes'], nil)
options[:require] = ENV['require'] ? ENV['require'].split(',') : []
options[:wrapper_open] = Annotate.fallback(ENV['wrapper_open'], ENV['wrapper'])
options[:wrapper_close] = Annotate.fallback(ENV['wrapper_close'], ENV['wrapper'])
options[:wrapper_open] = Annotate::Helpers.fallback(ENV['wrapper_open'], ENV['wrapper'])
options[:wrapper_close] = Annotate::Helpers.fallback(ENV['wrapper_close'], ENV['wrapper'])
AnnotateRoutes.do_annotations(options)
end
......
require File.dirname(__FILE__) + '/../spec_helper.rb'
require 'annotate/annotate_routes'
describe AnnotateRoutes do
ROUTE_FILE = 'config/routes.rb'.freeze
ANNOTATION_ADDED = "#{ROUTE_FILE} annotated.".freeze
ANNOTATION_REMOVED = "Removed annotations from #{ROUTE_FILE}.".freeze
FILE_UNCHANGED = "#{ROUTE_FILE} unchanged.".freeze
def mock_file(stubs = {})
@mock_file ||= double(File, stubs)
end
def magic_comments_list_each
[
'# encoding: UTF-8',
'# coding: UTF-8',
'# -*- coding: UTF-8 -*-',
'#encoding: utf-8',
'# encoding: utf-8',
'# -*- encoding : utf-8 -*-',
"# encoding: utf-8\n# frozen_string_literal: true",
"# frozen_string_literal: true\n# encoding: utf-8",
'# frozen_string_literal: true',
'#frozen_string_literal: false',
'# -*- frozen_string_literal : true -*-'
].each { |magic_comment| yield magic_comment }
end
it 'should check if routes.rb exists' do
expect(File).to receive(:exists?).with(ROUTE_FILE).and_return(false)
expect(AnnotateRoutes).to receive(:puts).with("Can't find routes.rb")
AnnotateRoutes.do_annotations
end
describe 'Annotate#example' do
let(:rake_routes_content) do
" Prefix Verb URI Pattern Controller#Action
myaction1 GET /url1(.:format) mycontroller1#action
myaction2 POST /url2(.:format) mycontroller2#action
myaction3 DELETE|GET /url3(.:format) mycontroller3#action\n"
end
before(:each) do
expect(File).to receive(:exists?).with(ROUTE_FILE).and_return(true).at_least(:once)
expect(File).to receive(:read).with(ROUTE_FILE).and_return("").at_least(:once)
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED).at_least(:once)
end
context 'without magic comments' do
before(:each) do
expect(AnnotateRoutes).to receive(:`).with('rake routes').and_return(rake_routes_content)
end
it 'annotate normal' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action\n")
AnnotateRoutes.do_annotations
end
it 'annotate markdown' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("
# ## Route Map
#
# Prefix | Verb | URI Pattern | Controller#Action
# --------- | ---------- | --------------- | --------------------
# myaction1 | GET | /url1(.:format) | mycontroller1#action
# myaction2 | POST | /url2(.:format) | mycontroller2#action
# myaction3 | DELETE-GET | /url3(.:format) | mycontroller3#action\n")
AnnotateRoutes.do_annotations(format_markdown: true)
end
it 'wraps annotation if wrapper is specified' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("
# START
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action
# END\n")
AnnotateRoutes.do_annotations(wrapper_open: 'START', wrapper_close: 'END')
end
end
context 'file with magic comments' do
it 'should not remove magic comments' do
magic_comments_list_each do |magic_comment|
expect(AnnotateRoutes).to receive(:`).with('rake routes')
.and_return("#{magic_comment}\n#{rake_routes_content}")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("
#{magic_comment}
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action\n")
AnnotateRoutes.do_annotations
end
end
it 'annotate markdown' do
magic_comments_list_each do |magic_comment|
expect(AnnotateRoutes).to receive(:`).with('rake routes')
.and_return("#{magic_comment}\n#{rake_routes_content}")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("
#{magic_comment}
# ## Route Map
#
# Prefix | Verb | URI Pattern | Controller#Action
# --------- | ---------- | --------------- | --------------------
# myaction1 | GET | /url1(.:format) | mycontroller1#action
# myaction2 | POST | /url2(.:format) | mycontroller2#action
# myaction3 | DELETE-GET | /url3(.:format) | mycontroller3#action\n")
AnnotateRoutes.do_annotations(format_markdown: true)
end
end
it 'wraps annotation if wrapper is specified' do
magic_comments_list_each do |magic_comment|
expect(AnnotateRoutes).to receive(:`).with('rake routes')
.and_return("#{magic_comment}\n#{rake_routes_content}")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("
#{magic_comment}
# START
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action
# END\n")
AnnotateRoutes.do_annotations(wrapper_open: 'START', wrapper_close: 'END')
end
end
end
end
describe 'When adding' do
before(:each) do
expect(File).to receive(:exists?).with(ROUTE_FILE)
.and_return(true).at_least(:once)
expect(AnnotateRoutes).to receive(:`).with('rake routes')
.and_return('').at_least(:once)
end
it 'should insert annotations if file does not contain annotations' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("\n# == Route Map\n#\n")
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
AnnotateRoutes.do_annotations
end
it 'should insert annotations if file does not contain annotations and ignore routes' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("\n# == Route Map\n#\n")
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
AnnotateRoutes.do_annotations(ignore_routes: 'my_route')
end
it 'should insert annotations if file does not contain annotations and position top' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(@mock_file).to receive(:puts).with("# == Route Map\n#\n")
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
AnnotateRoutes.do_annotations(position_in_routes: 'top')
end
it 'should skip annotations if file does already contain annotation' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("\n# == Route Map\n#\n")
expect(AnnotateRoutes).to receive(:puts).with(FILE_UNCHANGED)
AnnotateRoutes.do_annotations
end
context 'file with magic comments' do
it 'leaves magic comment on top, adds an empty line between magic comment and annotation (position_in_routes :top)' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb')
.and_yield(mock_file).at_least(:once)
magic_comments_list_each do |magic_comment|
expect(File).to receive(:read).with(ROUTE_FILE).and_return("#{magic_comment}\nSomething")
expect(@mock_file).to receive(:puts).with("#{magic_comment}\n\n# == Route Map\n#\n\nSomething\n")
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
AnnotateRoutes.do_annotations(position_in_routes: 'top')
end
end
it 'leaves magic comment on top, adds an empty line between magic comment and annotation (position_in_routes :bottom)' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb')
.and_yield(mock_file).at_least(:once)
magic_comments_list_each do |magic_comment|
expect(File).to receive(:read).with(ROUTE_FILE).and_return("#{magic_comment}\nSomething")
expect(@mock_file).to receive(:puts).with("#{magic_comment}\nSomething\n\n# == Route Map\n#\n")
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
AnnotateRoutes.do_annotations(position_in_routes: 'bottom')
end
end
it 'skips annotations if file does already contain annotation' do
magic_comments_list_each do |magic_comment|
expect(File).to receive(:read).with(ROUTE_FILE)
.and_return("#{magic_comment}\n\n# == Route Map\n#\n")
expect(AnnotateRoutes).to receive(:puts).with(FILE_UNCHANGED)
AnnotateRoutes.do_annotations
end
end
end
end
describe 'When adding with older Rake versions' do
before(:each) do
expect(File).to receive(:exists?).with(ROUTE_FILE).and_return(true)
expect(AnnotateRoutes).to receive(:`).with('rake routes').and_return("(in /bad/line)\ngood line")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
end
it 'should annotate and add a newline!' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("ActionController::Routing...\nfoo")
expect(@mock_file).to receive(:puts).with(/ActionController::Routing...\nfoo\n\n# == Route Map\n#\n# good line\n/)
AnnotateRoutes.do_annotations
end
it 'should not add a newline if there are empty lines' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("ActionController::Routing...\nfoo\n")
expect(@mock_file).to receive(:puts).with(/ActionController::Routing...\nfoo\n\n# == Route Map\n#\n# good line\n/)
AnnotateRoutes.do_annotations
end
end
describe 'When adding with newer Rake versions' do
before(:each) do
expect(File).to receive(:exists?).with(ROUTE_FILE).and_return(true)
expect(AnnotateRoutes).to receive(:`).with('rake routes').and_return("another good line\ngood line")
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_ADDED)
end
it 'should annotate and add a newline!' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("ActionController::Routing...\nfoo")
expect(@mock_file).to receive(:puts).with(/ActionController::Routing...\nfoo\n\n# == Route Map\n#\n# another good line\n# good line\n/)
AnnotateRoutes.do_annotations
end
it 'should not add a newline if there are empty lines' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("ActionController::Routing...\nfoo\n")
expect(@mock_file).to receive(:puts).with(/ActionController::Routing...\nfoo\n\n# == Route Map\n#\n# another good line\n# good line\n/)
AnnotateRoutes.do_annotations
end
it 'should add a timestamp when :timestamp is passed' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return("ActionController::Routing...\nfoo")
expect(@mock_file).to receive(:puts).with(/ActionController::Routing...\nfoo\n\n# == Route Map \(Updated \d{4}-\d{2}-\d{2} \d{2}:\d{2}\)\n#\n# another good line\n# good line\n/)
AnnotateRoutes.do_annotations timestamp: true
end
end
describe 'When removing' do
before(:each) do
expect(File).to receive(:exists?).with(ROUTE_FILE).and_return(true)
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(AnnotateRoutes).to receive(:puts).with(ANNOTATION_REMOVED)
end
it 'should remove trailing annotation and trim trailing newlines, but leave leading newlines alone' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return(<<-EOS
ActionController::Routing...
foo
# == Route Map
#
# another good line
# good line
EOS
)
expect(@mock_file).to receive(:puts).with(<<-EOS
ActionController::Routing...
foo
EOS
)
AnnotateRoutes.remove_annotations
end
it 'should remove prepended annotation and trim leading newlines, but leave trailing newlines alone' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return(<<-EOS
# == Route Map
#
# another good line
# good line
Rails.application.routes.draw do
root 'root#index'
end
EOS
)
expect(@mock_file).to receive(:puts).with(<<-EOS
Rails.application.routes.draw do
root 'root#index'
end
EOS
)
AnnotateRoutes.remove_annotations
end
it 'should not remove custom comments above route map' do
expect(File).to receive(:read).with(ROUTE_FILE).and_return(<<-EOS
# My comment
# == Route Map
#
# another good line
# good line
Rails.application.routes.draw do
root 'root#index'
end
EOS
)
expect(@mock_file).to receive(:puts).with(<<-EOS
# My comment
Rails.application.routes.draw do
root 'root#index'
end
EOS
)
AnnotateRoutes.remove_annotations
end
end
end
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 1
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 1
timeout: 5000
require 'rubygems'
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
# secret_token.rb
TestApp::Application.config.secret_token = '4768b21141022d583b141fde0db7e0b31759321b7fce459963914fdd82db248ea0318d9568030dcde70d404d4e86003ce5f51a7a83c8130842e5a97062b68c3c'
# session_store.rb
TestApp::Application.config.session_store :cookie_store, key: '_session'
# wrap_parameters.rb
ActiveSupport.on_load(:active_record) { self.include_root_in_json = false }
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template.Gemfile and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'sqlite3'
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
PATH
remote: ../../..
specs:
annotate (2.5.0)
activerecord
rake
GEM
remote: https://rubygems.org/
specs:
actionmailer (3.2.8)
actionpack (= 3.2.8)
mail (~> 2.4.4)
actionpack (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.4)
rack (~> 1.4.0)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
sprockets (~> 2.1.3)
activemodel (3.2.8)
activesupport (= 3.2.8)
builder (~> 3.0.0)
activerecord (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
activesupport (3.2.8)
i18n (~> 0.6)
multi_json (~> 1.0)
arel (3.0.2)
builder (3.0.0)
erubis (2.7.0)
hike (1.2.1)
i18n (0.6.0)
journey (1.0.4)
json (1.7.4)
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.19)
multi_json (1.3.6)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack (>= 0.4)
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.2.8)
actionmailer (= 3.2.8)
actionpack (= 3.2.8)
activerecord (= 3.2.8)
activeresource (= 3.2.8)
activesupport (= 3.2.8)
bundler (~> 1.0)
railties (= 3.2.8)
railties (3.2.8)
actionpack (= 3.2.8)
activesupport (= 3.2.8)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
sprockets (2.1.3)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
thor (0.16.0)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.33)
PLATFORMS
ruby
DEPENDENCIES
annotate!
rails (= 3.2.8)
sqlite3
TestApp::Application.configure do
config.action_dispatch.best_standards_support = :builtin
config.active_record.auto_explain_threshold_in_seconds = 0.5
config.active_record.mass_assignment_sanitizer = :strict
config.active_support.deprecation = :log
config.cache_classes = false
config.consider_all_requests_local = true
config.whiny_nils = true
end
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
TestApp::Application.initialize!
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
require 'rails/commands'
#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
TestApp::Application.load_tasks
TestApp::Application.configure do
config.action_dispatch.show_exceptions = false
config.active_record.mass_assignment_sanitizer = :strict
config.active_support.deprecation = :stderr
config.cache_classes = true
config.consider_all_requests_local = true
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
config.whiny_nils = true
end
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
end
require File.expand_path('../boot', __FILE__)
require "active_record/railtie"
require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
end
module TestApp
class Application < Rails::Application
config.assets.enabled = false
end
end
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template..rvmrc and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
if [ "$(type rvm | head -1)" != "rvm is a function" ]; then
# First, make sure we're not in 'sh' mode (I.E. strict-superset-of-Bourne
# mode), as RVM doesn't like this...
shopt -u -o posix
# Now, load RVM...
source $HOME/.rvm/scripts/rvm
fi
# Now, switch to our preferred Ruby and gemset...
GEMSET=annotate_test_$(basename $(pwd) | perl -pse 's/\.//g')
rvm use --create ${rvm_ruby_string}@${GEMSET}
# Early-out when we just want to wipe the gemsets clean...
if [ "$SKIP_BUNDLER" != "1" ]; then
# ... and make sure everything's up-to-date, that it'll use the right Gemfile,
# etc.
if [ $(which bundle) == "" ]; then
gem install bundler
fi
export BUNDLE_GEMFILE=./Gemfile
# The apparently superfluous --gemfile param is to work around some stupidness
# in Bundler. Specifically it gets very confused about BUNDLE_GEMFILE not
# pointing at an absolute path.
#
# The special-case handling of bin being empty is to support debug workflows
# where the gemset will in fact already be set up, but the binstubs get nuked.
mkdir -p bin
if [ $(($(ls bin | wc -l) + 0)) -eq 0 ]; then
bundle install --binstubs=bin --gemfile ./Gemfile
else
bundle check || bundle install --binstubs=bin --gemfile ./Gemfile
fi
fi
module Annotate
module Validations
module Common
def self.test_commands
'bin/annotate && bin/annotate --routes'
end
def self.verify_output(output)
output.should =~ /Annotated \(1\): Task/
output.should =~ /Route file annotated./
end
def self.verify_files(which_files, test_rig, schema_annotation, routes_annotation, place_before = true)
check_task_model(test_rig, schema_annotation, place_before) if which_files[:model]
check_task_unittest(test_rig, schema_annotation, place_before) if which_files[:test]
check_task_fixture(test_rig, schema_annotation, place_before) if which_files[:fixture]
check_task_factory(test_rig, schema_annotation, place_before) if which_files[:factory]
check_routes(test_rig, routes_annotation, place_before) if which_files[:routes]
end
def self.check_task_model(test_rig, annotation, place_before = true)
model = apply_annotation(test_rig, 'app/models/task.rb', annotation, place_before)
File.read('app/models/task.rb').should == model
end
def self.check_routes(test_rig, annotation, place_before = true)
routes = apply_annotation(test_rig, 'config/routes.rb', annotation, place_before)
File.read('config/routes.rb')
.sub(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/, 'YYYY-MM-DD HH:MM')
.should == routes
end
def self.check_task_unittest(test_rig, annotation, place_before = true)
unittest = apply_annotation(test_rig, 'test/unit/task_test.rb', annotation, place_before)
File.read('test/unit/task_test.rb').should == unittest
end
def self.check_task_modeltest(test_rig, annotation, place_before=true)
unittest = apply_annotation(test_rig, 'test/models/task_test.rb', annotation, place_before)
File.read('test/models/task_test.rb').should == unittest
end
def self.check_task_factory(test_rig, annotation, place_before=true)
fixture = apply_annotation(test_rig, 'test/factories/tasks.rb', annotation, place_before)
File.read('test/factories/tasks.rb').should == fixture
end
def self.check_task_fixture(test_rig, annotation, place_before = true)
fixture = apply_annotation(test_rig, 'test/fixtures/tasks.yml', annotation, place_before)
File.read('test/fixtures/tasks.yml').should == fixture
end
def self.apply_annotation(test_rig, fname, annotation, place_before = true)
corpus = File.read(File.join(test_rig, fname))
if place_before
annotation + "\n" + corpus
else
corpus + "\n" + annotation
end
end
end
end
end
module Annotate
module Validations
class Base
def self.test_commands
Annotate::Validations::Common.test_commands
end
def self.verify_output(output)
Annotate::Validations::Common.verify_output(output)
end
def self.verify_files(test_rig)
Annotate::Validations::Common.verify_files(
{
model: true,
test: true,
fixture: true,
factory: false,
routes: true
}, test_rig, schema_annotation, route_annotation, true
)
end
def self.foo
require 'pry'
require 'pry-coolline'
end
end
end
end
class IntegrationHelper
MIN_RUBY_VERSIONS = {
'rails_5.2.4.1' => '>= 2.2.2',
'rails_6.0.2.1' => '>= 2.5.0'
}.freeze
def self.able_to_run?(file_path, ruby_version)
return false unless ENV['INTEGRATION_TESTS']
file_name = File.basename(file_path)
rails_app = File.basename(file_name, '_spec.rb')
ruby_dependency = MIN_RUBY_VERSIONS[rails_app]
required_version = Gem::Dependency.new('', ruby_dependency)
able_to_run = required_version.match?('', ruby_version)
unless able_to_run
output = "\n" \
"Skipping running the integration test for #{file_name}.\n" \
"The current version of Ruby is #{ruby_version}, " \
"but the integration test requires Ruby #{ruby_dependency}."
puts output
end
able_to_run
end
end
# Smoke test to assure basic functionality works on a variety of Rails versions.
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'spec_helper'
require 'files'
require 'wrong'
require 'rake'
include Files
include Wrong::D
BASEDIR = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
RVM_BIN = `which rvm`.chomp
USING_RVM = (RVM_BIN != '')
CURRENT_RUBY = `rvm-prompt i v p 2>/dev/null`.chomp
ENV['rvm_pretty_print_flag'] = '0'
ENV['BUNDLE_GEMFILE'] = './Gemfile'
describe "annotate inside Rails, using #{CURRENT_RUBY}" do
chosen_scenario = nil
unless ENV['SCENARIO'].blank?
chosen_scenario = File.expand_path(ENV['SCENARIO'])
raise "Can't find specified scenario '#{chosen_scenario}'!" unless File.directory?(chosen_scenario)
end
Annotate::Integration::SCENARIOS.each do |test_rig, base_dir, test_name|
next if chosen_scenario && chosen_scenario != test_rig
it "works under #{test_name}" do
unless USING_RVM
skip 'Must have RVM installed.'
next
end
# Don't proceed if the working copy is dirty!
expect(Annotate::Integration.clean?(test_rig)).to eq(true)
skip 'temporarily ignored until Travis can run them'
Bundler.with_clean_env do
dir base_dir do
temp_dir = Dir.pwd
expect(File.basename(temp_dir)).to eq(base_dir)
# Delete cruft from hands-on debugging...
Annotate::Integration.nuke_cruft(test_rig)
# Copy everything to our test directory...
exclusions = ["#{test_rig}/.", "#{test_rig}/.."]
files = (FileList["#{test_rig}/*", "#{test_rig}/.*"] - exclusions).to_a
# We want to NOT preserve symlinks during this copy...
system("rsync -aL #{files.shelljoin} #{temp_dir.shellescape}")
# By default, rvm_ruby_string isn't inherited over properly, so let's
# make sure it's there so our .rvmrc will work.
ENV['rvm_ruby_string'] = CURRENT_RUBY
require base_dir.to_s # Will get "#{base_dir}.rb"...
klass = "Annotate::Validations::#{base_dir.tr('.', '_').classify}".constantize
Dir.chdir(temp_dir) do
# bash is required by rvm
# the shopt command forces us out of "strict sh" mode
commands = <<-BASH
export AUTOMATED_TEST="#{BASEDIR}";
shopt -u -o posix;
source .rvmrc &&
(bundle check || bundle install) &&
#{klass.test_commands}
BASH
output = `/usr/bin/env bash -c '#{commands}' 2>&1`.chomp
klass.verify_output(output)
klass.verify_files(test_rig)
end
end
end
end
end
end
require 'common_validation'
module Annotate
module Validations
class Rails23WithBundler < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime
# updated_at :datetime
#
RUBY
end
def self.route_annotation
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) {:controller=>"tasks", :action=>"index"}
# POST /tasks(.:format) {:controller=>"tasks", :action=>"create"}
# new_task GET /tasks/new(.:format) {:controller=>"tasks", :action=>"new"}
# edit_task GET /tasks/:id/edit(.:format) {:controller=>"tasks", :action=>"edit"}
# task GET /tasks/:id(.:format) {:controller=>"tasks", :action=>"show"}
# PUT /tasks/:id(.:format) {:controller=>"tasks", :action=>"update"}
# DELETE /tasks/:id(.:format) {:controller=>"tasks", :action=>"destroy"}
#
RUBY
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template.Gemfile and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
source 'https://rubygems.org'
gem 'bundler'
gem 'rake', '~>0.8.7', :require => false
gem 'rails', '~>2.3.14'
gem 'sqlite3'
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
PATH
remote: ../../..
specs:
annotate (2.5.0)
activerecord
rake
GEM
remote: https://rubygems.org/
specs:
actionmailer (2.3.14)
actionpack (= 2.3.14)
actionpack (2.3.14)
activesupport (= 2.3.14)
rack (~> 1.1.0)
activerecord (2.3.14)
activesupport (= 2.3.14)
activeresource (2.3.14)
activesupport (= 2.3.14)
activesupport (2.3.14)
rack (1.1.3)
rails (2.3.14)
actionmailer (= 2.3.14)
actionpack (= 2.3.14)
activerecord (= 2.3.14)
activeresource (= 2.3.14)
activesupport (= 2.3.14)
rake (>= 0.8.3)
rake (0.8.7)
sqlite3 (1.3.5)
PLATFORMS
ruby
DEPENDENCIES
annotate!
bundler
rails (~> 2.3.14)
rake (~> 0.8.7)
sqlite3
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
Rails::GemDependency.add_frozen_gem_path
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => e
if e.message =~ /Could not find RubyGem rails/
$stderr.puts "Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed."
exit 1
else
raise
end
end
class << self
def rubygems_version
Gem::RubyGemsVersion rescue nil
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
min_version = '1.3.2'
require 'rubygems'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
class Rails::Boot
def run
load_initializer
Rails::Initializer.class_eval do
def load_gems
@bundler_loaded ||= Bundler.require :default, Rails.env
end
end
Rails::Initializer.run(:set_load_path)
end
end
Rails.boot!
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 1
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 1
timeout: 5000
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.14' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.frameworks -= [ :active_resource, :action_mailer ]
end
config.cache_classes = false
config.whiny_nils = true
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_view.debug_rjs = true
config.action_mailer.raise_delivery_errors = false
config.cache_classes = true
config.whiny_nils = true
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_controller.allow_forgery_protection = false
config.action_view.cache_template_loading = true
config.action_mailer.delivery_method = :test
# new_rails_defaults.rb
if defined?(ActiveRecord)
ActiveRecord::Base.include_root_in_json = true
ActiveRecord::Base.store_full_sti_class = true
end
ActionController::Routing.generate_best_match = false
ActiveSupport.use_standard_json_time_format = true
ActiveSupport.escape_html_entities_in_json = false
# session_store.rb
ActionController::Base.session = {
:key => '_session',
:secret => 'a61ce930be7219beee70d3e3411e0794d90ab22d12e87a1f7f50c98ad7b08771ed92e72e1a7299c8ec4795d45d566a39e0a0a1f7e7095e2eeb31320a0c5d7ee5'
}
# cookie_verification_secret.rb
ActionController::Base.cookie_verifier_secret = '1b2363a161fbf01041bd9d0b0d9a332e5c7445503c9e89585c8a248698d28054e3918fa77a0206e662629ee9a00d2831949e74801f27ee85ba2116b62b675935';
# Hacks for Ruby 1.9.3...
MissingSourceFile::REGEXPS << [/^cannot load such file -- (.+)$/i, 1]
ActionController::Routing::Routes.draw do |map|
map.resources :tasks
end
class CreateTasks < ActiveRecord::Migration
def self.up
create_table :tasks do |t|
t.string :content
t.timestamps
end
end
def self.down
drop_table :tasks
end
end
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20120816085200) do
create_table "tasks", :force => true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
end
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/console'
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class ActiveSupport::TestCase
end
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
require 'common_validation'
module Annotate
module Validations
class Rails322 < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
RUBY
end
def self.route_annotation
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) tasks#index
# POST /tasks(.:format) tasks#create
# new_task GET /tasks/new(.:format) tasks#new
# edit_task GET /tasks/:id/edit(.:format) tasks#edit
# task GET /tasks/:id(.:format) tasks#show
# PUT /tasks/:id(.:format) tasks#update
# DELETE /tasks/:id(.:format) tasks#destroy
#
RUBY
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template.Gemfile and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
source 'https://rubygems.org'
gem 'rails', '3.2.2'
gem 'sqlite3'
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
PATH
remote: ../../..
specs:
annotate (2.5.0)
activerecord
rake
GEM
remote: https://rubygems.org/
specs:
actionmailer (3.2.2)
actionpack (= 3.2.2)
mail (~> 2.4.0)
actionpack (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.1)
rack (~> 1.4.0)
rack-cache (~> 1.1)
rack-test (~> 0.6.1)
sprockets (~> 2.1.2)
activemodel (3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
activerecord (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
activesupport (3.2.2)
i18n (~> 0.6)
multi_json (~> 1.0)
arel (3.0.2)
builder (3.0.0)
erubis (2.7.0)
hike (1.2.1)
i18n (0.6.0)
journey (1.0.4)
json (1.7.4)
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.19)
multi_json (1.3.6)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack (>= 0.4)
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.2.2)
actionmailer (= 3.2.2)
actionpack (= 3.2.2)
activerecord (= 3.2.2)
activeresource (= 3.2.2)
activesupport (= 3.2.2)
bundler (~> 1.0)
railties (= 3.2.2)
railties (3.2.2)
actionpack (= 3.2.2)
activesupport (= 3.2.2)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
sprockets (2.1.3)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.33)
PLATFORMS
ruby
DEPENDENCIES
annotate!
rails (= 3.2.2)
sqlite3
../../fixtures/rails_32_rakefile
\ No newline at end of file
../../../fixtures/rails_32old_application.rb
\ No newline at end of file
../../../fixtures/rails32_boot.rb
\ No newline at end of file
../../../fixtures/database.yml
\ No newline at end of file
../../../fixtures/rails_32_environment.rb
\ No newline at end of file
../../../../fixtures/rails_32_development.rb
\ No newline at end of file
../../../../fixtures/rails_32_test.rb
\ No newline at end of file
../../../../fixtures/rails32_unified_initializer.rb
\ No newline at end of file
../../../../fixtures/20120816164927_create_tasks.rb
\ No newline at end of file
../../../fixtures/rails_32_schema.rb
\ No newline at end of file
../../../fixtures/rails_32_rails
\ No newline at end of file
../../../fixtures/rails_32_test_helper.rb
\ No newline at end of file
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
require 'common_validation'
module Annotate
module Validations
class Rails328 < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
RUBY
end
def self.route_annotation
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) tasks#index
# POST /tasks(.:format) tasks#create
# new_task GET /tasks/new(.:format) tasks#new
# edit_task GET /tasks/:id/edit(.:format) tasks#edit
# task GET /tasks/:id(.:format) tasks#show
# PUT /tasks/:id(.:format) tasks#update
# DELETE /tasks/:id(.:format) tasks#destroy
#
RUBY
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
../../fixtures/rails_328_gemfile
\ No newline at end of file
../../fixtures/rails_328_gemfile.lock
\ No newline at end of file
../../fixtures/rails_32_rakefile
\ No newline at end of file
class Task < ActiveRecord::Base
attr_accessible :content
end
require File.expand_path('../boot', __FILE__)
require "active_record/railtie"
require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
end
module TestApp
class Application < Rails::Application
config.active_record.whitelist_attributes = true
config.active_support.escape_html_entities_in_json = true
config.assets.enabled = false
end
end
../../../fixtures/rails32_boot.rb
\ No newline at end of file
../../../fixtures/database.yml
\ No newline at end of file
../../../fixtures/rails_32_environment.rb
\ No newline at end of file
../../../../fixtures/rails_32_development.rb
\ No newline at end of file
../../../../fixtures/rails_32_test.rb
\ No newline at end of file
../../../../fixtures/rails32_unified_initializer.rb
\ No newline at end of file
../../../../fixtures/20120816164927_create_tasks.rb
\ No newline at end of file
../../../fixtures/rails_32_schema.rb
\ No newline at end of file
../../../fixtures/rails_32_rails
\ No newline at end of file
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
one:
content: MyString
two:
content: MyString
../../../fixtures/rails_32_test_helper.rb
\ No newline at end of file
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
require 'common_validation'
module Annotate
module Validations
class Rails32AutoloadingFactoryGirl < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
RUBY
end
def self.route_annotation
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) tasks#index
# POST /tasks(.:format) tasks#create
# new_task GET /tasks/new(.:format) tasks#new
# edit_task GET /tasks/:id/edit(.:format) tasks#edit
# task GET /tasks/:id(.:format) tasks#show
# PUT /tasks/:id(.:format) tasks#update
# DELETE /tasks/:id(.:format) tasks#destroy
#
RUBY
end
def self.verify_files(test_rig)
Annotate::Validations::Common.verify_files(
{
model: true,
test: true,
fixture: false,
factory: true,
routes: true
}, test_rig, schema_annotation, route_annotation, true
)
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template.Gemfile and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
source 'https://rubygems.org'
gem 'rails', '3.2.2'
gem 'sqlite3'
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
group :test do
gem 'factory_girl'
gem 'factory_girl_rails'
end
PATH
remote: ../../..
specs:
annotate (2.5.0)
activerecord
rake
GEM
remote: https://rubygems.org/
specs:
actionmailer (3.2.2)
actionpack (= 3.2.2)
mail (~> 2.4.0)
actionpack (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.1)
rack (~> 1.4.0)
rack-cache (~> 1.1)
rack-test (~> 0.6.1)
sprockets (~> 2.1.2)
activemodel (3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
activerecord (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
activesupport (3.2.2)
i18n (~> 0.6)
multi_json (~> 1.0)
arel (3.0.2)
builder (3.0.0)
erubis (2.7.0)
factory_girl (4.0.0)
activesupport (>= 3.0.0)
factory_girl_rails (4.0.0)
factory_girl (~> 4.0.0)
railties (>= 3.0.0)
hike (1.2.1)
i18n (0.6.0)
journey (1.0.4)
json (1.7.4)
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.19)
multi_json (1.3.6)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack (>= 0.4)
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.2.2)
actionmailer (= 3.2.2)
actionpack (= 3.2.2)
activerecord (= 3.2.2)
activeresource (= 3.2.2)
activesupport (= 3.2.2)
bundler (~> 1.0)
railties (= 3.2.2)
railties (3.2.2)
actionpack (= 3.2.2)
activesupport (= 3.2.2)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
sprockets (2.1.3)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.33)
PLATFORMS
ruby
DEPENDENCIES
annotate!
factory_girl
factory_girl_rails
rails (= 3.2.2)
sqlite3
../../fixtures/rails_32_rakefile
\ No newline at end of file
../../../fixtures/rails_32old_application.rb
\ No newline at end of file
../../../fixtures/rails32_boot.rb
\ No newline at end of file
../../../fixtures/database.yml
\ No newline at end of file
../../../fixtures/rails_32_environment.rb
\ No newline at end of file
../../../../fixtures/rails_32_development.rb
\ No newline at end of file
../../../../fixtures/rails_32_test.rb
\ No newline at end of file
../../../../fixtures/rails32_unified_initializer.rb
\ No newline at end of file
TestApp::Application.routes.draw do
resources :tasks
end
../../../../fixtures/20120816164927_create_tasks.rb
\ No newline at end of file
../../../fixtures/rails_32_schema.rb
\ No newline at end of file
../../../fixtures/rails_32_rails
\ No newline at end of file
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :task do
content "MyString"
end
end
../../../fixtures/rails_32_test_helper.rb
\ No newline at end of file
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
require 'common_validation'
module Annotate
module Validations
class Rails32CustomInflection < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
RUBY
end
def self.route_annotation
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) tasks#index
# POST /tasks(.:format) tasks#create
# new_task GET /tasks/new(.:format) tasks#new
# edit_task GET /tasks/:id/edit(.:format) tasks#edit
# task GET /tasks/:id(.:format) tasks#show
# PUT /tasks/:id(.:format) tasks#update
# DELETE /tasks/:id(.:format) tasks#destroy
#
RUBY
end
def self.verify_output(output)
output.should =~ /Annotated \(1\): TASk/
output.should =~ /Route file annotated./
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
../../fixtures/rails_328_gemfile
\ No newline at end of file
../../fixtures/rails_328_gemfile.lock
\ No newline at end of file
../../fixtures/rails_32_rakefile
\ No newline at end of file
class TASk < ActiveRecord::Base
attr_accessible :content
end
../../../fixtures/rails_32old_application.rb
\ No newline at end of file
../../../fixtures/rails32_boot.rb
\ No newline at end of file
../../../fixtures/database.yml
\ No newline at end of file
../../../fixtures/rails_32_environment.rb
\ No newline at end of file
../../../../fixtures/rails_32_development.rb
\ No newline at end of file
../../../../fixtures/rails_32_test.rb
\ No newline at end of file
# secret_token.rb
TestApp::Application.config.secret_token = '4768b21141022d583b141fde0db7e0b31759321b7fce459963914fdd82db248ea0318d9568030dcde70d404d4e86003ce5f51a7a83c8130842e5a97062b68c3c'
# session_store.rb
TestApp::Application.config.session_store :cookie_store, key: '_session'
# wrap_parameters.rb
ActiveSupport.on_load(:active_record) { self.include_root_in_json = false }
# inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
inflect.acronym 'TASk'
end
TestApp::Application.routes.draw do
resources :tasks
end
../../../../fixtures/20120816164927_create_tasks.rb
\ No newline at end of file
../../../fixtures/rails_32_schema.rb
\ No newline at end of file
../../../fixtures/rails_32_rails
\ No newline at end of file
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
one:
content: MyString
two:
content: MyString
../../../fixtures/rails_32_test_helper.rb
\ No newline at end of file
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
require 'common_validation'
module Annotate
module Validations
class Rails32WithAssetPipeline < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
RUBY
end
def self.route_annotation
<<-RUBY
# == Route Map (Updated YYYY-MM-DD HH:MM)
#
# tasks GET /tasks(.:format) tasks#index
# POST /tasks(.:format) tasks#create
# new_task GET /tasks/new(.:format) tasks#new
# edit_task GET /tasks/:id/edit(.:format) tasks#edit
# task GET /tasks/:id(.:format) tasks#show
# PUT /tasks/:id(.:format) tasks#update
# DELETE /tasks/:id(.:format) tasks#destroy
#
RUBY
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template.Gemfile and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
source 'https://rubygems.org'
gem 'rails', '3.2.2'
gem 'sqlite3'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
PATH
remote: ../../..
specs:
annotate (2.5.0)
activerecord
rake
GEM
remote: https://rubygems.org/
specs:
actionmailer (3.2.2)
actionpack (= 3.2.2)
mail (~> 2.4.0)
actionpack (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.1)
rack (~> 1.4.0)
rack-cache (~> 1.1)
rack-test (~> 0.6.1)
sprockets (~> 2.1.2)
activemodel (3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
activerecord (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.2)
activemodel (= 3.2.2)
activesupport (= 3.2.2)
activesupport (3.2.2)
i18n (~> 0.6)
multi_json (~> 1.0)
arel (3.0.2)
builder (3.0.0)
coffee-rails (3.2.2)
coffee-script (>= 2.2.0)
railties (~> 3.2.0)
coffee-script (2.2.0)
coffee-script-source
execjs
coffee-script-source (1.3.3)
erubis (2.7.0)
execjs (1.4.0)
multi_json (~> 1.0)
hike (1.2.1)
i18n (0.6.0)
journey (1.0.4)
json (1.7.4)
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.19)
multi_json (1.3.6)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack (>= 0.4)
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.2.2)
actionmailer (= 3.2.2)
actionpack (= 3.2.2)
activerecord (= 3.2.2)
activeresource (= 3.2.2)
activesupport (= 3.2.2)
bundler (~> 1.0)
railties (= 3.2.2)
railties (3.2.2)
actionpack (= 3.2.2)
activesupport (= 3.2.2)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
sass (3.2.1)
sass-rails (3.2.5)
railties (~> 3.2.0)
sass (>= 3.1.10)
tilt (~> 1.3)
sprockets (2.1.3)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.33)
uglifier (1.2.7)
execjs (>= 0.3.0)
multi_json (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
annotate!
coffee-rails (~> 3.2.1)
rails (= 3.2.2)
sass-rails (~> 3.2.3)
sqlite3
uglifier (>= 1.0.3)
../../fixtures/rails_32_rakefile
\ No newline at end of file
require File.expand_path('../boot', __FILE__)
require "active_record/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
end
module TestApp
class Application < Rails::Application
config.assets.enabled = true
config.assets.version = '1.0'
end
end
../../../fixtures/rails32_boot.rb
\ No newline at end of file
../../../fixtures/database.yml
\ No newline at end of file
../../../fixtures/rails_32_environment.rb
\ No newline at end of file
TestApp::Application.configure do
config.action_dispatch.best_standards_support = :builtin
config.active_record.auto_explain_threshold_in_seconds = 0.5
config.active_record.mass_assignment_sanitizer = :strict
config.active_support.deprecation = :log
config.assets.compress = false
config.assets.debug = true
config.cache_classes = false
config.consider_all_requests_local = true
config.whiny_nils = true
end
../../../../fixtures/rails_32_test.rb
\ No newline at end of file
# secret_token.rb
TestApp::Application.config.secret_token = '4768b21141022d583b141fde0db7e0b31759321b7fce459963914fdd82db248ea0318d9568030dcde70d404d4e86003ce5f51a7a83c8130842e5a97062b68c3c'
# session_store.rb
TestApp::Application.config.session_store :cookie_store, key: '_session'
# wrap_parameters.rb
ActiveSupport.on_load(:action_controller) { wrap_parameters format: [:json] }
ActiveSupport.on_load(:active_record) { self.include_root_in_json = false }
TestApp::Application.routes.draw do
resources :tasks
end
../../../../fixtures/20120816164927_create_tasks.rb
\ No newline at end of file
../../../fixtures/rails_32_schema.rb
\ No newline at end of file
../../../fixtures/rails_32_rails
\ No newline at end of file
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
one:
content: MyString
two:
content: MyString
../../../fixtures/rails_32_test_helper.rb
\ No newline at end of file
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
gem 'rails-observers'
PATH
remote: ../../..
specs:
annotate (2.6.6)
activerecord (>= 3.2, <= 4.3)
rake (~> 10.4)
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.1.1)
actionpack (= 4.1.1)
actionview (= 4.1.1)
mail (~> 2.5.4)
actionpack (4.1.1)
actionview (= 4.1.1)
activesupport (= 4.1.1)
rack (~> 1.5.2)
rack-test (~> 0.6.2)
actionview (4.1.1)
activesupport (= 4.1.1)
builder (~> 3.1)
erubis (~> 2.7.0)
activemodel (4.1.1)
activesupport (= 4.1.1)
builder (~> 3.1)
activerecord (4.1.1)
activemodel (= 4.1.1)
activesupport (= 4.1.1)
arel (~> 5.0.0)
activesupport (4.1.1)
i18n (~> 0.6, >= 0.6.9)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.1)
tzinfo (~> 1.1)
arel (5.0.1.20140414130214)
builder (3.2.2)
coffee-rails (4.0.1)
coffee-script (>= 2.2.0)
railties (>= 4.0.0, < 5.0)
coffee-script (2.3.0)
coffee-script-source
execjs
coffee-script-source (1.9.1)
erubis (2.7.0)
execjs (2.4.0)
hike (1.2.3)
i18n (0.7.0)
jbuilder (2.2.11)
activesupport (>= 3.0.0, < 5)
multi_json (~> 1.2)
jquery-rails (3.1.2)
railties (>= 3.0, < 5.0)
thor (>= 0.14, < 2.0)
json (1.8.2)
mail (2.5.4)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.25.1)
minitest (5.5.1)
multi_json (1.11.0)
polyglot (0.3.5)
rack (1.5.2)
rack-test (0.6.3)
rack (>= 1.0)
rails (4.1.1)
actionmailer (= 4.1.1)
actionpack (= 4.1.1)
actionview (= 4.1.1)
activemodel (= 4.1.1)
activerecord (= 4.1.1)
activesupport (= 4.1.1)
bundler (>= 1.3.0, < 2.0)
railties (= 4.1.1)
sprockets-rails (~> 2.0)
rails-observers (0.1.2)
activemodel (~> 4.0)
railties (4.1.1)
actionpack (= 4.1.1)
activesupport (= 4.1.1)
rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0)
rake (10.4.2)
rdoc (4.2.0)
json (~> 1.4)
sass (3.2.19)
sass-rails (4.0.5)
railties (>= 4.0.0, < 5.0)
sass (~> 3.2.2)
sprockets (~> 2.8, < 3.0)
sprockets-rails (~> 2.0)
sdoc (0.4.1)
json (~> 1.7, >= 1.7.7)
rdoc (~> 4.0)
spring (1.3.3)
sprockets (2.12.3)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sprockets-rails (2.2.4)
actionpack (>= 3.0)
activesupport (>= 3.0)
sprockets (>= 2.8, < 4.0)
sqlite3 (1.3.10)
thor (0.19.1)
thread_safe (0.3.4)
tilt (1.4.1)
treetop (1.4.15)
polyglot (>= 0.3.1)
turbolinks (2.5.3)
coffee-rails
tzinfo (1.2.2)
thread_safe (~> 0.1)
uglifier (2.7.1)
execjs (>= 0.3.0)
json (>= 1.8.0)
PLATFORMS
ruby
DEPENDENCIES
annotate!
coffee-rails (~> 4.0.0)
jbuilder (~> 2.0)
jquery-rails
rails (= 4.1.1)
rails-observers
sass-rails (~> 4.0.3)
sdoc (~> 0.4.0)
spring
sqlite3
turbolinks
uglifier (>= 1.3.0)
# == Schema Information
#
# Table name: events
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime
# updated_at :datetime
#
module Sub1::Sub2::Sub3
class Event < ActiveRecord::Base
end
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime
# updated_at :datetime
#
class Sub1::User < ActiveRecord::Base
end
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# count :integer default(0)
# status :boolean default(FALSE)
# created_at :datetime
# updated_at :datetime
#
class Task < ActiveRecord::Base
enum status: %w(normal active completed)
end
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Rails411
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_rails_4_1_1_session'
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.
development:
secret_key_base: 6c17ffa1446409733e3bc5b3250a56dbbfe8fb1a235c966e89344814abca7c25a23647d3eef49d2a7e7751d501b294cc4a3911549441aa9ddffe45a36f40e96c
test:
secret_key_base: 952ea361989ff7bba92aae19f14cbd4ab5c1fe431a0d28420ab1d14593a4b15c905dffdb26f3ab14108c023540fa89ac9364a98fe48e402602ec01159fa64b91
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :content
t.integer :count, :default => 0
t.boolean :status, :default => 0
t.timestamps
end
end
end
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :content
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :content
t.timestamps
end
end
end
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140705000010) do
create_table "events", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "tasks", force: true do |t|
t.string "content"
t.integer "count", default: 0
t.boolean "status", default: false
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
end
# 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",
'position_in_class' => "before",
'position_in_test' => "before",
'position_in_fixture' => "before",
'position_in_factory' => "before",
'show_foreign_keys' => "true",
'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' => "false",
'force' => "false",
'trace' => "false",
})
end
Annotate.load_tasks
end
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# count :integer default(0)
# status :boolean default(FALSE)
# created_at :datetime
# updated_at :datetime
#
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
gem 'rails-observers'
PATH
remote: ../../..
specs:
annotate (2.6.6)
activerecord (>= 3.2, <= 4.3)
rake (~> 10.4)
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.2.0)
actionpack (= 4.2.0)
actionview (= 4.2.0)
activejob (= 4.2.0)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 1.0, >= 1.0.5)
actionpack (4.2.0)
actionview (= 4.2.0)
activesupport (= 4.2.0)
rack (~> 1.6.0)
rack-test (~> 0.6.2)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.1)
actionview (4.2.0)
activesupport (= 4.2.0)
builder (~> 3.1)
erubis (~> 2.7.0)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.1)
activejob (4.2.0)
activesupport (= 4.2.0)
globalid (>= 0.3.0)
activemodel (4.2.0)
activesupport (= 4.2.0)
builder (~> 3.1)
activerecord (4.2.0)
activemodel (= 4.2.0)
activesupport (= 4.2.0)
arel (~> 6.0)
activesupport (4.2.0)
i18n (~> 0.7)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
arel (6.0.0)
builder (3.2.2)
coffee-rails (4.1.0)
coffee-script (>= 2.2.0)
railties (>= 4.0.0, < 5.0)
coffee-script (2.3.0)
coffee-script-source
execjs
coffee-script-source (1.9.1)
erubis (2.7.0)
execjs (2.4.0)
globalid (0.3.3)
activesupport (>= 4.1.0)
hike (1.2.3)
i18n (0.7.0)
jbuilder (2.2.11)
activesupport (>= 3.0.0, < 5)
multi_json (~> 1.2)
jquery-rails (4.0.3)
rails-dom-testing (~> 1.0)
railties (>= 4.2.0)
thor (>= 0.14, < 2.0)
json (1.8.2)
loofah (2.0.1)
nokogiri (>= 1.5.9)
mail (2.6.3)
mime-types (>= 1.16, < 3)
mime-types (2.4.3)
mini_portile (0.6.2)
minitest (5.5.1)
multi_json (1.11.0)
nokogiri (1.6.6.2)
mini_portile (~> 0.6.0)
rack (1.6.0)
rack-test (0.6.3)
rack (>= 1.0)
rails (4.2.0)
actionmailer (= 4.2.0)
actionpack (= 4.2.0)
actionview (= 4.2.0)
activejob (= 4.2.0)
activemodel (= 4.2.0)
activerecord (= 4.2.0)
activesupport (= 4.2.0)
bundler (>= 1.3.0, < 2.0)
railties (= 4.2.0)
sprockets-rails
rails-deprecated_sanitizer (1.0.3)
activesupport (>= 4.2.0.alpha)
rails-dom-testing (1.0.5)
activesupport (>= 4.2.0.beta, < 5.0)
nokogiri (~> 1.6.0)
rails-deprecated_sanitizer (>= 1.0.1)
rails-html-sanitizer (1.0.1)
loofah (~> 2.0)
rails-observers (0.1.2)
activemodel (~> 4.0)
railties (4.2.0)
actionpack (= 4.2.0)
activesupport (= 4.2.0)
rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0)
rake (10.4.2)
rdoc (4.2.0)
json (~> 1.4)
sass (3.4.13)
sass-rails (5.0.1)
railties (>= 4.0.0, < 5.0)
sass (~> 3.1)
sprockets (>= 2.8, < 4.0)
sprockets-rails (>= 2.0, < 4.0)
tilt (~> 1.1)
sdoc (0.4.1)
json (~> 1.7, >= 1.7.7)
rdoc (~> 4.0)
spring (1.3.3)
sprockets (2.12.3)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sprockets-rails (2.2.4)
actionpack (>= 3.0)
activesupport (>= 3.0)
sprockets (>= 2.8, < 4.0)
sqlite3 (1.3.10)
thor (0.19.1)
thread_safe (0.3.4)
tilt (1.4.1)
turbolinks (2.5.3)
coffee-rails
tzinfo (1.2.2)
thread_safe (~> 0.1)
uglifier (2.7.1)
execjs (>= 0.3.0)
json (>= 1.8.0)
PLATFORMS
ruby
DEPENDENCIES
annotate!
coffee-rails (~> 4.1.0)
jbuilder (~> 2.0)
jquery-rails
rails (= 4.2.0)
rails-observers
sass-rails (~> 5.0)
sdoc (~> 0.4.0)
spring
sqlite3
turbolinks
uglifier (>= 1.3.0)
class NoNamespace < ActiveRecord::Base
enum foo: [:bar, :baz]
end
# == Schema Information
#
# Table name: events
#
# id :integer not null, primary key
# content :string
# created_at :datetime
# updated_at :datetime
#
module Sub1::Sub2::Sub3
class Event < ActiveRecord::Base
end
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# content :string
# created_at :datetime
# updated_at :datetime
#
class Sub1::User < ActiveRecord::Base
end
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string
# count :integer default(0)
# status :boolean default(FALSE)
# created_at :datetime
# updated_at :datetime
#
class Task < ActiveRecord::Base
enum status: %w(normal active completed)
end
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Rails411
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_rails_4_1_1_session'
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.
development:
secret_key_base: 6c17ffa1446409733e3bc5b3250a56dbbfe8fb1a235c966e89344814abca7c25a23647d3eef49d2a7e7751d501b294cc4a3911549441aa9ddffe45a36f40e96c
test:
secret_key_base: 952ea361989ff7bba92aae19f14cbd4ab5c1fe431a0d28420ab1d14593a4b15c905dffdb26f3ab14108c023540fa89ac9364a98fe48e402602ec01159fa64b91
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :content
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :content
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :no_namespaces do |t|
t.integer :foo
t.timestamps
end
end
end
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140705000010) do
create_table "events", force: :cascade do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "tasks", force: :cascade do |t|
t.string "content"
t.integer "count", default: 0
t.boolean "status", default: false
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: :cascade do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
end
# 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",
'position_in_class' => "before",
'position_in_test' => "before",
'position_in_fixture' => "before",
'position_in_factory' => "before",
'show_foreign_keys' => "true",
'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' => "false",
'force' => "false",
'trace' => "false",
})
end
Annotate.load_tasks
end
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string
# count :integer default(0)
# status :boolean default(FALSE)
# created_at :datetime
# updated_at :datetime
#
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
......@@ -12,5 +12,20 @@
/db/*.sqlite3-journal
# Ignore all logfiles and tempfiles.
/log/*.log
/tmp
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep
# Ignore uploaded files in development
/storage/*
!/storage/.keep
/node_modules
/yarn-error.log
/public/assets
.byebug_history
# Ignore master key for decrypting credentials and more.
/config/master.key
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.4', '>= 5.2.4.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 5.6'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
gem 'annotate', path: '../../..'
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
gem 'chromedriver-helper'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
PATH
remote: ../../..
specs:
annotate (3.1.1)
activerecord (>= 3.2, < 8.0)
rake (>= 10.4, < 14.0)
GEM
remote: https://rubygems.org/
specs:
actioncable (5.2.5)
actionpack (= 5.2.5)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)
actionmailer (5.2.5)
actionpack (= 5.2.5)
actionview (= 5.2.5)
activejob (= 5.2.5)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 2.0)
actionpack (5.2.5)
actionview (= 5.2.5)
activesupport (= 5.2.5)
rack (~> 2.0, >= 2.0.8)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (5.2.5)
activesupport (= 5.2.5)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
activejob (5.2.5)
activesupport (= 5.2.5)
globalid (>= 0.3.6)
activemodel (5.2.5)
activesupport (= 5.2.5)
activerecord (5.2.5)
activemodel (= 5.2.5)
activesupport (= 5.2.5)
arel (>= 9.0)
activestorage (5.2.5)
actionpack (= 5.2.5)
activerecord (= 5.2.5)
marcel (~> 1.0.0)
activesupport (5.2.5)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
archive-zip (0.12.0)
io-like (~> 0.3.0)
arel (9.0.0)
bindex (0.8.1)
bootsnap (1.7.3)
msgpack (~> 1.0)
builder (3.2.4)
byebug (11.1.3)
capybara (3.32.2)
addressable
mini_mime (>= 0.1.3)
nokogiri (~> 1.8)
rack (>= 1.6.0)
rack-test (>= 0.6.3)
regexp_parser (~> 1.5)
xpath (~> 3.2)
childprocess (3.0.0)
chromedriver-helper (2.1.1)
archive-zip (~> 0.10)
nokogiri (~> 1.8)
coffee-rails (4.2.2)
coffee-script (>= 2.2.0)
railties (>= 4.0.0)
coffee-script (2.4.1)
coffee-script-source
execjs
coffee-script-source (1.12.2)
concurrent-ruby (1.1.8)
crass (1.0.6)
erubi (1.10.0)
execjs (2.7.0)
ffi (1.15.0)
globalid (0.4.2)
activesupport (>= 4.2.0)
i18n (1.8.10)
concurrent-ruby (~> 1.0)
io-like (0.3.1)
jbuilder (2.11.2)
activesupport (>= 5.0.0)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
loofah (2.9.0)
crass (~> 1.0.2)
nokogiri (>= 1.5.9)
mail (2.7.1)
mini_mime (>= 0.1.1)
marcel (1.0.1)
method_source (1.0.0)
mini_mime (1.0.3)
mini_portile2 (2.4.0)
minitest (5.14.4)
msgpack (1.4.2)
nio4r (2.5.8)
nokogiri (1.10.10)
mini_portile2 (~> 2.4.0)
public_suffix (4.0.6)
puma (5.6.1)
nio4r (~> 2.0)
rack (2.2.3)
rack-test (1.1.0)
rack (>= 1.0, < 3)
rails (5.2.5)
actioncable (= 5.2.5)
actionmailer (= 5.2.5)
actionpack (= 5.2.5)
actionview (= 5.2.5)
activejob (= 5.2.5)
activemodel (= 5.2.5)
activerecord (= 5.2.5)
activestorage (= 5.2.5)
activesupport (= 5.2.5)
bundler (>= 1.3.0)
railties (= 5.2.5)
sprockets-rails (>= 2.0.0)
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
rails-html-sanitizer (1.3.0)
loofah (~> 2.3)
railties (5.2.5)
actionpack (= 5.2.5)
activesupport (= 5.2.5)
method_source
rake (>= 0.8.7)
thor (>= 0.19.0, < 2.0)
rake (13.0.3)
rb-fsevent (0.10.4)
rb-inotify (0.10.1)
ffi (~> 1.0)
regexp_parser (1.8.2)
ruby_dep (1.5.0)
rubyzip (2.3.0)
sass (3.7.4)
sass-listen (~> 4.0.0)
sass-listen (4.0.0)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
sass-rails (5.1.0)
railties (>= 5.2.0)
sass (~> 3.1)
sprockets (>= 2.8, < 4.0)
sprockets-rails (>= 2.0, < 4.0)
tilt (>= 1.1, < 3)
selenium-webdriver (3.142.7)
childprocess (>= 0.5, < 4.0)
rubyzip (>= 1.2.2)
sprockets (3.7.2)
concurrent-ruby (~> 1.0)
rack (> 1, < 3)
sprockets-rails (3.2.2)
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
sqlite3 (1.4.2)
thor (1.1.0)
thread_safe (0.3.6)
tilt (2.0.10)
turbolinks (5.2.1)
turbolinks-source (~> 5.2)
turbolinks-source (5.2.0)
tzinfo (1.2.9)
thread_safe (~> 0.1)
uglifier (4.2.0)
execjs (>= 0.3.0, < 3)
web-console (3.7.0)
actionview (>= 5.0)
activemodel (>= 5.0)
bindex (>= 0.4.0)
railties (>= 5.0)
websocket-driver (0.7.3)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.5)
xpath (3.2.0)
nokogiri (~> 1.8)
PLATFORMS
ruby
DEPENDENCIES
annotate!
bootsnap (>= 1.1.0)
byebug
capybara (>= 2.15)
chromedriver-helper
coffee-rails (~> 4.2)
jbuilder (~> 2.5)
listen (>= 3.0.5, < 3.2)
puma (~> 5.6)
rails (~> 5.2.4, >= 5.2.4.1)
sass-rails (~> 5.0)
selenium-webdriver
sqlite3
turbolinks (~> 5)
tzinfo-data
uglifier (>= 1.3.0)
web-console (>= 3.3.0)
BUNDLED WITH
2.2.15
== README
# README
This README would normally document whatever steps are necessary to get the
application up and running.
......@@ -22,7 +22,3 @@ Things you may want to cover:
* Deployment instructions
* ...
Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require_relative 'config/application'
Rails.application.load_tasks
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
this.App || (this.App = {});
App.cable = ActionCable.createConsumer();
}).call(this);
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
* vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
* files in this directory. Styles in this file should be added after the last require_* statement.
* It is generally better to create a new file per style scope.
*
*= require_tree .
*= require_self
*/
module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
<!DOCTYPE html>
<html>
<head>
<title>Rails5241</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= yield %>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
/* Email styles need to be inline */
</style>
</head>
<body>
<%= yield %>
</body>
</html>
#!/usr/bin/env ruby
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
load Gem.bin_path('bundler', 'bundle')
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative '../config/boot'
require 'rails/commands'
#!/usr/bin/env ruby
require_relative '../config/boot'
require 'rake'
Rake.application.run
#!/usr/bin/env ruby
require 'fileutils'
include FileUtils
# path to your application root.
APP_ROOT = File.expand_path('..', __dir__)
def system!(*args)
system(*args) || abort("\n== Command #{args} failed ==")
end
chdir APP_ROOT do
# This script is a starting point to setup your application.
# Add necessary setup steps to this file.
puts '== Installing dependencies =='
system! 'gem install bundler --conservative'
system('bundle check') || system!('bundle install')
# Install JavaScript dependencies if using Yarn
# system('bin/yarn')
# puts "\n== Copying sample files =="
# unless File.exist?('config/database.yml')
# cp 'config/database.yml.sample', 'config/database.yml'
# end
puts "\n== Preparing database =="
system! 'bin/rails db:setup'
puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear'
puts "\n== Restarting application server =="
system! 'bin/rails restart'
end
#!/usr/bin/env ruby
require 'fileutils'
include FileUtils
# path to your application root.
APP_ROOT = File.expand_path('..', __dir__)
def system!(*args)
system(*args) || abort("\n== Command #{args} failed ==")
end
chdir APP_ROOT do
# This script is a way to update your development environment automatically.
# Add necessary update steps to this file.
puts '== Installing dependencies =='
system! 'gem install bundler --conservative'
system('bundle check') || system!('bundle install')
# Install JavaScript dependencies if using Yarn
# system('bin/yarn')
puts "\n== Updating database =="
system! 'bin/rails db:migrate'
puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear'
puts "\n== Restarting application server =="
system! 'bin/rails restart'
end
#!/usr/bin/env ruby
APP_ROOT = File.expand_path('..', __dir__)
Dir.chdir(APP_ROOT) do
begin
exec "yarnpkg", *ARGV
rescue Errno::ENOENT
$stderr.puts "Yarn executable was not detected in the system."
$stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install"
exit 1
end
end
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
require_relative 'config/environment'
run Rails.application
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Rails5241
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
development:
adapter: async
test:
adapter: async
production:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
channel_prefix: rails_5_2_4_1_production
kaq24JvP21fLJw+1dPA4vJwDDrmXYkK9Z0eGm427byJIzbzyz4/iZOeOaMbmgPus3C1brzeGXrXvH/XObBtrktOftldHzYN9EjYIvip+Z38ep7kv5FhkL2OMlOAJCOkIv0xxyZld6pn6VR6QyJ8GmO/vJh1/k0AMpioQA4QPVi4AZyRxNNlO8UkQ4nidlYBjueoZDTbrKwDUNGwnCfSihDYzWsyNqQfEuvZDjd8UdpPUFDRVkG7TI4EVGfJD2TSmnbm2XCxrfRvSkWL5M7qJavBSJTJ2pUc4sZhmSlVjCBV1nuW+gvl5UC5yABmc2MwnftfwEplXObKdEHIR7y1EQ92KGqsgmoOZTnqEbEbN4jWDI14SS3DDoosu2mROI88R7rWCMjMDmjOlaVELYvzoXYW4hfNBvXvqbb2O--vdG9CDzyXc67QVYu--pSJBykeDMvvx3dUeH5L3ng==
\ No newline at end of file
......@@ -6,7 +6,7 @@
#
default: &default
adapter: sqlite3
pool: 5
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
......
# Load the Rails application.
require File.expand_path('../application', __FILE__)
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
......@@ -9,29 +9,53 @@ Rails.application.configure do
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
......@@ -14,13 +14,13 @@ Rails.application.configure do
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
......@@ -29,37 +29,41 @@ Rails.application.configure do
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "rails_5_2_4_1_#{Rails.env}"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
......@@ -72,12 +76,19 @@ Rails.application.configure do
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
......@@ -12,9 +12,11 @@ Rails.application.configure do
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = 'public, max-age=3600'
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
......@@ -26,6 +28,11 @@ Rails.application.configure do
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory
config.active_storage.service = :test
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
......
# Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )
# Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
# Be sure to restart your server when you modify this file.
Rails.application.config.action_dispatch.cookies_serializer = :json
\ No newline at end of file
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
......@@ -5,10 +5,10 @@
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# self.include_root_in_json = true
# end
......@@ -16,6 +16,16 @@
#
# This would use the information in config/locales/es.yml.
#
# The following keys must be escaped otherwise they will not be retrieved by
# the default I18n backend:
#
# true, false, on, off, yes, no
#
# Instead, surround them with single quotes.
#
# en:
# 'true': 'foo'
#
# To learn more, please read the Rails Internationalization guide
# available at http://guides.rubyonrails.org/i18n.html.
......
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
TestApp::Application.routes.draw do
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :tasks
end
%w[
.ruby-version
.rbenv-vars
tmp/restart.txt
tmp/caching-dev.txt
].each { |path| Spring.watch(path) }
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>
# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
# amazon:
# service: S3
# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
# region: us-east-1
# bucket: your_own_bucket
# Remember not to checkin your GCS keyfile to a repository
# google:
# service: GCS
# project: your_project
# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
# bucket: your_own_bucket
# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
# microsoft:
# service: AzureStorage
# storage_account_name: your_account_name
# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
# container: your_container_name
# mirror:
# service: Mirror
# primary: local
# mirrors: [ amazon, google, microsoft ]
class CreateTasks < ActiveRecord::Migration
class CreateTasks < ActiveRecord::Migration[5.2]
def change
create_table :tasks do |t|
t.string :content
t.integer :count, default: 0
t.boolean :status, default: 0
t.boolean :status, default: false
t.timestamps
end
end
......
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
......@@ -9,12 +8,16 @@
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(:version => 20120816164927) do
create_table "tasks", :force => true do |t|
t.string "content"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
ActiveRecord::Schema.define(version: 2020_02_04_052946) do
create_table "tasks", force: :cascade do |t|
t.string "content"
t.integer "count", default: 0
t.boolean "status", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
{
"name": "rails_5_2_4_1",
"private": true,
"dependencies": {}
}
<!DOCTYPE html>
<html>
<head>
<title>The page you were looking for doesn't exist (404)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.rails-default-error-page {
background-color: #EFEFEF;
color: #2E2F30;
text-align: center;
font-family: arial, sans-serif;
margin: 0;
}
.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}
.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}
.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>
</head>
<body class="rails-default-error-page">
<!-- This file lives in public/404.html -->
<div class="dialog">
<div>
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
<p>If you are the application owner check the logs for more information.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>The change you wanted was rejected (422)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.rails-default-error-page {
background-color: #EFEFEF;
color: #2E2F30;
text-align: center;
font-family: arial, sans-serif;
margin: 0;
}
.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}
.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}
.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>
</head>
<body class="rails-default-error-page">
<!-- This file lives in public/422.html -->
<div class="dialog">
<div>
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
<p>If you are the application owner check the logs for more information.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>We're sorry, but something went wrong (500)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.rails-default-error-page {
background-color: #EFEFEF;
color: #2E2F30;
text-align: center;
font-family: arial, sans-serif;
margin: 0;
}
.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}
.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}
.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>
</head>
<body class="rails-default-error-page">
<!-- This file lives in public/500.html -->
<div class="dialog">
<div>
<h1>We're sorry, but something went wrong.</h1>
</div>
<p>If you are the application owner check the logs for more information.</p>
</div>
</body>
</html>
# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :chrome, screen_size: [1400, 1400]
end
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
one:
content: MyString
count: 1
status: false
two:
content: MyString
count: 1
status: false
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
......
require 'bundler'
require 'rspec'
require 'git'
require_relative 'integration_helper'
describe 'Integration testing on Rails 5.2.4.1', if: IntegrationHelper.able_to_run?(__FILE__, RUBY_VERSION) do
::RAILS_5_2_APP_NAME = 'rails_5.2.4.1'.freeze
::RAILS_5_2_PROJECT_PATH = File.expand_path('../..', __dir__).freeze
::RAILS_5_2_APP_PATH = File.expand_path(RAILS_5_2_APP_NAME, __dir__).freeze
let!(:git) { Git.open(RAILS_5_2_PROJECT_PATH) }
before(:all) do
Bundler.with_clean_env do
Dir.chdir RAILS_5_2_APP_PATH do
puts `bundle install`
puts `bin/rails db:migrate`
end
end
end
after(:each) do
git.reset_hard
end
describe 'annotate --models' do
let(:command) { 'bundle exec annotate --models' }
let(:task_model) do
patch = <<~PATCH
+# == Schema Information
+#
+# Table name: tasks
+#
+# id :integer not null, primary key
+# content :string
+# count :integer default(0)
+# status :boolean default(FALSE)
+# created_at :datetime not null
+# updated_at :datetime not null
+#
PATCH
path = 'app/models/task.rb'
{
path: include(path),
patch: include(patch)
}
end
let(:task_test) do
patch = <<~PATCH
+# == Schema Information
+#
+# Table name: tasks
+#
+# id :integer not null, primary key
+# content :string
+# count :integer default(0)
+# status :boolean default(FALSE)
+# created_at :datetime not null
+# updated_at :datetime not null
+#
PATCH
path = 'test/models/task_test.rb'
{
path: include(path),
patch: include(patch)
}
end
let(:task_fixture) do
patch = <<~PATCH
+# == Schema Information
+#
+# Table name: tasks
+#
+# id :integer not null, primary key
+# content :string
+# count :integer default(0)
+# status :boolean default(FALSE)
+# created_at :datetime not null
+# updated_at :datetime not null
+#
PATCH
path = 'test/fixtures/tasks.yml'
{
path: include(path),
patch: include(patch)
}
end
it 'annotate models' do
Bundler.with_clean_env do
Dir.chdir RAILS_5_2_APP_PATH do
expect(git.diff.any?).to be_falsy
puts `#{command}`
expect(git.diff.entries).to contain_exactly(
an_object_having_attributes(task_model),
an_object_having_attributes(task_test),
an_object_having_attributes(task_fixture)
)
end
end
end
end
describe 'annotate --routes' do
let(:command) { 'bundle exec annotate --routes' }
let(:task_routes) do
task_routes_diff = <<-DIFF
+# == Route Map
+#
+# Prefix Verb URI Pattern Controller#Action
+# tasks GET /tasks(.:format) tasks#index
+# POST /tasks(.:format) tasks#create
+# new_task GET /tasks/new(.:format) tasks#new
+# edit_task GET /tasks/:id/edit(.:format) tasks#edit
+# task GET /tasks/:id(.:format) tasks#show
+# PATCH /tasks/:id(.:format) tasks#update
+# PUT /tasks/:id(.:format) tasks#update
+# DELETE /tasks/:id(.:format) tasks#destroy
DIFF
default_routes_diff = <<-DIFF
+# rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
+# rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
+# rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
+# update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
+# rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
DIFF
path = 'config/routes.rb'
{
path: include(path),
patch: include(task_routes_diff, default_routes_diff)
}
end
it 'annotate routes.rb' do
Bundler.with_clean_env do
Dir.chdir RAILS_5_2_APP_PATH do
expect(git.diff.any?).to be_falsy
puts `#{command}`
expect(git.diff.entries).to contain_exactly(an_object_having_attributes(task_routes))
end
end
end
end
describe 'rails g annotate:install' do
let(:command) { 'bin/rails g annotate:install' }
let(:rake_file_path) { 'lib/tasks/auto_annotate_models.rake' }
it 'generates the rake file' do
Bundler.with_clean_env do
Dir.chdir RAILS_5_2_APP_PATH do
full_path = File.expand_path(rake_file_path)
expect { `#{command}` }.to change { File.exist?(rake_file_path) }.from(false).to(true)
File.delete(full_path)
end
end
end
end
end
......@@ -10,7 +10,27 @@
# Ignore the default SQLite database.
/db/*.sqlite3
/db/*.sqlite3-journal
/db/*.sqlite3-*
# Ignore all logfiles and tempfiles.
/log/*.log
/tmp
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep
# Ignore uploaded files in development.
/storage/*
!/storage/.keep
/public/assets
.byebug_history
# Ignore master key for decrypting credentials and more.
/config/master.key
/public/packs
/public/packs-test
/node_modules
/yarn-error.log
yarn-debug.log*
.yarn-integrity
\ No newline at end of file
inherit_from: .rubocop_todo.yml
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2020-02-01 10:51:52 -1000 using RuboCop version 0.68.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: TreatCommentsAsGroupSeparators, Include.
# Include: **/*.gemfile, **/Gemfile, **/gems.rb
Bundler/OrderedGems:
Exclude:
- 'Gemfile'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, IndentationWidth.
# SupportedStyles: outdent, indent
Layout/AccessModifierIndentation:
Exclude:
- 'bin/bundle'
# Offense count: 6
# Cop supports --auto-correct.
Layout/EmptyLineAfterGuardClause:
Exclude:
- 'bin/bundle'
# Offense count: 1
# Cop supports --auto-correct.
Layout/EmptyLines:
Exclude:
- 'config/environments/development.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: empty_lines, no_empty_lines
Layout/EmptyLinesAroundBlockBody:
Exclude:
- 'db/schema.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets.
# SupportedStyles: space, no_space, compact
# SupportedStylesForEmptyBrackets: space, no_space
Layout/SpaceInsideArrayLiteralBrackets:
Exclude:
- 'config/environments/production.rb'
# Offense count: 1
Metrics/AbcSize:
Max: 18
# Offense count: 1
Metrics/CyclomaticComplexity:
Max: 9
# Offense count: 2
# Configuration parameters: CountComments, ExcludedMethods.
Metrics/MethodLength:
Max: 13
# Offense count: 1
Metrics/PerceivedComplexity:
Max: 9
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AutoCorrect, EnforcedStyle.
# SupportedStyles: nested, compact
Style/ClassAndModuleChildren:
Exclude:
- 'test/channels/application_cable/connection_test.rb'
- 'test/test_helper.rb'
# Offense count: 5
Style/Documentation:
Exclude:
- 'spec/**/*'
- 'test/**/*'
- 'app/helpers/application_helper.rb'
- 'app/mailers/application_mailer.rb'
- 'app/models/application_record.rb'
- 'config/application.rb'
- 'db/migrate/20200201204456_create_tasks.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/ExpandPathArguments:
Exclude:
- 'bin/bundle'
# Offense count: 37
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: when_needed, always, never
Style/FrozenStringLiteralComment:
Enabled: false
# Offense count: 3
# Cop supports --auto-correct.
Style/IfUnlessModifier:
Exclude:
- 'bin/bundle'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: MinDigits, Strict.
Style/NumericLiterals:
Exclude:
- 'db/schema.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/PerlBackrefs:
Exclude:
- 'bin/bundle'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: .
# SupportedStyles: use_perl_names, use_english_names
Style/SpecialGlobalVars:
EnforcedStyle: use_perl_names
# Offense count: 43
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline.
# SupportedStyles: single_quotes, double_quotes
Style/StringLiterals:
Exclude:
- 'bin/bundle'
- 'config/application.rb'
- 'config/environments/production.rb'
- 'config/puma.rb'
- 'db/schema.rb'
- 'test/application_system_test_case.rb'
- 'test/channels/application_cable/connection_test.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: MinSize.
# SupportedStyles: percent, brackets
Style/SymbolArray:
EnforcedStyle: brackets
# Offense count: 40
# Cop supports --auto-correct.
# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
Max: 190
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
# Use Puma as the app server
gem 'puma', '~> 5.6.1'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
gem 'annotate', path: '../../..'
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
PATH
remote: ../../..
specs:
annotate (3.1.1)
activerecord (>= 3.2, < 8.0)
rake (>= 10.4, < 14.0)
GEM
remote: https://rubygems.org/
specs:
actioncable (6.0.2.1)
actionpack (= 6.0.2.1)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)
actionmailbox (6.0.2.1)
actionpack (= 6.0.2.1)
activejob (= 6.0.2.1)
activerecord (= 6.0.2.1)
activestorage (= 6.0.2.1)
activesupport (= 6.0.2.1)
mail (>= 2.7.1)
actionmailer (6.0.2.1)
actionpack (= 6.0.2.1)
actionview (= 6.0.2.1)
activejob (= 6.0.2.1)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 2.0)
actionpack (6.0.2.1)
actionview (= 6.0.2.1)
activesupport (= 6.0.2.1)
rack (~> 2.0, >= 2.0.8)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.2.0)
actiontext (6.0.2.1)
actionpack (= 6.0.2.1)
activerecord (= 6.0.2.1)
activestorage (= 6.0.2.1)
activesupport (= 6.0.2.1)
nokogiri (>= 1.8.5)
actionview (6.0.2.1)
activesupport (= 6.0.2.1)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.1, >= 1.2.0)
activejob (6.0.2.1)
activesupport (= 6.0.2.1)
globalid (>= 0.3.6)
activemodel (6.0.2.1)
activesupport (= 6.0.2.1)
activerecord (6.0.2.1)
activemodel (= 6.0.2.1)
activesupport (= 6.0.2.1)
activestorage (6.0.2.1)
actionpack (= 6.0.2.1)
activejob (= 6.0.2.1)
activerecord (= 6.0.2.1)
marcel (~> 0.3.1)
activesupport (6.0.2.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
zeitwerk (~> 2.2)
addressable (2.8.0)
public_suffix (>= 2.0.2, < 5.0)
bindex (0.8.1)
bootsnap (1.4.5)
msgpack (~> 1.0)
builder (3.2.4)
byebug (11.1.1)
capybara (3.31.0)
addressable
mini_mime (>= 0.1.3)
nokogiri (~> 1.8)
rack (>= 1.6.0)
rack-test (>= 0.6.3)
regexp_parser (~> 1.5)
xpath (~> 3.2)
childprocess (3.0.0)
concurrent-ruby (1.1.8)
crass (1.0.6)
erubi (1.10.0)
ffi (1.15.5)
globalid (0.4.2)
activesupport (>= 4.2.0)
i18n (1.8.10)
concurrent-ruby (~> 1.0)
jbuilder (2.9.1)
activesupport (>= 4.2.0)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
loofah (2.9.0)
crass (~> 1.0.2)
nokogiri (>= 1.5.9)
mail (2.7.1)
mini_mime (>= 0.1.1)
marcel (0.3.3)
mimemagic (~> 0.3.2)
method_source (0.9.2)
mimemagic (0.3.10)
nokogiri (~> 1)
rake
mini_mime (1.0.2)
mini_portile2 (2.5.3)
minitest (5.14.4)
msgpack (1.3.1)
nio4r (2.5.2)
nokogiri (1.11.7)
mini_portile2 (~> 2.5.0)
racc (~> 1.4)
public_suffix (4.0.6)
puma (5.6.1)
nio4r (~> 2.0)
racc (1.5.2)
rack (2.2.3)
rack-test (1.1.0)
rack (>= 1.0, < 3)
rails (6.0.2.1)
actioncable (= 6.0.2.1)
actionmailbox (= 6.0.2.1)
actionmailer (= 6.0.2.1)
actionpack (= 6.0.2.1)
actiontext (= 6.0.2.1)
actionview (= 6.0.2.1)
activejob (= 6.0.2.1)
activemodel (= 6.0.2.1)
activerecord (= 6.0.2.1)
activestorage (= 6.0.2.1)
activesupport (= 6.0.2.1)
bundler (>= 1.3.0)
railties (= 6.0.2.1)
sprockets-rails (>= 2.0.0)
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
rails-html-sanitizer (1.3.0)
loofah (~> 2.3)
railties (6.0.2.1)
actionpack (= 6.0.2.1)
activesupport (= 6.0.2.1)
method_source
rake (>= 0.8.7)
thor (>= 0.20.3, < 2.0)
rake (13.0.3)
rb-fsevent (0.11.0)
rb-inotify (0.10.1)
ffi (~> 1.0)
regexp_parser (1.6.0)
ruby_dep (1.5.0)
rubyzip (2.2.0)
selenium-webdriver (3.142.7)
childprocess (>= 0.5, < 4.0)
rubyzip (>= 1.2.2)
sprockets (4.0.0)
concurrent-ruby (~> 1.0)
rack (> 1, < 3)
sprockets-rails (3.2.1)
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
sqlite3 (1.4.2)
thor (1.0.1)
thread_safe (0.3.6)
tzinfo (1.2.9)
thread_safe (~> 0.1)
web-console (4.0.1)
actionview (>= 6.0.0)
activemodel (>= 6.0.0)
bindex (>= 0.4.0)
railties (>= 6.0.0)
webdrivers (4.2.0)
nokogiri (~> 1.6)
rubyzip (>= 1.3.0)
selenium-webdriver (>= 3.0, < 4.0)
websocket-driver (0.7.1)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.5)
xpath (3.2.0)
nokogiri (~> 1.8)
zeitwerk (2.4.2)
PLATFORMS
ruby
DEPENDENCIES
annotate!
bootsnap (>= 1.4.2)
byebug
capybara (>= 2.15)
jbuilder (~> 2.7)
listen (>= 3.0.5, < 3.2)
puma (~> 5.6.1)
rails (~> 6.0.2, >= 6.0.2.1)
selenium-webdriver
sqlite3 (~> 1.4)
tzinfo-data
web-console (>= 3.3.0)
webdrivers
BUNDLED WITH
2.2.15
== README
# README
This README would normally document whatever steps are necessary to get the
application up and running.
......@@ -22,7 +22,3 @@ Things you may want to cover:
* Deployment instructions
* ...
Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require_relative 'config/application'
Rails.application.load_tasks
//= link_tree ../images
//= link_directory ../stylesheets .css
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
* vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
* files in this directory. Styles in this file should be added after the last require_* statement.
* It is generally better to create a new file per style scope.
*
*= require_tree .
*= require_self
*/
module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
class TaskObserver < ActiveRecord::Observer
end
\ No newline at end of file
class ApplicationController < ActionController::Base
end
class TaskObserver < ActiveRecord::Observer
end
\ No newline at end of file
module ApplicationHelper
end
class ApplicationJob < ActiveJob::Base
# Automatically retry jobs that encountered a deadlock
# retry_on ActiveRecord::Deadlocked
# Most jobs are safe to ignore if the underlying records are no longer available
# discard_on ActiveJob::DeserializationError
end
class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Task < ApplicationRecord
end
<!DOCTYPE html>
<html>
<head>
<title>Rails6021</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all' %>
</head>
<body>
<%= yield %>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
/* Email styles need to be inline */
</style>
</head>
<body>
<%= yield %>
</body>
</html>
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'bundle' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "rubygems"
m = Module.new do
module_function
def invoked_as_script?
File.expand_path($0) == File.expand_path(__FILE__)
end
def env_var_version
ENV["BUNDLER_VERSION"]
end
def cli_arg_version
return unless invoked_as_script? # don't want to hijack other binstubs
return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
bundler_version = nil
update_index = nil
ARGV.each_with_index do |a, i|
if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
bundler_version = a
end
next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
bundler_version = $1 || ">= 0.a"
update_index = i
end
bundler_version
end
def gemfile
gemfile = ENV["BUNDLE_GEMFILE"]
return gemfile if gemfile && !gemfile.empty?
File.expand_path("../../Gemfile", __FILE__)
end
def lockfile
lockfile =
case File.basename(gemfile)
when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
else "#{gemfile}.lock"
end
File.expand_path(lockfile)
end
def lockfile_version
return unless File.file?(lockfile)
lockfile_contents = File.read(lockfile)
return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
Regexp.last_match(1)
end
def bundler_version
@bundler_version ||= begin
env_var_version || cli_arg_version ||
lockfile_version || "#{Gem::Requirement.default}.a"
end
end
def load_bundler!
ENV["BUNDLE_GEMFILE"] ||= gemfile
# must dup string for RG < 1.8 compatibility
activate_bundler(bundler_version.dup)
end
def activate_bundler(bundler_version)
if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0")
bundler_version = "< 2"
end
gem_error = activation_error_handling do
gem "bundler", bundler_version
end
return if gem_error.nil?
require_error = activation_error_handling do
require "bundler/version"
end
return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION))
warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`"
exit 42
end
def activation_error_handling
yield
nil
rescue StandardError, LoadError => e
e
end
end
m.load_bundler!
if m.invoked_as_script?
load Gem.bin_path("bundler", "bundle")
end
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative '../config/boot'
require 'rails/commands'
#!/usr/bin/env ruby
require_relative '../config/boot'
require 'rake'
Rake.application.run
#!/usr/bin/env ruby
require 'fileutils'
# path to your application root.
APP_ROOT = File.expand_path('..', __dir__)
def system!(*args)
system(*args) || abort("\n== Command #{args} failed ==")
end
FileUtils.chdir APP_ROOT do
# This script is a way to setup or update your development environment automatically.
# This script is idempotent, so that you can run it at anytime and get an expectable outcome.
# Add necessary setup steps to this file.
puts '== Installing dependencies =='
system! 'gem install bundler --conservative'
system('bundle check') || system!('bundle install')
# puts "\n== Copying sample files =="
# unless File.exist?('config/database.yml')
# FileUtils.cp 'config/database.yml.sample', 'config/database.yml'
# end
puts "\n== Preparing database =="
system! 'bin/rails db:prepare'
puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear'
puts "\n== Restarting application server =="
system! 'bin/rails restart'
end
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
require_relative 'config/environment'
run Rails.application
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Rails6021
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
self.paths['config/database'] = 'config/multi-database.yml' if ENV['MULTI_DB']
end
end
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
development:
adapter: async
test:
adapter: test
production:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
channel_prefix: rails_6_0_2_1_production
p9Ehs8NhqPrCcIMQWQwVqNKvXN0NnrY9Yn6zbHOJXv80LRwTVw+xrcK2pSr0Df3P42D9SQCzCkooDopjCRd3Rd2AGAj5oYybs8//J+YdDKxsEjdB8R2KG7A+fbLlztq2bHoPNvO9wU22fobO8ANxEV5JuqeLyBukcuzztNm5ZHuufp0J2ltSXJuX7rEToELKTob+g+PnecvmwGzTTQzBiZ2jMmaGqWXESXc4Y6VsnBjj1H6Xs/T4OXiq2rLBulV3NR5/orof2GJKV5ohX1U3z0jZzLPUflgDtPvJN4UieTiqpKa9Umibtdd3TOR/aj7uoXj0Tq9FYG3dIMqsWpUb1133zcYzWsyxbC2dXVvpga4/LsQE2/74I+n1WXC5zH30STOYWJpdhEn0S9I4kq+xwzMAJKALI9BzvgZL--9deAjVLbz0BaSSau--9gVti9PVO/wgBKe5nsl8Ow==
\ No newline at end of file
# SQLite version 3.x
# SQLite. Versions 3.8.0 and up are supported.
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
......@@ -6,7 +6,7 @@
#
default: &default
adapter: sqlite3
pool: 5
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
......
# Load the Rails application.
require File.expand_path('../application', __FILE__)
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
......@@ -9,29 +9,47 @@ Rails.application.configure do
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "rails_6_0_2_1_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
......@@ -12,13 +13,16 @@ Rails.application.configure do
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = 'public, max-age=3600'
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
......@@ -26,6 +30,11 @@ Rails.application.configure do
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :test
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
......@@ -34,6 +43,6 @@ Rails.application.configure do
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
end
# Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
# Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Set the nonce only to specific directives
# Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
# Be sure to restart your server when you modify this file.
Rails.application.config.action_dispatch.cookies_serializer = :json
\ No newline at end of file
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
......@@ -5,10 +5,10 @@
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# self.include_root_in_json = true
# end
......@@ -16,8 +16,18 @@
#
# This would use the information in config/locales/es.yml.
#
# The following keys must be escaped otherwise they will not be retrieved by
# the default I18n backend:
#
# true, false, on, off, yes, no
#
# Instead, surround them with single quotes.
#
# en:
# 'true': 'foo'
#
# To learn more, please read the Rails Internationalization guide
# available at http://guides.rubyonrails.org/i18n.html.
# available at https://guides.rubyonrails.org/i18n.html.
en:
hello: "Hello world"
# SQLite. Versions 3.8.0 and up are supported.
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
#
default: &default
adapter: sqlite3
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
primary:
<<: *default
database: db/development.sqlite3
secondary:
<<: *default
database: db/development-secondary.sqlite3
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
primary:
<<: *default
database: db/test.sqlite3
secondary:
<<: *default
database: db/test-secondary.sqlite3
production:
primary:
<<: *default
database: db/production.sqlite3
secondary:
<<: *default
database: db/production-secondary.sqlite3
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
TestApp::Application.routes.draw do
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :tasks
end
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>
# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
# amazon:
# service: S3
# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
# region: us-east-1
# bucket: your_own_bucket
# Remember not to checkin your GCS keyfile to a repository
# google:
# service: GCS
# project: your_project
# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
# bucket: your_own_bucket
# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
# microsoft:
# service: AzureStorage
# storage_account_name: your_account_name
# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
# container: your_container_name
# mirror:
# service: Mirror
# primary: local
# mirrors: [ amazon, google, microsoft ]
class CreateTasks < ActiveRecord::Migration
class CreateTasks < ActiveRecord::Migration[6.0]
def change
create_table :tasks do |t|
t.string :content
t.integer :count, default: 0
t.boolean :status, default: false
t.timestamps
end
......
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_02_01_204456) do
create_table "tasks", force: :cascade do |t|
t.string "content"
t.integer "count", default: 0
t.boolean "status", default: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
end
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
<!DOCTYPE html>
<html>
<head>
<title>The page you were looking for doesn't exist (404)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.rails-default-error-page {
background-color: #EFEFEF;
color: #2E2F30;
text-align: center;
font-family: arial, sans-serif;
margin: 0;
}
.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}
.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}
.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>
</head>
<body class="rails-default-error-page">
<!-- This file lives in public/404.html -->
<div class="dialog">
<div>
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
<p>If you are the application owner check the logs for more information.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>The change you wanted was rejected (422)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.rails-default-error-page {
background-color: #EFEFEF;
color: #2E2F30;
text-align: center;
font-family: arial, sans-serif;
margin: 0;
}
.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}
.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}
.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>
</head>
<body class="rails-default-error-page">
<!-- This file lives in public/422.html -->
<div class="dialog">
<div>
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
<p>If you are the application owner check the logs for more information.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>We're sorry, but something went wrong (500)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.rails-default-error-page {
background-color: #EFEFEF;
color: #2E2F30;
text-align: center;
font-family: arial, sans-serif;
margin: 0;
}
.rails-default-error-page div.dialog {
width: 95%;
max-width: 33em;
margin: 4em auto 0;
}
.rails-default-error-page div.dialog > div {
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #BBB;
border-top: #B00100 solid 4px;
border-top-left-radius: 9px;
border-top-right-radius: 9px;
background-color: white;
padding: 7px 12% 0;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
.rails-default-error-page h1 {
font-size: 100%;
color: #730E15;
line-height: 1.5em;
}
.rails-default-error-page div.dialog > p {
margin: 0 0 1em;
padding: 1em;
background-color: #F7F7F7;
border: 1px solid #CCC;
border-right-color: #999;
border-left-color: #999;
border-bottom-color: #999;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-color: #DADADA;
color: #666;
box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
}
</style>
</head>
<body class="rails-default-error-page">
<!-- This file lives in public/500.html -->
<div class="dialog">
<div>
<h1>We're sorry, but something went wrong.</h1>
</div>
<p>If you are the application owner check the logs for more information.</p>
</div>
</body>
</html>
# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :chrome, screen_size: [1400, 1400]
end
require "test_helper"
class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
# test "connects with cookies" do
# cookies.signed[:user_id] = 42
#
# connect
#
# assert_equal connection.user_id, "42"
# end
end
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
one:
content: MyString
count: 1
status: false
two:
content: MyString
count: 1
status: false
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
......
require 'bundler'
require 'rspec'
require 'git'
require_relative 'integration_helper'
describe 'Integration testing on Rails 6.0.2.1', if: IntegrationHelper.able_to_run?(__FILE__, RUBY_VERSION) do
::RAILS_6_0_APP_NAME = 'rails_6.0.2.1'.freeze
::RAILS_6_0_PROJECT_PATH = File.expand_path('../..', __dir__).freeze
::RAILS_6_0_APP_PATH = File.expand_path(RAILS_6_0_APP_NAME, __dir__).freeze
let!(:git) { Git.open(RAILS_6_0_PROJECT_PATH) }
let(:task_model) do
patch = <<~PATCH
+# == Schema Information
+#
+# Table name: tasks
+#
+# id :integer not null, primary key
+# content :string
+# count :integer default(0)
+# status :boolean default(FALSE)
+# created_at :datetime not null
+# updated_at :datetime not null
+#
PATCH
path = 'app/models/task.rb'
{
path: include(path),
patch: include(patch)
}
end
let(:task_test) do
patch = <<~PATCH
+# == Schema Information
+#
+# Table name: tasks
+#
+# id :integer not null, primary key
+# content :string
+# count :integer default(0)
+# status :boolean default(FALSE)
+# created_at :datetime not null
+# updated_at :datetime not null
+#
PATCH
path = 'test/models/task_test.rb'
{
path: include(path),
patch: include(patch)
}
end
let(:task_fixture) do
patch = <<~PATCH
+# == Schema Information
+#
+# Table name: tasks
+#
+# id :integer not null, primary key
+# content :string
+# count :integer default(0)
+# status :boolean default(FALSE)
+# created_at :datetime not null
+# updated_at :datetime not null
+#
PATCH
path = 'test/fixtures/tasks.yml'
{
path: include(path),
patch: include(patch)
}
end
before(:all) do
Bundler.with_clean_env do
Dir.chdir RAILS_6_0_APP_PATH do
puts `bundle install`
puts `bin/rails db:migrate`
end
end
end
around(:each) do |example|
Bundler.with_clean_env do
Dir.chdir RAILS_6_0_APP_PATH do
example.run
end
end
end
after(:each) do
git.reset_hard
end
describe 'annotate --models' do
let(:command) { 'bundle exec annotate --models' }
it 'annotate models' do
expect(git.diff.any?).to be_falsy
puts `#{command}`
expect(git.diff.entries).to contain_exactly(
an_object_having_attributes(task_model),
an_object_having_attributes(task_test),
an_object_having_attributes(task_fixture)
)
end
end
describe 'annotate --routes' do
let(:command) { 'bundle exec annotate --routes' }
let(:task_routes) do
task_routes_diff = <<-DIFF
+# == Route Map
+#
+# Prefix Verb URI Pattern Controller#Action
+# tasks GET /tasks(.:format) tasks#index
+# POST /tasks(.:format) tasks#create
+# new_task GET /tasks/new(.:format) tasks#new
+# edit_task GET /tasks/:id/edit(.:format) tasks#edit
+# task GET /tasks/:id(.:format) tasks#show
+# PATCH /tasks/:id(.:format) tasks#update
+# PUT /tasks/:id(.:format) tasks#update
+# DELETE /tasks/:id(.:format) tasks#destroy
DIFF
default_routes_diff = <<-DIFF
+# rails_mandrill_inbound_emails POST /rails/action_mailbox/mandrill/inbound_emails(.:format) action_mailbox/ingresses/mandrill/inbound_emails#create
+# rails_postmark_inbound_emails POST /rails/action_mailbox/postmark/inbound_emails(.:format) action_mailbox/ingresses/postmark/inbound_emails#create
+# rails_relay_inbound_emails POST /rails/action_mailbox/relay/inbound_emails(.:format) action_mailbox/ingresses/relay/inbound_emails#create
+# rails_sendgrid_inbound_emails POST /rails/action_mailbox/sendgrid/inbound_emails(.:format) action_mailbox/ingresses/sendgrid/inbound_emails#create
+# rails_mailgun_inbound_emails POST /rails/action_mailbox/mailgun/inbound_emails/mime(.:format) action_mailbox/ingresses/mailgun/inbound_emails#create
+# rails_conductor_inbound_emails GET /rails/conductor/action_mailbox/inbound_emails(.:format) rails/conductor/action_mailbox/inbound_emails#index
+# POST /rails/conductor/action_mailbox/inbound_emails(.:format) rails/conductor/action_mailbox/inbound_emails#create
+# new_rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/new(.:format) rails/conductor/action_mailbox/inbound_emails#new
+# edit_rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/:id/edit(.:format) rails/conductor/action_mailbox/inbound_emails#edit
+# rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#show
+# PATCH /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#update
+# PUT /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#update
+# DELETE /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#destroy
+# rails_conductor_inbound_email_reroute POST /rails/conductor/action_mailbox/:inbound_email_id/reroute(.:format) rails/conductor/action_mailbox/reroutes#create
+# rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
+# rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
+# rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
+# update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
+# rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
DIFF
path = 'config/routes.rb'
{
path: include(path),
patch: include(task_routes_diff, default_routes_diff)
}
end
it 'annotate routes.rb' do
expect(git.diff.any?).to be_falsy
puts `#{command}`
expect(git.diff.entries).to contain_exactly(an_object_having_attributes(task_routes))
end
end
describe 'rails g annotate:install' do
let(:command) { 'bin/rails g annotate:install' }
let(:rake_file_path) { 'lib/tasks/auto_annotate_models.rake' }
let(:full_path) { File.expand_path(rake_file_path) }
after(:each) do
File.delete(full_path)
end
it 'generates the rake file' do
expect { `#{command}` }.to change { File.exist?(rake_file_path) }.from(false).to(true)
end
context 'with multi-db environment' do
let(:migrate_command) { 'bin/rails db:migrate:primary' }
it 'hooks database-specific commands and annotates models' do
expect(git.diff.any?).to be_falsy
system({ 'MULTI_DB' => 'true' }, command)
system({ 'MULTI_DB' => 'true' }, migrate_command)
expect(git.diff.entries).to contain_exactly(
an_object_having_attributes(task_model),
an_object_having_attributes(task_test),
an_object_having_attributes(task_fixture)
)
end
end
end
end
require 'common_validation'
module Annotate
module Validations
class Standalone < Base
def self.schema_annotation
<<-RUBY
# == Schema Information
#
# Table name: tasks
#
# id :integer not null, primary key
# content :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
RUBY
end
def self.test_commands
'bin/annotate --require ./config/init.rb'
end
def self.verify_output(output)
output.should =~ /Annotated \(1\): Task/
end
def self.verify_files(test_rig)
Annotate::Validations::Common.verify_files(
{
model: true,
test: false,
fixture: false,
factory: false,
routes: false
}, test_rig, schema_annotation, nil, true
)
end
end
end
end
../../fixtures/rvmrc.sh
\ No newline at end of file
# This file is a hybrid file meant for live debugging without going through an
# actual RSpec run, and for being used in an RSpec run. To change it, change
# template.Gemfile and run 'rake templates:rebuild' which will do so for all
# templates in all build scenarios.
#
# ALSO, be sure NOT to commit any changes that happen in app/* or config/*
# when debugging this way as that will defeat the point of the automated tests!
#
# In fact, before running RSpec again after manual testing, you should run
# 'rake integration:clober' to reset modified files to their pristine state,
# and remove cruft that may interfere with the build.
source 'https://rubygems.org'
gem 'activerecord', '3.2.8'
gem 'sqlite3'
group :development do
if(ENV['AUTOMATED_TEST'] && ENV['AUTOMATED_TEST'] != '')
gem 'annotate', :path => ENV['AUTOMATED_TEST']
else
gem 'annotate', :path => '../../..'
end
end
PATH
remote: ../../..
specs:
annotate (2.5.0)
activerecord
rake
GEM
remote: https://rubygems.org/
specs:
activemodel (3.2.8)
activesupport (= 3.2.8)
builder (~> 3.0.0)
activerecord (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activesupport (3.2.8)
i18n (~> 0.6)
multi_json (~> 1.0)
arel (3.0.2)
builder (3.0.0)
i18n (0.6.0)
multi_json (1.3.6)
rake (0.9.2.2)
sqlite3 (1.3.6)
tzinfo (0.3.33)
PLATFORMS
ruby
DEPENDENCIES
activerecord (= 3.2.8)
annotate!
sqlite3
class Task < ActiveRecord::Base
attr_accessible :content
end
require 'active_record'
ActiveRecord::Base.establish_connection({
adapter: 'sqlite3',
database: 'db/development.sqlite3',
pool: 1,
timeout: 5000
})
../../../fixtures/rails_32_schema.rb
\ No newline at end of file
require_relative '../../../spec_helper'
require 'annotate/annotate_models'
describe AnnotateModels::FilePatterns do
describe '.by_pattern' do
subject { AnnotateModels::FilePatterns.generate(root_directory, pattern_type, options) }
let(:root_directory) { '/root' }
let(:options) { {} }
context 'when pattern_type is "test"' do
let(:pattern_type) { 'test' }
it 'returns patterns of test files' do
is_expected.to eq([
'/root/test/unit/%MODEL_NAME%_test.rb',
'/root/test/models/%MODEL_NAME%_test.rb',
'/root/spec/models/%MODEL_NAME%_spec.rb'
])
end
end
context 'when pattern_type is "fixture"' do
let(:pattern_type) { 'fixture' }
it 'returns patterns of fixture files' do
is_expected.to eq([
'/root/test/fixtures/%TABLE_NAME%.yml',
'/root/spec/fixtures/%TABLE_NAME%.yml',
'/root/test/fixtures/%PLURALIZED_MODEL_NAME%.yml',
'/root/spec/fixtures/%PLURALIZED_MODEL_NAME%.yml'
])
end
end
context 'when pattern_type is "scaffold"' do
let(:pattern_type) { 'scaffold' }
it 'returns patterns of scaffold files' do
is_expected.to eq([
'/root/test/controllers/%PLURALIZED_MODEL_NAME%_controller_test.rb',
'/root/spec/controllers/%PLURALIZED_MODEL_NAME%_controller_spec.rb',
'/root/spec/requests/%PLURALIZED_MODEL_NAME%_spec.rb',
'/root/spec/routing/%PLURALIZED_MODEL_NAME%_routing_spec.rb'
])
end
end
context 'when pattern_type is "factory"' do
let(:pattern_type) { 'factory' }
it 'returns patterns of factory files' do
is_expected.to eq([
'/root/test/exemplars/%MODEL_NAME%_exemplar.rb',
'/root/spec/exemplars/%MODEL_NAME%_exemplar.rb',
'/root/test/blueprints/%MODEL_NAME%_blueprint.rb',
'/root/spec/blueprints/%MODEL_NAME%_blueprint.rb',
'/root/test/factories/%MODEL_NAME%_factory.rb',
'/root/spec/factories/%MODEL_NAME%_factory.rb',
'/root/test/factories/%TABLE_NAME%.rb',
'/root/spec/factories/%TABLE_NAME%.rb',
'/root/test/factories/%PLURALIZED_MODEL_NAME%.rb',
'/root/spec/factories/%PLURALIZED_MODEL_NAME%.rb',
'/root/test/fabricators/%MODEL_NAME%_fabricator.rb',
'/root/spec/fabricators/%MODEL_NAME%_fabricator.rb'
])
end
end
context 'when pattern_type is "serializer"' do
let(:pattern_type) { 'serializer' }
it 'returns patterns of serializer files' do
is_expected.to eq([
'/root/app/serializers/%MODEL_NAME%_serializer.rb',
'/root/test/serializers/%MODEL_NAME%_serializer_test.rb',
'/root/spec/serializers/%MODEL_NAME%_serializer_spec.rb'
])
end
end
context 'when pattern_type is "additional_file_patterns"' do
let(:pattern_type) { 'additional_file_patterns' }
context 'when additional_file_patterns is specified in the options' do
let(:additional_file_patterns) do
[
'%PLURALIZED_MODEL_NAME%/**/*.rb',
'%PLURALIZED_MODEL_NAME%/*_form'
]
end
let(:options) { { additional_file_patterns: additional_file_patterns } }
it 'returns additional_file_patterns in the argument "options"' do
is_expected.to eq(additional_file_patterns)
end
end
context 'when additional_file_patterns is not specified in the options' do
let(:options) { {} }
it 'returns an empty array' do
is_expected.to eq([])
end
end
end
context 'when pattern_type is "controller"' do
let(:pattern_type) { 'controller' }
it 'returns patterns of controller files' do
is_expected.to eq([
'/root/app/controllers/%PLURALIZED_MODEL_NAME%_controller.rb'
])
end
end
context 'when pattern_type is "admin"' do
let(:pattern_type) { 'admin' }
it 'returns both singular and pluralized model names' do
is_expected.to eq(['/root/app/admin/%MODEL_NAME%.rb', '/root/app/admin/%PLURALIZED_MODEL_NAME%.rb'])
end
end
context 'when pattern_type is "helper"' do
let(:pattern_type) { 'helper' }
it 'returns patterns of helper files' do
is_expected.to eq([
'/root/app/helpers/%PLURALIZED_MODEL_NAME%_helper.rb'
])
end
end
end
end
This source diff could not be displayed because it is too large. You can view the blob instead.
require_relative '../../spec_helper'
require 'annotate/annotate_routes'
describe AnnotateRoutes do
ROUTE_FILE = 'config/routes.rb'.freeze
MESSAGE_ANNOTATED = "#{ROUTE_FILE} was annotated.".freeze
MESSAGE_UNCHANGED = "#{ROUTE_FILE} was not changed.".freeze
MESSAGE_NOT_FOUND = "#{ROUTE_FILE} could not be found.".freeze
MESSAGE_REMOVED = "Annotations were removed from #{ROUTE_FILE}.".freeze
MAGIC_COMMENTS = [
'# encoding: UTF-8',
'# coding: UTF-8',
'# -*- coding: UTF-8 -*-',
'#encoding: utf-8',
'# encoding: utf-8',
'# -*- encoding : utf-8 -*-',
"# encoding: utf-8\n# frozen_string_literal: true",
"# frozen_string_literal: true\n# encoding: utf-8",
'# frozen_string_literal: true',
'#frozen_string_literal: false',
'# -*- frozen_string_literal : true -*-'
].freeze
let :stubs do
{}
end
let :mock_file do
double(File, stubs)
end
describe '.do_annotations' do
context 'When "config/routes.rb" does not exist' do
before :each do
expect(File).to receive(:exist?).with(ROUTE_FILE).and_return(false).once
end
it 'does not annotates any file' do
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_NOT_FOUND)
AnnotateRoutes.do_annotations
end
end
context 'When "config/routes.rb" exists' do
before :each do
expect(File).to receive(:exist?).with(ROUTE_FILE).and_return(true).once
expect(File).to receive(:read).with(ROUTE_FILE).and_return(route_file_content).once
expect(AnnotateRoutes::HeaderGenerator).to receive(:`).with('rake routes').and_return(rake_routes_result).once
end
context 'When the result of `rake routes` is present' do
context 'When the result of `rake routes` does not contain Rake version' do
context 'When the file does not contain magic comment' do
let :rake_routes_result do
<<-EOS
Prefix Verb URI Pattern Controller#Action
myaction1 GET /url1(.:format) mycontroller1#action
myaction2 POST /url2(.:format) mycontroller2#action
myaction3 DELETE|GET /url3(.:format) mycontroller3#action
EOS
end
let :route_file_content do
''
end
context 'When the file does not contain annotation yet' do
context 'When no option is passed' do
let :expected_result do
<<~EOS
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action
EOS
end
it 'annotates normally' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
context 'When the option "format_markdown" is passed' do
let :expected_result do
<<~EOS
# ## Route Map
#
# Prefix | Verb | URI Pattern | Controller#Action
# --------- | ---------- | --------------- | --------------------
# myaction1 | GET | /url1(.:format) | mycontroller1#action
# myaction2 | POST | /url2(.:format) | mycontroller2#action
# myaction3 | DELETE-GET | /url3(.:format) | mycontroller3#action
EOS
end
it 'annotates in Markdown format' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(format_markdown: true)
end
end
context 'When the options "wrapper_open" and "wrapper_close" are passed' do
let :expected_result do
<<~EOS
# START
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action
# END
EOS
end
it 'annotates and wraps annotation with specified words' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(wrapper_open: 'START', wrapper_close: 'END')
end
end
end
end
context 'When the file contains magic comments' do
MAGIC_COMMENTS.each do |magic_comment|
describe "magic comment: #{magic_comment.inspect}" do
let :route_file_content do
<<~EOS
#{magic_comment}
EOS
end
let :rake_routes_result do
<<-EOS
Prefix Verb URI Pattern Controller#Action
myaction1 GET /url1(.:format) mycontroller1#action
myaction2 POST /url2(.:format) mycontroller2#action
myaction3 DELETE|GET /url3(.:format) mycontroller3#action
EOS
end
context 'When the file does not contain annotation yet' do
context 'When no option is passed' do
let :expected_result do
<<~EOS
#{magic_comment}
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action
EOS
end
it 'annotates normally' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
context 'When the option "format_markdown" is passed' do
let :expected_result do
<<~EOS
#{magic_comment}
# ## Route Map
#
# Prefix | Verb | URI Pattern | Controller#Action
# --------- | ---------- | --------------- | --------------------
# myaction1 | GET | /url1(.:format) | mycontroller1#action
# myaction2 | POST | /url2(.:format) | mycontroller2#action
# myaction3 | DELETE-GET | /url3(.:format) | mycontroller3#action
EOS
end
it 'annotates in Markdown format' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(format_markdown: true)
end
end
context 'When the options "wrapper_open" and "wrapper_close" are passed' do
let :expected_result do
<<~EOS
#{magic_comment}
# START
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# myaction1 GET /url1(.:format) mycontroller1#action
# myaction2 POST /url2(.:format) mycontroller2#action
# myaction3 DELETE|GET /url3(.:format) mycontroller3#action
# END
EOS
end
it 'annotates and wraps annotation with specified words' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(wrapper_open: 'START', wrapper_close: 'END')
end
end
end
end
end
end
end
context 'When the result of `rake routes` contains Rake version' do
context 'with older Rake versions' do
let :rake_routes_result do
<<~EOS.chomp
(in /bad/line)
good line
EOS
end
context 'When the route file does not end with an empty line' do
let :route_file_content do
<<~EOS.chomp
ActionController::Routing...
foo
EOS
end
let :expected_result do
<<~EOS
ActionController::Routing...
foo
# == Route Map
#
# good line
EOS
end
it 'annotates with an empty line' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
context 'When the route file ends with an empty line' do
let :route_file_content do
<<~EOS
ActionController::Routing...
foo
EOS
end
let :expected_result do
<<~EOS
ActionController::Routing...
foo
# == Route Map
#
# good line
EOS
end
it 'annotates without an empty line' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
end
context 'with newer Rake versions' do
let :rake_routes_result do
<<~EOS.chomp
another good line
good line
EOS
end
context 'When the route file does not end with an empty line' do
context 'When no option is passed' do
let :route_file_content do
<<~EOS.chomp
ActionController::Routing...
foo
EOS
end
let :expected_result do
<<~EOS
ActionController::Routing...
foo
# == Route Map
#
# another good line
# good line
EOS
end
it 'annotates with an empty line' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
end
context 'When the route file ends with an empty line' do
let :route_file_content do
<<~EOS
ActionController::Routing...
foo
EOS
end
let :expected_result do
<<~EOS
ActionController::Routing...
foo
# == Route Map
#
# another good line
# good line
EOS
end
it 'annotates without an empty line' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
context 'When option "timestamp" is passed' do
let :route_file_content do
<<~EOS.chomp
ActionController::Routing...
foo
EOS
end
let :expected_result do
/ActionController::Routing...\nfoo\n\n# == Route Map \(Updated \d{4}-\d{2}-\d{2} \d{2}:\d{2}\)\n#\n# another good line\n# good line\n/
end
it 'annotates with the timestamp and an empty line' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations timestamp: true
end
end
end
end
end
context 'When the result of `rake routes` is blank' do
let :rake_routes_result do
''
end
context 'When the file does not contain magic comment' do
context 'When the file does not contain annotation yet' do
let :route_file_content do
''
end
context 'When no option is specified' do
let :expected_result do
<<~EOS
# == Route Map
#
EOS
end
it 'inserts annotations' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations
end
end
context 'When the option "ignore_routes" is specified' do
let :expected_result do
<<~EOS
# == Route Map
#
EOS
end
it 'inserts annotations' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(ignore_routes: 'my_route')
end
end
context 'When the option "position_in_routes" is specified as "top"' do
let :expected_result do
<<~EOS
# == Route Map
#
EOS
end
it 'inserts annotations' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(position_in_routes: 'top')
end
end
end
context 'When the file already contains annotation' do
context 'When no option is specified' do
let :route_file_content do
<<~EOS
# == Route Map
#
EOS
end
it 'should skip annotations if file does already contain annotation' do
expect(File).not_to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(mock_file).not_to receive(:puts)
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_UNCHANGED).once
AnnotateRoutes.do_annotations
end
end
end
end
context 'When the file contains magic comments' do
MAGIC_COMMENTS.each do |magic_comment|
describe "magic comment: #{magic_comment.inspect}" do
let :route_file_content do
<<~EOS
#{magic_comment}
Something
EOS
end
context 'When the file does not contain annotation yet' do
context 'When the option "position_in_routes" is specified as "top"' do
let :expected_result do
<<~EOS
#{magic_comment}
# == Route Map
#
Something
EOS
end
it 'leaves magic comment on top and adds an empty line between magic comment and annotation' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(position_in_routes: 'top')
end
end
context 'When the option "position_in_routes" is specified as "bottom"' do
let :expected_result do
<<~EOS
#{magic_comment}
Something
# == Route Map
#
EOS
end
it 'leaves magic comment on top and adds an empty line between magic comment and annotation' do
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_ANNOTATED).once
AnnotateRoutes.do_annotations(position_in_routes: 'bottom')
end
end
end
context 'When the file already contains annotation' do
let :route_file_content do
<<~EOS
#{magic_comment}
# == Route Map
#
EOS
end
it 'skips annotations' do
expect(File).not_to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file)
expect(mock_file).not_to receive(:puts)
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_UNCHANGED).once
AnnotateRoutes.do_annotations
end
end
end
end
end
end
end
end
describe '.remove_annotations' do
before :each do
expect(File).to receive(:exist?).with(ROUTE_FILE).and_return(true).once
expect(File).to receive(:read).with(ROUTE_FILE).and_return(route_file_content).once
expect(File).to receive(:open).with(ROUTE_FILE, 'wb').and_yield(mock_file).once
end
context 'When trailing annotation exists' do
let :route_file_content do
<<~EOS
ActionController::Routing...
foo
# == Route Map
#
# another good line
# good line
EOS
end
let :expected_result do
<<~EOS
ActionController::Routing...
foo
EOS
end
it 'removes trailing annotation and trim trailing newlines, but leave leading newlines alone' do
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_REMOVED).once
AnnotateRoutes.remove_annotations
end
end
context 'When prepended annotation exists' do
let :route_file_content do
<<~EOS
# == Route Map
#
# another good line
# good line
Rails.application.routes.draw do
root 'root#index'
end
EOS
end
let :expected_result do
<<~EOS
Rails.application.routes.draw do
root 'root#index'
end
EOS
end
it 'removes prepended annotation and trim leading newlines, but leave trailing newlines alone' do
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_REMOVED).once
AnnotateRoutes.remove_annotations
end
end
context 'When custom comments are above route map' do
let :route_file_content do
<<~EOS
# My comment
# == Route Map
#
# another good line
# good line
Rails.application.routes.draw do
root 'root#index'
end
EOS
end
let :expected_result do
<<~EOS
# My comment
Rails.application.routes.draw do
root 'root#index'
end
EOS
end
it 'does not remove custom comments above route map' do
expect(mock_file).to receive(:puts).with(expected_result).once
expect(AnnotateRoutes).to receive(:puts).with(MESSAGE_REMOVED).once
AnnotateRoutes.remove_annotations
end
end
end
end
require_relative '../../spec_helper'
RSpec.describe Annotate::Helpers do
describe '.skip_on_migration?' do
subject { described_class.skip_on_migration? }
before do
allow(ENV).to receive(:[]).and_return(nil)
end
it { is_expected.to be_falsy }
context "when ENV['ANNOTATE_SKIP_ON_DB_MIGRATE'] is set" do
let(:key) { 'ANNOTATE_SKIP_ON_DB_MIGRATE' }
let(:env_value) { '1' }
before do
allow(ENV).to receive(:[]).with(key).and_return(env_value)
end
it { is_expected.to be_truthy }
end
context "when ENV['skip_on_db_migrate'] is set" do
let(:key) { 'skip_on_db_migrate' }
let(:env_value) { '1' }
before do
allow(ENV).to receive(:[]).with(key).and_return(env_value)
end
it { is_expected.to be_truthy }
end
end
describe '.include_routes?' do
subject { described_class.include_routes? }
before do
allow(ENV).to receive(:[]).and_return(nil)
end
it { is_expected.to be_falsy }
context "when ENV['routes'] is set" do
let(:key) { 'routes' }
let(:env_value) { '1' }
before do
allow(ENV).to receive(:[]).with(key).and_return(env_value)
end
it { is_expected.to be_truthy }
end
end
describe '.include_models?' do
subject { described_class.include_models? }
before do
allow(ENV).to receive(:[]).and_return(nil)
end
it { is_expected.to be_falsy }
context "when ENV['models'] is set" do
let(:key) { 'models' }
let(:env_value) { '1' }
before do
allow(ENV).to receive(:[]).with(key).and_return(env_value)
end
it { is_expected.to be_truthy }
end
end
describe '.true?' do
subject { described_class.true?(val) }
let(:val) { nil }
it { is_expected.to be_falsy }
context 'when val is blank' do
let(:val) { '' }
it { is_expected.to be_falsy }
end
context 'when it matches the regex' do
valid_truthy_values = %w[true t yes y 1]
valid_truthy_values.each do |truthy_value|
let(:val) { truthy_value }
it "returns truthy for '#{truthy_value}'" do
is_expected.to be_truthy
end
end
end
end
describe '.fallback' do
subject { described_class.fallback(*args) }
let(:args) { [arg_1, arg_2] }
let(:arg_1) { '' } # is considered blank
let(:arg_2) { 'yes' }
it 'returns the first non-blank argument' do
is_expected.to eq(arg_2)
end
context 'when the first argument is non-blank' do
let(:arg_1) { 'yes' }
let(:arg_2) { 'no' }
it { is_expected.to eq(arg_1) }
end
end
describe '.reset_options' do
subject { described_class.reset_options(options) }
let(:options) { [included_option] }
let(:included_option) { :some_key }
let(:excluded_option) { :yet_another_key }
let(:reset_value) { nil }
before do
allow(ENV).to receive(:[]=)
end
it 'resets ENV value' do
expect(ENV).to receive(:[]=).with(included_option.to_s, reset_value)
expect(ENV).to_not receive(:[]=).with(excluded_option.to_s, reset_value)
subject
end
end
end
require_relative '../../spec_helper'
module Annotate # rubocop:disable Metrics/ModuleLength
describe Parser do
before(:example) do
ENV.clear
end
context 'when given empty args' do
it 'returns an options hash with defaults' do
result = Parser.parse([])
expect(result).to be_a(Hash)
expect(result).to include(target_action: :do_annotations)
end
end
%w[--additional-file-patterns].each do |option|
describe option do
it 'sets array of paths to :additional_file_patterns' do
paths = 'foo/bar,baz'
allow(ENV).to receive(:[]=)
Parser.parse([option, paths])
expect(ENV).to have_received(:[]=).with('additional_file_patterns', ['foo/bar', 'baz'])
end
end
end
%w[-d --delete].each do |option|
describe option do
it 'sets target_action to :remove_annotations' do
result = Parser.parse([option])
expect(result).to include(target_action: :remove_annotations)
end
end
end
%w[-p --position].each do |option|
describe option do
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying #{position}" do
it "#{position} position is an option" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(Parser::ANNOTATION_POSITIONS).to include(position)
end
it "sets ENV['position'] to be position" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with('position', position)
end
it 'sets the value in ENV for the different file types' do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
Parser::FILE_TYPE_POSITIONS.each do |file_type|
expect(ENV).to have_received(:[]=).with(file_type, position)
end
end
end
end
end
end
context 'when position_in_class is set to top' do
context 'and when position is a different value' do
it 'does not override' do
other_commands = %w[--pc top]
position_command = %w[-p bottom]
options = other_commands + position_command
Parser.parse(options)
expect(ENV['position_in_class']).to eq('top')
expect(ENV['position']).to eq('bottom')
end
end
end
%w[--pc --position-in-class].each do |option|
describe option do
let(:env_key) { 'position_in_class' }
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying '#{position}'" do
it "sets the ENV variable to '#{position}'" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with(env_key, position)
end
end
end
end
end
%w[--pf --position-in-factory].each do |option|
describe option do
let(:env_key) { 'position_in_factory' }
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying #{position}" do
it "sets the ENV variable to #{position}" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with(env_key, position)
end
end
end
end
end
%w[--px --position-in-fixture].each do |option|
describe option do
let(:env_key) { 'position_in_fixture' }
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying #{position}" do
it "sets the ENV variable to #{position}" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with(env_key, position)
end
end
end
end
end
%w[--pt --position-in-test].each do |option|
describe option do
let(:env_key) { 'position_in_test' }
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying #{position}" do
it "sets the ENV variable to #{position}" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with(env_key, position)
end
end
end
end
end
%w[--pr --position-in-routes].each do |option|
describe option do
let(:env_key) { 'position_in_routes' }
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying #{position}" do
it "sets the ENV variable to #{position}" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with(env_key, position)
end
end
end
end
end
%w[--ps --position-in-serializer].each do |option|
describe option do
let(:env_key) { 'position_in_serializer' }
Parser::ANNOTATION_POSITIONS.each do |position|
context "when specifying #{position}" do
it "sets the ENV variable to #{position}" do
allow(ENV).to receive(:[]=)
Parser.parse([option, position])
expect(ENV).to have_received(:[]=).with(env_key, position)
end
end
end
end
end
%w[--w --wrapper].each do |option|
describe option do
let(:env_key) { 'wrapper' }
let(:set_value) { 'STR' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, set_value])
end
end
end
%w[--wo --wrapper-open].each do |option|
describe option do
let(:env_key) { 'wrapper_open' }
let(:set_value) { 'STR' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, set_value])
end
end
end
%w[--wc --wrapper-close].each do |option|
describe option do
let(:env_key) { 'wrapper_close' }
let(:set_value) { 'STR' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, set_value])
end
end
end
%w[-r --routes].each do |option|
describe option do
let(:env_key) { 'routes' }
let(:set_value) { 'true' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
%w[--models].each do |option|
describe option do
let(:env_key) { 'models' }
let(:set_value) { 'true' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
%w[-a --active-admin].each do |option|
describe option do
let(:env_key) { 'active_admin' }
let(:set_value) { 'true' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
%w[-v --version].each do |option|
describe option do
it 'sets the ENV variable' do
expect { Parser.parse([option]) }.to output("annotate v#{Annotate.version}\n").to_stdout
expect(Parser.parse([option])).to include(exit: true)
end
end
end
%w[-m --show-migration].each do |option|
describe option do
let(:env_key) { 'include_version' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
%w[-k --show-foreign-keys].each do |option|
describe option do
let(:env_key) { 'show_foreign_keys' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
%w[--ck --complete-foreign-keys].each do |option|
describe option do
it 'sets the ENV variable' do
allow(ENV).to receive(:[]=)
Parser.parse([option])
expect(ENV).to have_received(:[]=).with('show_foreign_keys', 'yes')
expect(ENV).to have_received(:[]=).with('show_complete_foreign_keys', 'yes')
end
end
end
%w[-i --show-indexes].each do |option|
describe option do
let(:env_key) { 'show_indexes' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
%w[-s --simple-indexes].each do |option|
describe option do
let(:env_key) { 'simple_indexes' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
describe '--model-dir' do
let(:option) { '--model-dir' }
let(:env_key) { 'model_dir' }
let(:set_value) { 'some_dir/' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, set_value])
end
end
describe '--root-dir' do
let(:option) { '--root-dir' }
let(:env_key) { 'root_dir' }
let(:set_value) { 'some_dir/' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, set_value])
end
end
describe '--ignore-model-subdirects' do
let(:option) { '--ignore-model-subdirects' }
let(:env_key) { 'ignore_model_sub_dir' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
describe '--sort' do
let(:option) { '--sort' }
let(:env_key) { 'sort' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
describe '--classified-sort' do
let(:option) { '--classified-sort' }
let(:env_key) { 'classified_sort' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
%w[-R --require].each do |option|
describe option do
let(:env_key) { 'require' }
let(:set_value) { 'another_dir' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, set_value])
end
context "when ENV['require'] is already set" do
let(:preset_require_value) { 'some_dir/' }
it "appends the path to ENV['require']" do
env = { 'require' => preset_require_value }
expect(ENV).to receive(:[]=).with(env_key, "#{preset_require_value},#{set_value}")
Parser.parse([option, set_value], env)
end
end
end
end
describe 'Parser::EXCLUSION_LIST' do
it "has 'tests'" do
expect(Parser::EXCLUSION_LIST).to include('tests')
end
it "has 'fixtures'" do
expect(Parser::EXCLUSION_LIST).to include('fixtures')
end
it "has 'factories'" do
expect(Parser::EXCLUSION_LIST).to include('factories')
end
it "has 'serializers'" do
expect(Parser::EXCLUSION_LIST).to include('serializers')
end
end
%w[-e --exclude].each do |option|
describe option do
let(:set_value) { 'yes' }
it "sets the exclusion ENV variables for 'tests', 'fixtures', 'factories', and 'serializers'" do
allow(ENV).to receive(:[]=)
Parser.parse([option])
expect(ENV).to have_received(:[]=).with('exclude_tests', set_value)
expect(ENV).to have_received(:[]=).with('exclude_fixtures', set_value)
expect(ENV).to have_received(:[]=).with('exclude_factories', set_value)
expect(ENV).to have_received(:[]=).with('exclude_serializers', set_value)
end
context 'when a type is passed in' do
let(:exclusions) { "tests" }
it "sets the exclusion ENV variable for 'tests' only" do
expect(ENV).to receive(:[]=).with('exclude_tests', set_value)
Parser.parse([option, exclusions])
end
end
context 'when two types are passed in' do
let(:exclusions) { "tests,fixtures" }
it "sets the exclusion ENV variable for 'tests' and 'fixtures'" do
allow(ENV).to receive(:[]=)
Parser.parse([option, exclusions])
expect(ENV).to have_received(:[]=).with('exclude_tests', set_value)
expect(ENV).to have_received(:[]=).with('exclude_fixtures', set_value)
end
end
end
end
%w[-f --format].each do |option|
describe option do
Parser::FORMAT_TYPES.each do |format_type|
context "when passing in format type '#{format_type}'" do
let(:env_key) { "format_#{format_type}" }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option, format_type])
end
end
end
end
end
describe '--force' do
let(:option) { '--force' }
let(:env_key) { 'force' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
describe '--frozen' do
let(:option) { '--frozen' }
let(:env_key) { 'frozen' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
describe '--timestamp' do
let(:option) { '--timestamp' }
let(:env_key) { 'timestamp' }
let(:set_value) { 'true' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
describe '--trace' do
let(:option) { '--trace' }
let(:env_key) { 'trace' }
let(:set_value) { 'yes' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
%w[-I --ignore-columns].each do |option|
describe option do
let(:env_key) { 'ignore_columns' }
let(:regex) { '^(id|updated_at|created_at)' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, regex)
Parser.parse([option, regex])
end
end
end
describe '--ignore-routes' do
let(:option) { '--ignore-routes' }
let(:env_key) { 'ignore_routes' }
let(:regex) { '(mobile|resque|pghero)' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, regex)
Parser.parse([option, regex])
end
end
describe '--hide-limit-column-types' do
let(:option) { '--hide-limit-column-types' }
let(:env_key) { 'hide_limit_column_types' }
let(:values) { 'integer,boolean,text' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, values)
Parser.parse([option, values])
end
end
describe '--hide-default-column-types' do
let(:option) { '--hide-default-column-types' }
let(:env_key) { 'hide_default_column_types' }
let(:values) { 'json,jsonb,hstore' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, values)
Parser.parse([option, values])
end
end
describe '--ignore-unknown-models' do
let(:option) { '--ignore-unknown-models' }
let(:env_key) { 'ignore_unknown_models' }
let(:set_value) { 'true' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
describe '--with-comment' do
let(:option) { '--with-comment' }
let(:env_key) { 'with_comment' }
let(:set_value) { 'true' }
it 'sets the ENV variable' do
expect(ENV).to receive(:[]=).with(env_key, set_value)
Parser.parse([option])
end
end
end
end
require File.dirname(__FILE__) + '/spec_helper.rb'
require_relative '../spec_helper'
describe Annotate do
it 'should have a version' do
expect(Annotate.version).to be_instance_of(String)
describe '.version' do
it 'has version' do
expect(Annotate.version).to be_instance_of(String)
end
end
end
require_relative '../spec_helper'
require_relative '../../spec_helper'
describe 'ActiveRecord migration rake task hooks' do
before do
......
require 'coveralls'
require 'codeclimate-test-reporter'
require 'simplecov'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(
[
Coveralls::SimpleCov::Formatter,
SimpleCov::Formatter::HTMLFormatter,
CodeClimate::TestReporter::Formatter
]
)
SimpleCov.start
if ENV['COVERAGE']
require 'coveralls'
require 'codeclimate-test-reporter'
require 'simplecov'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(
[
Coveralls::SimpleCov::Formatter,
SimpleCov::Formatter::HTMLFormatter,
CodeClimate::TestReporter::Formatter
]
)
SimpleCov.start
end
require 'rubygems'
require 'bundler'
......@@ -18,7 +20,6 @@ Bundler.setup
require 'rake'
require 'rspec'
require 'wrong/adapters/rspec'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '../lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
......@@ -28,65 +29,7 @@ require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/class/subclasses'
require 'active_support/core_ext/string/inflections'
require 'annotate'
require 'annotate/parser'
require 'annotate/helpers'
require 'annotate/constants'
require 'byebug'
module Annotate
module Integration
ABSOLUTE_GEM_ROOT = File.expand_path('../../', __FILE__)
CRUFT_PATTERNS = %w(
%SCENARIO%/bin/*
%SCENARIO%/log/*
%SCENARIO%/tmp/*
%SCENARIO%/.bundle
).freeze
SCENARIO_HOME = File.join(File.dirname(__FILE__), 'integration')
SCENARIOS = Dir.glob("#{SCENARIO_HOME}/*").select do |candidate|
File.directory?(candidate)
end.map do |test_rig|
base_dir = File.basename(test_rig)
[test_rig, base_dir, base_dir.titlecase]
end
def self.nuke_cruft(test_rig)
FileList[
Annotate::Integration::CRUFT_PATTERNS.map do |pattern|
pattern.sub('%SCENARIO%', test_rig)
end
].each do |fname|
FileUtils.rm_rf(fname)
end
end
def self.nuke_all_cruft
SCENARIOS.each do |test_rig, _base_dir, _test_name|
nuke_cruft(test_rig)
end
end
def self.empty_gemset(test_rig)
Dir.chdir(test_rig) do
system('
(
export SKIP_BUNDLER=1
source .rvmrc &&
rvm --force gemset empty
) 2>&1
')
end
end
def self.reset_dirty_files
system("git checkout HEAD -- #{SCENARIO_HOME}/*/")
end
def self.clear_untracked_files
system("git clean -dfx #{SCENARIO_HOME}/*/")
end
def self.clean?(test_rig)
`git status --porcelain #{test_rig}/ | wc -l`.strip.to_i.zero?
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment