Refactor annotate_routes (Reduced offenses).

Reduced the Cyclomatic complexity. #330 By default didn't annotate activeadmin models. This close #330
parent 3e441d14
......@@ -5,6 +5,7 @@
.bundle
.gems
.rbenv-version
.ruby-*
/.idea/
/.rbx
/.rvmrc
......
inherit_from: ./.rubocop_todo.yml
AllCops:
Include:
- '**/Rakefile'
- '**/config.ru'
Exclude:
- 'bin/**/*'
- 'vendor/**/*'
- 'spec/fixtures/**/*'
- 'tmp/**/*'
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2016-01-19 23:50:34 +0100 using RuboCop version 0.36.0.
# on 2016-01-23 17:15:16 +0100 using RuboCop version 0.36.0.
# 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
......@@ -19,12 +19,11 @@ Lint/Debugger:
Exclude:
- 'spec/integration/common_validation.rb'
# Offense count: 7
# Offense count: 6
# Cop supports --auto-correct.
Lint/DeprecatedClassMethods:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/fixtures/rails32_boot.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'
......@@ -36,23 +35,29 @@ Lint/DuplicateMethods:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 2
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AlignWith, SupportedStyles, AutoCorrect.
# SupportedStyles: keyword, variable, start_of_line
Lint/EndAlignment:
Enabled: false
# Offense count: 6
# Offense count: 1
Lint/HandleExceptions:
Exclude:
- 'bin/annotate'
# Offense count: 9
Lint/IneffectiveAccessModifier:
Exclude:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 7
# Offense count: 8
Lint/RescueException:
Exclude:
- 'Rakefile'
- 'bin/annotate'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
......@@ -61,22 +66,12 @@ Lint/ShadowingOuterLocalVariable:
Exclude:
- 'Rakefile'
# Offense count: 4
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: IgnoreEmptyBlocks.
Lint/UnusedBlockArgument:
Exclude:
- 'Rakefile'
- 'spec/spec_helper.rb'
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods.
Lint/UnusedMethodArgument:
Exclude:
- 'lib/annotate/active_record_patch.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/annotate/annotate_models_spec.rb'
- 'bin/annotate'
# Offense count: 2
Lint/UselessAccessModifier:
......@@ -84,91 +79,43 @@ Lint/UselessAccessModifier:
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
# Offense count: 18
# Offense count: 16
Metrics/AbcSize:
Max: 157
Max: 154
# Offense count: 2
Metrics/BlockNesting:
Max: 4
# Offense count: 9
# Offense count: 7
Metrics/CyclomaticComplexity:
Max: 36
# Offense count: 292
# Offense count: 344
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes.
# URISchemes: http, https
Metrics/LineLength:
Max: 276
Max: 543
# Offense count: 23
# Offense count: 24
# Configuration parameters: CountComments.
Metrics/MethodLength:
Max: 85
Max: 83
# Offense count: 2
# Configuration parameters: CountComments.
Metrics/ModuleLength:
Max: 493
Max: 444
# Offense count: 9
# Offense count: 7
Metrics/PerceivedComplexity:
Max: 43
# Offense count: 1
# Cop supports --auto-correct.
Performance/Detect:
Exclude:
- 'Rakefile'
# Offense count: 2
# Cop supports --auto-correct.
Performance/RedundantMatch:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 1
# Cop supports --auto-correct.
Performance/RedundantMerge:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
Performance/StringReplacement:
Exclude:
- 'spec/integration/integration_spec.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: outdent, indent
Style/AccessModifierIndentation:
Enabled: false
# Offense count: 1
Style/AccessorMethodName:
Exclude:
- 'lib/annotate.rb'
# Offense count: 5
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: with_first_parameter, with_fixed_indentation
Style/AlignParameters:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: always, conditionals
Style/AndOr:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
......@@ -189,12 +136,15 @@ Style/BlockDelimiters:
- 'lib/annotate/annotate_models.rb'
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 1
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: braces, no_braces, context_dependent
Style/BracesAroundHashParameters:
Exclude:
- 'bin/annotate'
- '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'
# Offense count: 1
......@@ -209,11 +159,31 @@ Style/CaseEquality:
Style/CaseIndentation:
Enabled: false
# Offense count: 16
# Offense count: 15
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: nested, compact
Style/ClassAndModuleChildren:
Enabled: false
Exclude:
- 'lib/annotate/active_record_patch.rb'
- 'spec/annotate/annotate_models_spec.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:
Exclude:
- 'lib/tasks/migrate.rake'
# Offense count: 2
# Cop supports --auto-correct.
......@@ -229,27 +199,15 @@ Style/CommentAnnotation:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/CommentIndentation:
Exclude:
- 'lib/annotate/annotate_routes.rb'
# Offense count: 2
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: SingleLineConditionsOnly.
Style/ConditionalAssignment:
Exclude:
- 'bin/annotate'
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Cop supports --auto-correct.
Style/DeprecatedHashMethods:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
# Offense count: 6
# Offense count: 8
Style/Documentation:
Exclude:
- 'spec/**/*'
......@@ -257,35 +215,25 @@ Style/Documentation:
- 'lib/annotate.rb'
- 'lib/annotate/active_record_patch.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/file_patterns.rb'
- 'lib/annotate/version.rb'
- 'lib/generators/annotate/install_generator.rb'
- 'lib/tasks/migrate.rake'
# Offense count: 18
# Offense count: 14
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: leading, trailing
Style/DotPosition:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
Style/ElseAlignment:
Exclude:
- 'lib/annotate.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowAdjacentOneLineDefs.
Style/EmptyLineBetweenDefs:
Exclude:
- 'lib/annotate.rb'
# Offense count: 2
# Offense count: 3
# Cop supports --auto-correct.
Style/EmptyLines:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/annotate/annotate_routes_spec.rb'
- 'spec/integration/rails_4.1.1/Gemfile'
- 'spec/integration/rails_4.2.0/Gemfile'
# Offense count: 1
# Cop supports --auto-correct.
......@@ -293,16 +241,15 @@ Style/EmptyLinesAroundAccessModifier:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 31
# Offense count: 22
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: empty_lines, no_empty_lines
Style/EmptyLinesAroundBlockBody:
Exclude:
- 'bin/annotate'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/annotate/annotate_routes_spec.rb'
- 'spec/annotate_spec.rb'
- 'spec/fixtures/rails_32_schema.rb'
- 'spec/integration/rails_2.3_with_bundler/db/schema.rb'
- 'spec/integration/rails_3.2.2/db/schema.rb'
- 'spec/integration/rails_3.2.8/db/schema.rb'
......@@ -313,28 +260,24 @@ Style/EmptyLinesAroundBlockBody:
- 'spec/integration/rails_4.2.0/db/schema.rb'
- 'spec/integration/standalone/db/schema.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: empty_lines, no_empty_lines
Style/EmptyLinesAroundClassBody:
Exclude:
- 'lib/generators/annotate/install_generator.rb'
# Offense count: 24
# Offense count: 25
# Cop supports --auto-correct.
# Configuration parameters: AllowForAlignment, ForceEqualSignAlignment.
Style/ExtraSpacing:
Exclude:
- 'Guardfile'
- 'lib/annotate/annotate_models.rb'
- 'spec/fixtures/rails_32_rails'
- 'lib/annotate/file_patterns.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: 8
......@@ -344,14 +287,14 @@ Style/FormatString:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 5
# Offense count: 4
# Configuration parameters: MinBodyLength.
Style/GuardClause:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 135
# Offense count: 145
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues.
# SupportedStyles: ruby19, ruby19_no_mixed_keys, hash_rockets
......@@ -359,33 +302,27 @@ Style/HashSyntax:
Enabled: false
# Offense count: 1
Style/IfInsideElse:
Exclude:
- 'lib/annotate/annotate_routes.rb'
# Offense count: 5
# Cop supports --auto-correct.
# Configuration parameters: MaxLineLength.
Style/IfUnlessModifier:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
# Offense count: 22
# Offense count: 28
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: special_inside_parentheses, consistent, align_brackets
Style/IndentArray:
Enabled: false
# Offense count: 8
# Offense count: 12
# Cop supports --auto-correct.
# Configuration parameters: SupportedStyles, IndentationWidth.
# SupportedStyles: special_inside_parentheses, consistent, align_braces
Style/IndentHash:
EnforcedStyle: consistent
# Offense count: 3
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: normal, rails
......@@ -394,12 +331,11 @@ Style/IndentationConsistency:
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 9
# Offense count: 8
# Cop supports --auto-correct.
# Configuration parameters: Width.
Style/IndentationWidth:
Exclude:
- 'lib/annotate.rb'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_4.1.1/app/models/sub1/sub2/sub3/event.rb'
- 'spec/integration/rails_4.1.1/app/models/task.rb'
......@@ -425,6 +361,12 @@ Style/MultilineBlockChain:
- 'Rakefile'
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Cop supports --auto-correct.
Style/MultilineIfThen:
Exclude:
- 'annotate.gemspec'
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
......@@ -432,19 +374,17 @@ Style/MultilineBlockChain:
Style/MultilineMethodCallIndentation:
Enabled: false
# Offense count: 19
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth.
# SupportedStyles: aligned, indented
Style/MultilineOperationIndentation:
Enabled: false
# Offense count: 21
# Offense count: 16
# Cop supports --auto-correct.
Style/MutableConstant:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/annotate/annotate_routes_spec.rb'
......@@ -452,26 +392,27 @@ Style/MutableConstant:
- 'spec/integration/rails_2.3_with_bundler/config/environment.rb'
- 'spec/spec_helper.rb'
# Offense count: 6
# Offense count: 3
# Cop supports --auto-correct.
Style/NegatedIf:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/integration_spec.rb'
# Offense count: 3
# Offense count: 1
Style/NestedParenthesizedCalls:
Exclude:
- 'bin/annotate'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles.
# SupportedStyles: skip_modifier_ifs, always
Style/Next:
Exclude:
- 'Rakefile'
- 'lib/annotate/annotate_models.rb'
# Offense count: 10
# Offense count: 9
# Cop supports --auto-correct.
Style/NumericLiterals:
MinDigits: 15
......@@ -482,20 +423,19 @@ Style/ParallelAssignment:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 4
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowSafeAssignment.
Style/ParenthesesAroundCondition:
Exclude:
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'bin/annotate'
# Offense count: 4
# Offense count: 8
# Cop supports --auto-correct.
# Configuration parameters: PreferredDelimiters.
Style/PercentLiteralDelimiters:
Exclude:
- 'Rakefile'
- 'annotate.gemspec'
- 'spec/integration/common_validation.rb'
- 'spec/integration/standalone.rb'
......@@ -527,19 +467,17 @@ Style/RedundantBegin:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 4
# Offense count: 1
# Cop supports --auto-correct.
Style/RedundantParentheses:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
# Offense count: 36
# Offense count: 25
# Cop supports --auto-correct.
# Configuration parameters: AllowMultipleReturnValues.
Style/RedundantReturn:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/annotate/annotate_models_spec.rb'
......@@ -553,12 +491,12 @@ Style/RedundantReturn:
- 'spec/integration/standalone.rb'
- 'spec/spec_helper.rb'
# Offense count: 9
# Offense count: 8
# Cop supports --auto-correct.
Style/RedundantSelf:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/tasks/migrate.rake'
- 'spec/integration/common_validation.rb'
- 'spec/integration/rails_3.2_autoloading_factory_girl.rb'
- 'spec/integration/standalone.rb'
......@@ -573,85 +511,74 @@ Style/RegexpLiteral:
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
# Offense count: 3
# Offense count: 2
# Cop supports --auto-correct.
Style/RescueModifier:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
# Offense count: 2
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: AllowAsExpressionSeparator.
Style/Semicolon:
Exclude:
- 'bin/annotate'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/config/initializers/unified_initializer.rb'
# Offense count: 5
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: only_raise, only_fail, semantic
Style/SignalException:
Exclude:
- 'Rakefile'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/integration_spec.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowIfMethodIsEmpty.
Style/SingleLineMethods:
Exclude:
- 'lib/annotate.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/SpaceAfterComma:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 44
# Offense count: 16
# Cop supports --auto-correct.
Style/SpaceAfterControlKeyword:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/common_validation.rb'
- 'spec/integration/integration_spec.rb'
- '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: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyleInsidePipes, SupportedStyles.
# SupportedStyles: space, no_space
Style/SpaceAroundBlockParameters:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 21
# Offense count: 22
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: space, no_space
Style/SpaceAroundEqualsInParameterDefault:
Enabled: false
# Offense count: 26
# Offense count: 24
# Cop supports --auto-correct.
# Configuration parameters: AllowForAlignment.
Style/SpaceAroundOperators:
Exclude:
- 'Rakefile'
- 'lib/annotate.rb'
- 'bin/annotate'
- 'lib/annotate/annotate_models.rb'
- 'lib/tasks/annotate_models.rake'
- 'lib/tasks/annotate_routes.rake'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/integration_spec.rb'
- 'spec/spec_helper.rb'
# Offense count: 15
# Offense count: 8
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: space, no_space
......@@ -664,7 +591,7 @@ Style/SpaceBeforeComment:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 23
# Offense count: 10
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters.
# SupportedStyles: space, no_space
......@@ -677,7 +604,14 @@ Style/SpaceInsideBrackets:
Exclude:
- 'spec/integration/rails_2.3_with_bundler/config/environment.rb'
# Offense count: 5
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles.
# SupportedStyles: space, no_space
Style/SpaceInsideHashLiteralBraces:
Enabled: false
# Offense count: 4
# Cop supports --auto-correct.
Style/SpaceInsideParens:
Exclude:
......@@ -693,12 +627,12 @@ Style/SpaceInsideStringInterpolation:
# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: SupportedStyles.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: use_perl_names, use_english_names
Style/SpecialGlobalVars:
EnforcedStyle: use_perl_names
Enabled: false
# Offense count: 357
# Offense count: 411
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, ConsistentQuotesInMultiline.
# SupportedStyles: single_quotes, double_quotes
......@@ -718,14 +652,6 @@ Style/SymbolLiteral:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 5
# Cop supports --auto-correct.
# Configuration parameters: IgnoredMethods.
# IgnoredMethods: respond_to
Style/SymbolProc:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 6
# Cop supports --auto-correct.
Style/Tab:
......@@ -735,12 +661,14 @@ Style/Tab:
- '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
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
# SupportedStyles: final_newline, final_blank_line
Style/TrailingBlankLines:
Exclude:
- 'Guardfile'
- 'lib/annotate/file_patterns.rb'
- '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'
......@@ -754,53 +682,39 @@ Style/TrailingCommaInArguments:
Exclude:
- 'spec/annotate/annotate_models_spec.rb'
# Offense count: 11
# Offense count: 12
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyleForMultiline, SupportedStyles.
# SupportedStyles: comma, consistent_comma, no_comma
Style/TrailingCommaInLiteral:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'lib/annotate/file_patterns.rb'
- 'spec/annotate/annotate_models_spec.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'
# Offense count: 3
# Cop supports --auto-correct.
Style/TrailingWhitespace:
Exclude:
- 'lib/annotate.rb'
- 'lib/annotate/annotate_models.rb'
- 'spec/annotate/annotate_models_spec.rb'
- 'spec/integration/rails_2.3_with_bundler/db/schema.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, Whitelist.
# Whitelist: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym
Style/TrivialAccessors:
Exclude:
- 'lib/annotate/annotate_models.rb'
# Offense count: 2
# Offense count: 3
# Cop supports --auto-correct.
Style/UnneededInterpolation:
Exclude:
- 'bin/annotate'
- 'lib/annotate/annotate_routes.rb'
- 'spec/integration/integration_spec.rb'
# Offense count: 7
# Offense count: 11
# Cop supports --auto-correct.
Style/UnneededPercentQ:
Exclude:
- 'Rakefile'
- 'annotate.gemspec'
- 'spec/integration/common_validation.rb'
- 'spec/integration/rails_2.3_with_bundler/config/boot.rb'
- 'spec/integration/standalone.rb'
- 'spec/spec_helper.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: SupportedStyles, WordRegex.
# SupportedStyles: percent, brackets
Style/WordArray:
EnforcedStyle: percent
MinSize: 3
......@@ -14,4 +14,3 @@ before_install:
- rvm @global do gem install bundler
script:
- bundle exec rspec
- bundle exec rubocop
......@@ -17,7 +17,7 @@ group :development, :test do
gem 'terminal-notifier-guard', require: false
gem 'simplecov', require: false
gem 'rubocop', require: false unless RUBY_VERSION =~ /^1.8/
gem 'coveralls'
# gem 'coveralls'
gem 'codeclimate-test-reporter'
platforms :mri do
......
......@@ -177,6 +177,7 @@ you can do so with a simple environment variable, instead of editing the
--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'
-aa, --active-admin Annotate all activeadmin models
-v, --version Show the current version of this gem
-m, --show-migration Include the migration version number in the annotation
-i, --show-indexes List the table's database indexes in the annotation
......
......@@ -26,57 +26,57 @@ include Rake::DSL if using_dsl
require './lib/annotate'
require 'mg'
begin
MG.new("annotate.gemspec")
MG.new('annotate.gemspec')
rescue Exception
STDERR.puts("WARNING: Couldn't read gemspec. As such, a number of tasks may be unavailable to you until you run 'rake gem:gemspec' to correct the issue.")
# Gemspec is probably in a broken state, so let's give ourselves a chance to
# build a new one...
end
DEVELOPMENT_GROUPS=[:development, :test]
RUNTIME_GROUPS=Bundler.definition.groups - DEVELOPMENT_GROUPS
DEVELOPMENT_GROUPS = [:development, :test].freeze
RUNTIME_GROUPS = Bundler.definition.groups - DEVELOPMENT_GROUPS
namespace :gem do
task :gemspec do
spec = Gem::Specification.new do |gem|
# See http://docs.rubygems.org/read/chapter/20
# for more options.
gem.version = Annotate.version
gem.name = "annotate"
gem.homepage = "http://github.com/ctran/annotate_models"
gem.rubyforge_project = "annotate"
gem.license = "Ruby"
gem.summary = %q{Annotates Rails Models, routes, fixtures, and others based on the database schema.}
gem.description = %q{Annotates Rails/ActiveRecord Models, routes, fixtures, and others based on the database schema.}
gem.email = ["alex@stinky.com", "cuong@gmail.com", "x@nofxx.com", "turadg@aleahmad.net", "jon@cloudability.com"]
gem.authors = ["Alex Chaffee", "Cuong Tran", "Marcos Piccinini", "Turadg Aleahmad", "Jon Frisby"]
gem.require_paths = ["lib"]
gem.name = 'annotate'
gem.homepage = 'http://github.com/ctran/annotate_models'
gem.rubyforge_project = 'annotate'
gem.license = 'Ruby'
gem.summary = 'Annotates Rails Models, routes, fixtures, and others based on the database schema.'
gem.description = 'Annotates Rails/ActiveRecord Models, routes, fixtures, and others based on the database schema.'
gem.email = ['alex@stinky.com', 'cuong@gmail.com', 'x@nofxx.com', 'turadg@aleahmad.net', 'jon@cloudability.com']
gem.authors = ['Alex Chaffee', 'Cuong Tran', 'Marcos Piccinini', 'Turadg Aleahmad', 'Jon Frisby']
gem.require_paths = ['lib']
# gem.rdoc_options = ["--charset=UTF-8"]
# gem.required_ruby_version = "> 1.9.2"
Bundler.load.dependencies_for(*RUNTIME_GROUPS).each do |dep|
runtime_resolved = Bundler.definition.specs_for(RUNTIME_GROUPS).select { |spec| spec.name == dep.name }.first
if(!runtime_resolved.nil?)
runtime_resolved = Bundler.definition.specs_for(RUNTIME_GROUPS).find { |spec| spec.name == dep.name }
unless runtime_resolved.nil?
gem.add_dependency(dep.name, dep.requirement)
end
end
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
gem.extra_rdoc_files = ['README.rdoc', 'CHANGELOG.rdoc', 'TODO.rdoc']
gem.files = `git ls-files -- .`.split("\n").reject do |fn|
fn =~ /^Gemfile.*/ ||
fn =~ /^Rakefile/ ||
fn =~ /^\.rvmrc/ ||
fn =~ /^\.gitignore/ ||
fn =~ /^\.rspec/ ||
fn =~ /^\.document/ ||
fn =~ /^\.yardopts/ ||
fn =~ /^pkg/ ||
fn =~ /^spec/ ||
fn =~ /^doc/ ||
fn =~ /^vendor\/cache/
fn =~ /^Rakefile/ ||
fn =~ /^\.rvmrc/ ||
fn =~ /^\.gitignore/ ||
fn =~ /^\.rspec/ ||
fn =~ /^\.document/ ||
fn =~ /^\.yardopts/ ||
fn =~ /^pkg/ ||
fn =~ /^spec/ ||
fn =~ /^doc/ ||
fn =~ /^vendor\/cache/
end.sort
end
File.open("annotate.gemspec", "wb") do |fh|
File.open('annotate.gemspec', 'wb') do |fh|
fh.write("# This file is auto-generated!\n")
fh.write("# DO NOT EDIT THIS FILE DIRECTLY!\n")
fh.write("# Instead, edit the Rakefile and run 'rake gems:gemspec'.")
......@@ -87,12 +87,12 @@ end
namespace :jeweler do
task :clobber do
FileUtils.rm_f("pkg")
FileUtils.rm_f('pkg')
end
end
task clobber: :'jeweler:clobber'
require "rspec/core/rake_task" # RSpec 2.0
require 'rspec/core/rake_task' # RSpec 2.0
RSpec::Core::RakeTask.new(:spec) do |t|
t.pattern = ['spec/*_spec.rb', 'spec/**/*_spec.rb']
t.rspec_opts = ['--backtrace', '--format d']
......@@ -107,8 +107,8 @@ end
namespace :gemsets do
desc "Completely empty any gemsets used by scenarios, so they'll be perfectly clean on the next run."
task :empty => [:integration_environment] do
Annotate::Integration::SCENARIOS.each do |test_rig, base_dir, test_name|
task empty: [:integration_environment] do
Annotate::Integration::SCENARIOS.each do |test_rig, _base_dir, _test_name|
Annotate::Integration.empty_gemset(test_rig)
end
end
......@@ -117,11 +117,11 @@ task clobber: :'gemsets:empty'
namespace :integration do
desc "Remove any cruft generated by manual debugging runs which is .gitignore'd."
task :clean => :integration_environment do
task clean: :integration_environment do
Annotate::Integration.nuke_all_cruft
end
desc "Reset any changed files, and remove any untracked files in spec/integration/*/, plus run integration:clean."
desc 'Reset any changed files, and remove any untracked files in spec/integration/*/, plus run integration:clean.'
task clobber: [:integration_environment, :'integration:clean'] do
Annotate::Integration.reset_dirty_files
Annotate::Integration.clear_untracked_files
......@@ -132,27 +132,27 @@ namespace :integration do
integration_dir = File.expand_path(File.join(File.dirname(__FILE__), 'spec', 'integration'))
# fixture_dir = File.expand_path(File.join(File.dirname(__FILE__), 'spec', 'fixtures'))
target_dir = File.expand_path(ENV['TARGET']) if(ENV['TARGET'])
raise "Must specify TARGET=x, where x is an integration test scenario!" unless target_dir && Dir.exist?(target_dir)
raise "TARGET directory must be within spec/integration/!" unless target_dir.start_with?(integration_dir)
target_dir = File.expand_path(ENV['TARGET']) if ENV['TARGET']
fail 'Must specify TARGET=x, where x is an integration test scenario!' unless target_dir && Dir.exist?(target_dir)
fail 'TARGET directory must be within spec/integration/!' unless target_dir.start_with?(integration_dir)
candidates = {}
FileList[
"#{target_dir}/.rvmrc",
"#{target_dir}/**/*"
].select { |fname| !(File.symlink?(fname) || File.directory?(fname)) }.
map { |fname| fname.sub(integration_dir, '') }.
reject do |fname|
].select { |fname| !(File.symlink?(fname) || File.directory?(fname)) }
.map { |fname| fname.sub(integration_dir, '') }
.reject do |fname|
fname =~ /\/\.gitkeep$/ ||
fname =~ /\/app\/models\// ||
fname =~ /\/routes\.rb$/ ||
fname =~ /\/fixtures\// ||
fname =~ /\/factories\// ||
fname =~ /\.sqlite3$/ ||
(fname =~ /\/test\// && fname !~ /_helper\.rb$/) ||
(fname =~ /\/spec\// && fname !~ /_helper\.rb$/)
end.
map { |fname| "#{integration_dir}#{fname}"}.
each do |fname|
fname =~ /\/app\/models\// ||
fname =~ /\/routes\.rb$/ ||
fname =~ /\/fixtures\// ||
fname =~ /\/factories\// ||
fname =~ /\.sqlite3$/ ||
(fname =~ /\/test\// && fname !~ /_helper\.rb$/) ||
(fname =~ /\/spec\// && fname !~ /_helper\.rb$/)
end
.map { |fname| "#{integration_dir}#{fname}" }
.each do |fname|
digest = Digest::MD5.hexdigest(File.read(fname))
candidates[digest] ||= []
candidates[digest] << fname
......@@ -163,22 +163,20 @@ namespace :integration do
end
candidates.keys.each do |digest|
if(fixtures.has_key?(digest))
candidates[digest].each do |fname|
# Double-check contents in case of hash collision...
if(FileUtils.identical?(fname, fixtures[digest]))
destination_dir = Pathname.new(File.dirname(fname))
relative_target = Pathname.new(fixtures[digest]).relative_path_from(destination_dir)
Dir.chdir(destination_dir) do
sh("ln", "-sfn", relative_target.to_s, File.basename(fname))
end
end
next unless fixtures.key?(digest)
candidates[digest].each do |fname|
# Double-check contents in case of hash collision...
next unless FileUtils.identical?(fname, fixtures[digest])
destination_dir = Pathname.new(File.dirname(fname))
relative_target = Pathname.new(fixtures[digest]).relative_path_from(destination_dir)
Dir.chdir(destination_dir) do
sh('ln', '-sfn', relative_target.to_s, File.basename(fname))
end
end
end
end
end
task :clobber => :'integration:clobber'
task clobber: :'integration:clobber'
require 'yard'
YARD::Rake::YardocTask.new do |t|
......@@ -188,16 +186,16 @@ end
namespace :yard do
task :clobber do
FileUtils.rm_f(".yardoc")
FileUtils.rm_f("doc")
FileUtils.rm_f('.yardoc')
FileUtils.rm_f('doc')
end
end
task clobber: :'yard:clobber'
namespace :rubinius do
task :clobber do
FileList["**/*.rbc"].each { |fname| FileUtils.rm_f(fname) }
FileList[".rbx/**/*"].each { |fname| FileUtils.rm_f(fname) }
FileList['**/*.rbc'].each { |fname| FileUtils.rm_f(fname) }
FileList['.rbx/**/*'].each { |fname| FileUtils.rm_f(fname) }
end
end
task clobber: :'rubinius:clobber'
......
......@@ -8,7 +8,7 @@ require 'rubygems'
begin
require 'bundler'
Bundler.setup
rescue Exception => e
rescue Exception
end
here = File.expand_path(File.dirname __FILE__)
......@@ -33,7 +33,7 @@ OptionParser.new do |opts|
'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])
ENV[key] = p unless (has_set_position[key])
end
end
......@@ -90,6 +90,10 @@ OptionParser.new do |opts|
ENV['routes'] = 'true'
end
opts.on('-aa', '--active-admin', 'Annotate active_admin models') do |p|
ENV['active_admin'] = p
end
opts.on('-v', '--version',
'Show the current version of this gem') do
puts "annotate v#{Annotate.version}"; exit
......@@ -169,25 +173,25 @@ OptionParser.new do |opts|
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|
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|
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 comas (i.e., `integer,boolean,text`)" ) do |values|
opts.on('--hide-limit-column-types VALUES', "don't show limit for given column types, separated by comas (i.e., `integer,boolean,text`)") do |values|
ENV['hide_limit_column_types'] = "#{values}"
end
opts.on('--ignore-unknown-models', "don't display warnings for bad model files" ) do |_values|
opts.on('--ignore-unknown-models', "don't display warnings for bad model files") do |values|
ENV['ignore_unknown_models'] = 'true'
end
end.parse!
options = Annotate.setup_options({ :is_rake => ENV['is_rake'] && !ENV['is_rake'].empty? })
options = Annotate.setup_options({is_rake: ENV['is_rake'] && !ENV['is_rake'].empty?})
Annotate.eager_load(options)
AnnotateModels.send(target_action, options) if Annotate.include_models?
......
$:.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'annotate/version'
require 'annotate/annotate_models'
require 'annotate/annotate_routes'
......@@ -19,52 +19,52 @@ module Annotate
##
# The set of available options to customize the behavior of Annotate.
#
POSITION_OPTIONS=[
POSITION_OPTIONS = [
:position_in_routes, :position_in_class, :position_in_test,
:position_in_fixture, :position_in_factory, :position,
:position_in_serializer
]
FLAG_OPTIONS=[
].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, :trace,
:timestamp, :exclude_serializers, :classified_sort, :show_foreign_keys,
:exclude_scaffolds, :exclude_controllers, :exclude_helpers, :ignore_unknown_models,
]
OTHER_OPTIONS=[
:exclude_scaffolds, :exclude_controllers, :exclude_helpers, :ignore_unknown_models
].freeze
OTHER_OPTIONS = [
:ignore_columns, :skip_on_db_migrate, :wrapper_open, :wrapper_close, :wrapper, :routes,
:hide_limit_column_types, :ignore_routes
]
PATH_OPTIONS=[
:hide_limit_column_types, :ignore_routes, :active_admin
].freeze
PATH_OPTIONS = [
:require, :model_dir, :root_dir
]
].freeze
##
# Set default values that can be overridden via environment variables.
#
def self.set_defaults(options = {})
return if(@has_set_defaults)
return if @has_set_defaults
@has_set_defaults = true
options = HashWithIndifferentAccess.new(options)
[POSITION_OPTIONS, FLAG_OPTIONS, PATH_OPTIONS, OTHER_OPTIONS].flatten.each do |key|
if options.has_key?(key)
if options.key?(key)
default_value = if options[key].is_a?(Array)
options[key].join(",")
else
options[key]
options[key].join(',')
else
options[key]
end
end
default_value = ENV[key.to_s] if !ENV[key.to_s].blank?
default_value = ENV[key.to_s] unless ENV[key.to_s].blank?
ENV[key.to_s] = default_value.nil? ? nil : default_value.to_s
end
end
##
# 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')
......@@ -73,19 +73,14 @@ module Annotate
options[key] = true?(ENV[key.to_s])
end
OTHER_OPTIONS.each do |key|
options[key] = (!ENV[key.to_s].blank?) ? ENV[key.to_s] : nil
options[key] = !ENV[key.to_s].blank? ? ENV[key.to_s] : nil
end
PATH_OPTIONS.each do |key|
options[key] = (!ENV[key.to_s].blank?) ? ENV[key.to_s].split(',') : []
options[key] = !ENV[key.to_s].blank? ? ENV[key.to_s].split(',') : []
end
if(options[:model_dir].empty?)
options[:model_dir] = ['app/models']
end
if(options[:root_dir].empty?)
options[:root_dir] = ['']
end
options[:model_dir] = ['app/models'] if options[:model_dir].empty?
options[:root_dir] = [''] if options[:root_dir].empty?
options[:wrapper_open] ||= options[:wrapper]
options[:wrapper_close] ||= options[:wrapper]
......@@ -95,7 +90,7 @@ module Annotate
options[:exclude_controllers] = Annotate.true?(ENV.fetch('exclude_controllers', 'true'))
options[:exclude_helpers] = Annotate.true?(ENV.fetch('exclude_helpers', 'true'))
return options
options
end
def self.reset_options
......@@ -116,11 +111,16 @@ module Annotate
true
end
def self.loaded_tasks=(val); @loaded_tasks = val; end
def self.loaded_tasks; return @loaded_tasks; end
def self.loaded_tasks=(val)
@loaded_tasks = val
end
def self.loaded_tasks
@loaded_tasks
end
def self.load_tasks
return if(self.loaded_tasks)
return if loaded_tasks
self.loaded_tasks = true
Dir[File.join(File.dirname(__FILE__), 'tasks', '**/*.rake')].each { |rake| load rake }
......@@ -131,11 +131,11 @@ module Annotate
end
def self.eager_load(options)
self.load_requires(options)
require "annotate/active_record_patch"
load_requires(options)
require 'annotate/active_record_patch'
if(defined?(Rails))
if(Rails.version.split('.').first.to_i < 3)
if defined?(Rails)
if Rails.version.split('.').first.to_i < 3
Rails.configuration.eager_load_paths.each do |load_path|
matcher = /\A#{Regexp.escape(load_path)}(.*)\.rb\Z/
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
......@@ -166,7 +166,11 @@ module Annotate
require 'rake'
load './Rakefile' if File.exist?('./Rakefile')
Rake::Task[:environment].invoke rescue nil
begin
Rake::Task[:environment].invoke
rescue
nil
end
unless defined?(Rails)
# Not in a Rails project, so time to load up the parts of
# ActiveSupport we need.
......@@ -175,17 +179,17 @@ module Annotate
require 'active_support/core_ext/string/inflections'
end
self.load_tasks
load_tasks
Rake::Task[:set_annotation_options].invoke
end
def self.fallback(*args)
return args.detect { |arg| !arg.blank? }
args.detect { |arg| !arg.blank? }
end
def self.true?(val)
return false if(val.blank?)
return false unless(val =~ TRUE_RE)
return true
return false if val.blank?
return false unless val =~ TRUE_RE
true
end
end
......@@ -2,7 +2,7 @@
module ::ActiveRecord
class Base
def self.method_missing(name, *args)
def self.method_missing(_name, *_args)
# ignore this, so unknown/unloaded macros won't cause parsing to fail
end
end
......
require 'bigdecimal'
require 'annotate/file_patterns'
module AnnotateModels
TRUE_RE = /^(true|t|yes|y|1)$/i
# Annotate Models plugin use this header
COMPAT_PREFIX = "== Schema Info"
COMPAT_PREFIX_MD = "## Schema Info"
......@@ -9,7 +12,7 @@ module AnnotateModels
END_MARK = "== Schema Information End"
PATTERN = /^\r?\n?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?\r?\n(#.*\r?\n)*(\r?\n)*/
MATCHED_TYPES = %w(test fixture factory serializer scaffold controller admin helper)
MATCHED_TYPES = %w(test fixture factory serializer scaffold controller helper)
# File.join for windows reverse bar compat?
# I dont use windows, can`t test
......@@ -57,85 +60,29 @@ module AnnotateModels
# Don't show limit (#) on these column types
# Example: show "integer" instead of "integer(4)"
NO_LIMIT_COL_TYPES = ["integer", "boolean"]
NO_LIMIT_COL_TYPES = %w(integer boolean)
# Don't show default value for these column types
NO_DEFAULT_COL_TYPES = ["json", "jsonb"]
NO_DEFAULT_COL_TYPES = %w(json jsonb)
class << self
def model_dir
@model_dir.is_a?(Array) ? @model_dir : [@model_dir || "app/models"]
@model_dir.is_a?(Array) ? @model_dir : [@model_dir || 'app/models']
end
def model_dir=(dir)
@model_dir = dir
end
attr_writer :model_dir
def root_dir
@root_dir.is_a?(Array) ? @root_dir : [@root_dir || ""]
@root_dir.is_a?(Array) ? @root_dir : [@root_dir || '']
end
def root_dir=(dir)
@root_dir = dir
end
attr_writer :root_dir
def get_patterns(pattern_types=MATCHED_TYPES)
def get_patterns(pattern_types=[])
current_patterns = []
root_dir.each do |root_directory|
Array(pattern_types).each do |pattern_type|
current_patterns += case pattern_type
when 'test'
[
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"),
]
when 'fixture'
[
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"),
]
when 'scaffold'
[
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"),
]
when 'factory'
[
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, FABRICATORS_TEST_DIR, "%MODEL_NAME%_fabricator.rb"),
File.join(root_directory, FABRICATORS_SPEC_DIR, "%MODEL_NAME%_fabricator.rb"),
]
when 'serializer'
[
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")
]
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")
]
end
current_patterns += files_by_pattern(root_directory, pattern_type)
end
end
current_patterns.map{ |p| p.sub(/^[\/]*/, '') }
......@@ -144,9 +91,9 @@ module AnnotateModels
# Simple quoting for the default column value
def quote(value)
case value
when NilClass then "NULL"
when TrueClass then "TRUE"
when FalseClass then "FALSE"
when NilClass then 'NULL'
when TrueClass then 'TRUE'
when FalseClass then 'FALSE'
when Float, Fixnum, Bignum then value.to_s
# BigDecimals need to be output in a non-normalized form and quoted.
when BigDecimal then value.to_s('F')
......@@ -167,7 +114,7 @@ module AnnotateModels
def get_schema_info(klass, header, options = {})
info = "# #{header}\n"
info<< "#\n"
if(options[:format_markdown])
if options[:format_markdown]
info<< "# Table name: `#{klass.table_name}`\n"
info<< "#\n"
info<< "# ### Columns\n"
......@@ -176,13 +123,13 @@ module AnnotateModels
end
info<< "#\n"
max_size = klass.column_names.map{|name| name.size}.max || 0
max_size = klass.column_names.map(&:size).max || 0
max_size += options[:format_rdoc] ? 5 : 1
md_names_overhead = 6
md_type_allowance = 18
bare_type_allowance = 16
if(options[:format_markdown])
if options[:format_markdown]
info<< sprintf( "# %-#{max_size + md_names_overhead}.#{max_size + md_names_overhead}s | %-#{md_type_allowance}.#{md_type_allowance}s | %s\n", 'Name', 'Type', 'Attributes' )
info<< "# #{ '-' * ( max_size + md_names_overhead ) } | #{'-' * md_type_allowance} | #{ '-' * 27 }\n"
end
......@@ -195,20 +142,20 @@ module AnnotateModels
klass.columns
end
cols = cols.sort_by(&:name) if(options[:sort])
cols = classified_sort(cols) if(options[:classified_sort])
cols = cols.sort_by(&:name) if options[:sort]
cols = classified_sort(cols) if options[:classified_sort]
cols.each do |col|
col_type = (col.type || col.sql_type).to_s
attrs = []
attrs << "default(#{schema_default(klass, col)})" unless col.default.nil? || NO_DEFAULT_COL_TYPES.include?(col_type)
attrs << "not null" unless col.null
attrs << "primary key" if klass.primary_key && (klass.primary_key.is_a?(Array) ? klass.primary_key.collect{|c|c.to_sym}.include?(col.name.to_sym) : col.name.to_sym == klass.primary_key.to_sym)
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"
if col_type == 'decimal'
col_type << "(#{col.precision}, #{col.scale})"
elsif col_type != "spatial"
if (col.limit)
elsif col_type != 'spatial'
if col.limit
if col.limit.is_a? Array
attrs << "(#{col.limit.join(', ')})"
else
......@@ -218,15 +165,13 @@ module AnnotateModels
end
# Check out if we got an array column
if col.respond_to?(:array) && col.array
attrs << "is an Array"
end
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) and col.geometric_type.present?
elsif col.respond_to?(:geometric_type) && col.geometric_type.present?
attrs << "#{col.geometric_type.to_s.downcase}, #{col.srid}"
end
......@@ -235,7 +180,7 @@ module AnnotateModels
if options[:simple_indexes] && klass.table_exists?# Check out if this column is indexed
indices = klass.connection.indexes(klass.table_name)
if indices = indices.select { |ind| ind.columns.include? col.name }
indices.sort_by{|ind| ind.name}.each do |ind|
indices.sort_by(&:name).each do |ind|
ind = ind.columns.reject! { |i| i == col.name }
attrs << (ind.length == 0 ? "indexed" : "indexed => [#{ind.join(", ")}]")
end
......@@ -271,24 +216,25 @@ module AnnotateModels
end
def get_index_info(klass, options={})
if(options[:format_markdown])
if options[:format_markdown]
index_info = "#\n# ### Indexes\n#\n"
else
index_info = "#\n# Indexes\n#\n"
end
indexes = klass.connection.indexes(klass.table_name)
return "" if indexes.empty?
return '' if indexes.empty?
max_size = indexes.collect{|index| index.name.size}.max + 1
indexes.sort_by{|index| index.name}.each do |index|
if(options[:format_markdown])
indexes.sort_by(&:name).each do |index|
if options[:format_markdown]
index_info << sprintf("# * `%s`%s:\n# * **`%s`**\n", index.name, index.unique ? " (_unique_)" : "", index.columns.join("`**\n# * **`"))
else
index_info << sprintf("# %-#{max_size}.#{max_size}s %s %s", index.name, "(#{index.columns.join(",")})", index.unique ? "UNIQUE" : "").rstrip + "\n"
end
end
return index_info
index_info
end
def hide_limit?(col_type, options)
......@@ -303,27 +249,28 @@ module AnnotateModels
end
def get_foreign_key_info(klass, options={})
if(options[:format_markdown])
if options[:format_markdown]
fk_info = "#\n# ### Foreign Keys\n#\n"
else
fk_info = "#\n# Foreign Keys\n#\n"
end
return "" unless klass.connection.supports_foreign_keys? && klass.connection.respond_to?(:foreign_keys)
return '' unless klass.connection.supports_foreign_keys? && klass.connection.respond_to?(:foreign_keys)
foreign_keys = klass.connection.foreign_keys(klass.table_name)
return "" if foreign_keys.empty?
return '' if foreign_keys.empty?
max_size = foreign_keys.collect{|fk| fk.name.size}.max + 1
foreign_keys.sort_by{|fk| fk.name}.each do |fk|
foreign_keys.sort_by(&:name).each do |fk|
ref_info = "#{fk.column} => #{fk.to_table}.#{fk.primary_key}"
if(options[:format_markdown])
if options[:format_markdown]
fk_info << sprintf("# * `%s`:\n# * **`%s`**\n", fk.name, ref_info)
else
fk_info << sprintf("# %-#{max_size}.#{max_size}s %s", fk.name, "(#{ref_info})").rstrip + "\n"
end
end
return fk_info
fk_info
end
# Add a schema block to a file. If the file already contains
......@@ -342,7 +289,7 @@ module AnnotateModels
def annotate_one_file(file_name, info_block, position, options={})
if File.exist?(file_name)
old_content = File.read(file_name)
return false if(old_content =~ /# -\*- SkipSchemaAnnotations.*\n/)
return false if old_content =~ /# -\*- SkipSchemaAnnotations.*\n/
# Ignore the Schema version line because it changes with each migration
header_pattern = /(^# Table name:.*?\n(#.*[\r]?\n)*[\r]?)/
......@@ -386,7 +333,7 @@ module AnnotateModels
return true
end
else
return false
false
end
end
......@@ -403,6 +350,13 @@ module AnnotateModels
end
end
def matched_types(options)
types = MATCHED_TYPES
types << 'admin' if options[:active_admin] =~ TRUE_RE && !types.include?('admin')
types
end
# Given the name of an ActiveRecord class, create a schema
# info block (basically a comment containing information
# on the columns and their types) and put it at the front
......@@ -437,10 +391,16 @@ module AnnotateModels
annotated << model_file_name
end
MATCHED_TYPES.each do |key|
matched_types(options).each do |key|
exclusion_key = "exclude_#{key.pluralize}".to_sym
position_key = "position_in_#{key}".to_sym
# Same options for active_admin models
if key == 'admin'
exclusion_key = 'exclude_class'.to_sym
position_key = 'position_in_class'.to_sym
end
unless options[exclusion_key]
self.get_patterns(key).
map { |f| resolve_filename(f, model_name, table_name) }.
......@@ -456,12 +416,12 @@ module AnnotateModels
puts "\t" + e.backtrace.join("\n\t") if options[:trace]
end
return annotated
annotated
end
# position = :position_in_fixture or :position_in_class
def options_with_position(options, position_in)
options.merge(:position=>(options[position_in] || options[:position]))
options.merge(position: (options[position_in] || options[:position]))
end
# Return a list of the model files to annotate.
......@@ -470,7 +430,7 @@ module AnnotateModels
# in the model_dir directory.
def get_model_files(options)
models = []
if(!options[:is_rake])
if !options[:is_rake]
models = ARGV.dup.reject{|m| m.match(/^(.*)=/)}
end
......@@ -505,13 +465,13 @@ module AnnotateModels
model_path = file.gsub(/\.rb$/, '')
model_dir.each { |dir| model_path = model_path.gsub(/^#{dir}/, '').gsub(/^\//, '') }
begin
get_loaded_model(model_path) or raise BadModelFileError.new
get_loaded_model(model_path) || raise(BadModelFileError.new)
rescue LoadError
# this is for non-rails projects, which don't get Rails auto-require magic
file_path = File.expand_path(file)
if File.file?(file_path) && silence_warnings { Kernel.require(file_path) }
retry
elsif model_path.match(/\//)
elsif model_path =~ /\//
model_path = model_path.split('/')[1..-1].join('/').to_s
retry
else
......@@ -528,38 +488,39 @@ module AnnotateModels
# Revert to the old way but it is not really robust
ObjectSpace.each_object(::Class).
select do |c|
Class === c and # note: we use === to avoid a bug in activesupport 2.3.14 OptionMerger vs. is_a?
c.ancestors.respond_to?(:include?) and # to fix FactoryGirl bug, see https://github.com/ctran/annotate_models/pull/82
Class === c && # note: we use === to avoid a bug in activesupport 2.3.14 OptionMerger vs. is_a?
c.ancestors.respond_to?(:include?) && # to fix FactoryGirl bug, see https://github.com/ctran/annotate_models/pull/82
c.ancestors.include?(ActiveRecord::Base)
end.
detect { |c| ActiveSupport::Inflector.underscore(c.to_s) == model_path }
end
end
def parse_options(options={})
self.model_dir = options[:model_dir] if options[:model_dir]
self.root_dir = options[:root_dir] if options[:root_dir]
end
# We're passed a name of things that might be
# ActiveRecord models. If we can find the class, and
# if its a subclass of ActiveRecord::Base,
# then pass it to the associated block
def do_annotations(options={})
header = options[:format_markdown] ? PREFIX_MD.dup : PREFIX.dup
parse_options(options)
if options[:include_version]
version = ActiveRecord::Migrator.current_version rescue 0
if version > 0
header << "\n# Schema version: #{version}"
end
header = options[:format_markdown] ? PREFIX_MD.dup : PREFIX.dup
version = ActiveRecord::Migrator.current_version rescue 0
if options[:include_version] && version > 0
header << "\n# Schema version: #{version}"
end
self.model_dir = options[:model_dir] if options[:model_dir]
self.root_dir = options[:root_dir] if options[:root_dir]
annotated = []
get_model_files(options).each do |path, filename|
annotate_model_file(annotated, File.join(path, filename), header, options)
end
if annotated.empty?
puts "Model files unchanged."
puts 'Model files unchanged.'
else
puts "Annotated (#{annotated.length}): #{annotated.join(', ')}"
end
......@@ -567,7 +528,7 @@ module AnnotateModels
def annotate_model_file(annotated, file, header, options)
begin
return false if (/# -\*- SkipSchemaAnnotations.*/ =~ (File.exist?(file) ? File.read(file) : '') )
return false if /# -\*- SkipSchemaAnnotations.*/ =~ (File.exist?(file) ? File.read(file) : '')
klass = get_model_class(file)
if klass && klass < ActiveRecord::Base && !klass.abstract_class? && klass.table_exists?
annotated.concat(annotate(klass, file, header, options))
......@@ -584,8 +545,8 @@ module AnnotateModels
end
def remove_annotations(options={})
self.model_dir = options[:model_dir] if options[:model_dir]
self.root_dir = options[:root_dir] if options[:root_dir]
parse_options(options)
deannotated = []
deannotated_klass = false
get_model_files(options).each do |file|
......@@ -596,9 +557,9 @@ module AnnotateModels
model_name = klass.name.underscore
table_name = klass.table_name
model_file_name = file
deannotated_klass = true if(remove_annotation_of_file(model_file_name))
deannotated_klass = true if remove_annotation_of_file(model_file_name)
get_patterns.
get_patterns(matched_types(options)).
map { |f| resolve_filename(f, model_name, table_name) }.
each do |f|
if File.exist?(f)
......@@ -607,7 +568,7 @@ module AnnotateModels
end
end
end
deannotated << klass if(deannotated_klass)
deannotated << klass if deannotated_klass
rescue Exception => e
puts "Unable to deannotate #{File.join(file)}: #{e.message}"
puts "\t" + e.backtrace.join("\n\t") if options[:trace]
......@@ -617,10 +578,10 @@ module AnnotateModels
end
def resolve_filename(filename_template, model_name, table_name)
return filename_template.
gsub('%MODEL_NAME%', model_name).
gsub('%PLURALIZED_MODEL_NAME%', model_name.pluralize).
gsub('%TABLE_NAME%', table_name || model_name.pluralize)
filename_template.
gsub('%MODEL_NAME%', model_name).
gsub('%PLURALIZED_MODEL_NAME%', model_name.pluralize).
gsub('%TABLE_NAME%', table_name || model_name.pluralize)
end
def classified_sort(cols)
......@@ -632,7 +593,7 @@ module AnnotateModels
cols.each do |c|
if c.name.eql?('id')
id = c
elsif (c.name.eql?('created_at') || c.name.eql?('updated_at'))
elsif c.name.eql?('created_at') || c.name.eql?('updated_at')
timestamps << c
elsif c.name[-3,3].eql?('_id')
associations << c
......
......@@ -21,72 +21,51 @@ module AnnotateRoutes
PREFIX = '# == Route Map'
def self.do_annotations(options={})
return unless(routes_exists?)
return unless routes_exists?
position_after = ! %w(before top).include?(options[:position_in_routes])
routes_map = `rake routes`.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)
routes_map.reject!{|line| line.match(/#{options[:ignore_routes]}/)} if options[:ignore_routes]
routes_map = AnnotateRoutes.app_routes_map(options)
header = [
"#{PREFIX}" + (options[:timestamp] ? " (Updated #{Time.now.strftime('%Y-%m-%d %H:%M')})" : ''),
'#'
"#{PREFIX}" + (options[:timestamp] ? " (Updated #{Time.now.strftime('%Y-%m-%d %H:%M')})" : ''), '#'
] + routes_map.map { |line| "# #{line}".rstrip }
existing_text = File.read(routes_file)
(content, where_header_found) = strip_annotations(existing_text)
changed = where_header_found != 0 # 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.
if position_after
# Ensure we have adequate trailing newlines at the end of the file to
# ensure a blank line separating the content from the annotation.
content << '' if(content.last != '')
# We're moving something from the top of the file to the bottom, so ditch
# the spacer we put in the first time around.
if(changed && where_header_found == :before)
content.shift if(content.first == '')
end
else
header = header << '' if(content.first != '' || changed)
end
content = position_after ? (content + header) : header + content
if write_contents(existing_text, content)
if write_contents(existing_text, header, options)
puts "#{routes_file} annotated."
else
puts "#{routes_file} unchanged."
end
end
def self.remove_annotations(options={})
return unless(routes_exists?)
return unless routes_exists?
existing_text = File.read(routes_file)
(content, where_header_found) = strip_annotations(existing_text)
content, where_header_found = strip_annotations(existing_text)
content = strip_on_removal(content, where_header_found)
if write_contents(existing_text, content)
if write_contents(existing_text, content, options)
puts "Removed annotations from #{routes_file}."
else
puts "#{routes_file} unchanged."
end
end
protected
private
def self.app_routes_map(options)
routes_map = `rake routes`.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
def self.routes_file
@routes_rb ||= File.join('config', 'routes.rb')
......@@ -94,67 +73,96 @@ protected
def self.routes_exists?
routes_exists = File.exists?(routes_file)
puts "Can't find routes.rb" if(!routes_exists)
return routes_exists
puts "Can't find routes.rb" unless routes_exists
routes_exists
end
def self.write_contents(existing_text, new_content)
def self.write_contents(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_content << '' unless new_content.last == ''
new_text = new_content.join("\n")
return false if 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) }
true
end
end
File.open(routes_file, 'wb') { |f| f.puts(new_text) }
return true
def self.annotate_routes(header, content, where_header_found, options = {})
if %w(before top).include?(options[:position_in_routes])
header = header << '' if content.first != ''
new_content = header + content
else
# Ensure we have adequate trailing newlines at the end of the file to
# ensure a blank line separating the content from the annotation.
content << '' unless content.last == ''
# 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 == ''
new_content = content + header
end
new_content
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 self.strip_annotations(content)
real_content = []
mode = :content
line_number = 0
header_found_at = 0
content.split(/\n/, -1).each do |line|
line_number += 1
begin
if mode == :header
if line !~ /\s*#/
mode = :content
raise unless (line == '')
end
elsif mode == :content
if line =~ /^\s*#\s*== Route.*$/
header_found_at = line_number
mode = :header
else
real_content << line
end
content.split(/\n/, -1).each_with_index do |line, line_number|
if mode == :header && line !~ /\s*#/
mode = :content
next unless line == ''
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
rescue
retry
end
end
content_lines = real_content.count
where_header_found(real_content, header_found_at)
end
def self.where_header_found(real_content, header_found_at)
# By default assume the annotation was found in the middle of the file...
where_header_found = header_found_at
# ... unless we have evidence it was at the beginning ...
where_header_found = :before if(header_found_at == 1)
# ... or that it was at the end.
where_header_found = :after if(header_found_at >= content_lines)
if header_found_at == 1 # ... unless we have evidence it was at the beginning ...
return real_content, :before
elsif header_found_at >= real_content.count # ... or that it was at the end.
return real_content, :after
end
return real_content, where_header_found
return real_content, header_found_at
end
def self.strip_on_removal(content, where_header_found)
if where_header_found == :before
content.shift while(content.first == '')
content.shift while content.first == ''
elsif where_header_found == :after
content.pop while(content.last == '')
content.pop while content.last == ''
end
# 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...
return content
content
end
end
module FilePatterns
class << self
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_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, 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')]
else
[]
end
end
end
end
module Annotate
module Generators
class InstallGenerator < Rails::Generators::Base
desc "Copy annotate_models rakefiles for automatic annotation"
desc 'Copy annotate_models rakefiles for automatic annotation'
source_root File.expand_path('../templates', __FILE__)
# copy rake tasks
def copy_tasks
template "auto_annotate_models.rake", "lib/tasks/auto_annotate_models.rake"
template 'auto_annotate_models.rake', 'lib/tasks/auto_annotate_models.rake'
end
end
end
end
......@@ -31,7 +31,7 @@ if Rails.env.development?
'ignore_columns' => nil,
'ignore_routes' => nil,
'ignore_unknown_models' => 'false',
'hide_limit_column_types' => '<%= AnnotateModels::NO_LIMIT_COL_TYPES.join(',') %>',
'hide_limit_column_types' => '<%= AnnotateModels::NO_LIMIT_COL_TYPES.join(",") %>',
'skip_on_db_migrate' => 'false',
'format_bare' => 'true',
'format_rdoc' => 'false',
......@@ -40,7 +40,7 @@ if Rails.env.development?
'force' => 'false',
'trace' => 'false',
'wrapper_open' => nil,
'wrapper_close' => nil,
'wrapper_close' => nil
)
end
......
annotate_lib = File.expand_path(File.dirname(File.dirname(__FILE__)))
if !ENV['is_cli']
unless ENV['is_cli']
task :set_annotation_options
task :annotate_models => :set_annotation_options
task annotate_models: :set_annotation_options
end
desc "Add schema information (as comments) to model and fixture files"
task :annotate_models => :environment do
desc 'Add schema information (as comments) to model and fixture files'
task annotate_models: :environment do
require "#{annotate_lib}/annotate/annotate_models"
require "#{annotate_lib}/annotate/active_record_patch"
options={ :is_rake => true }
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'])
......@@ -48,12 +48,12 @@ task :annotate_models => :environment do
AnnotateModels.do_annotations(options)
end
desc "Remove schema information from model and fixture files"
task :remove_annotation => :environment do
desc 'Remove schema information from model and fixture files'
task remove_annotation: :environment do
require "#{annotate_lib}/annotate/annotate_models"
require "#{annotate_lib}/annotate/active_record_patch"
options={ :is_rake => true }
options={is_rake: true}
options[:model_dir] = ENV['model_dir']
options[:root_dir] = ENV['root_dir']
options[:require] = ENV['require'] ? ENV['require'].split(',') : []
......
......@@ -7,18 +7,18 @@ require 'active_support/core_ext/string'
describe AnnotateModels do
def mock_foreign_key(name, from_column, to_table, to_column = 'id')
double("ForeignKeyDefinition",
:name => name,
:column => from_column,
:to_table => to_table,
:primary_key => to_column,
:name => name,
:column => from_column,
:to_table => to_table,
:primary_key => to_column,
)
end
def mock_connection(indexes = [], foreign_keys = [])
double("Conn",
:indexes => indexes,
:foreign_keys => foreign_keys,
:supports_foreign_keys? => true,
:indexes => indexes,
:foreign_keys => foreign_keys,
:supports_foreign_keys? => true,
)
end
......@@ -47,7 +47,8 @@ describe AnnotateModels do
stubs = default_options.dup
stubs.merge!(options)
stubs.merge!(:name => name, :type => type)
stubs[:name] = name
stubs[:type] = type
double("Column", stubs)
end
......@@ -174,13 +175,13 @@ EOS
mock_column(:id, :integer),
mock_column(:foreign_thing_id, :integer),
],
[
mock_foreign_key(
'fk_rails_02e851e3b7',
'foreign_thing_id',
'foreign_things'
)
])
[
mock_foreign_key(
'fk_rails_02e851e3b7',
'foreign_thing_id',
'foreign_things'
)
])
expect(AnnotateModels.get_schema_info(klass, "Schema Info", :show_foreign_keys => true)).to eql(<<-EOS)
# Schema Info
#
......@@ -274,7 +275,7 @@ EOS
module ::ActiveRecord
class Base
def self.has_many name
def self.has_many _name
end
end
end
......@@ -644,7 +645,7 @@ end
before do
annotate_one_file :position => :before
another_schema_info = AnnotateModels.get_schema_info(mock_class(:users, :id, [mock_column(:id, :integer),]),
"== Schema Info")
"== Schema Info")
@schema_info = another_schema_info
end
......@@ -668,7 +669,7 @@ end
before do
annotate_one_file :position => :after
another_schema_info = AnnotateModels.get_schema_info(mock_class(:users, :id, [mock_column(:id, :integer),]),
"== Schema Info")
"== Schema Info")
@schema_info = another_schema_info
end
......
......@@ -38,11 +38,9 @@ describe AnnotateRoutes do
AnnotateRoutes.do_annotations
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")
......@@ -61,11 +59,9 @@ describe AnnotateRoutes do
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")
......@@ -73,7 +69,6 @@ describe AnnotateRoutes do
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/)
......@@ -91,11 +86,9 @@ describe AnnotateRoutes do
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)
......@@ -113,7 +106,5 @@ describe AnnotateRoutes do
expect(@mock_file).to receive(:puts).with(/ActionController::Routing...\nfoo\n\n\n\n\n\n\n\n\n\n\n/)
AnnotateRoutes.remove_annotations
end
end
end
......@@ -53,7 +53,7 @@ module Annotate
File.read("test/fixtures/tasks.yml").should == fixture
end
protected
protected
def self.apply_annotation(test_rig, fname, annotation, place_before=true)
corpus = File.read(File.join(test_rig, fname))
......
......@@ -54,7 +54,7 @@ describe "annotate inside Rails, using #{CURRENT_RUBY}" do
ENV['rvm_ruby_string']=CURRENT_RUBY
require "#{base_dir}" # Will get "#{base_dir}.rb"...
klass = "Annotate::Validations::#{base_dir.gsub('.', '_').classify}".constantize
klass = "Annotate::Validations::#{base_dir.tr('.', '_').classify}".constantize
Dir.chdir(temp_dir) do
# bash is required by rvm
......
require 'coveralls'
# require 'coveralls'
require 'codeclimate-test-reporter'
require 'simplecov'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
Coveralls::SimpleCov::Formatter,
# Coveralls::SimpleCov::Formatter,
SimpleCov::Formatter::HTMLFormatter,
CodeClimate::TestReporter::Formatter
]
......@@ -14,6 +14,7 @@ require 'rubygems'
require 'bundler'
Bundler.setup
require 'rake'
require 'rspec'
require 'wrong/adapters/rspec'
......@@ -26,6 +27,10 @@ require 'active_support/core_ext/class/subclasses'
require 'active_support/core_ext/string/inflections'
require 'annotate'
require 'rubocop/rake_task'
RuboCop::RakeTask.new
Rake::Task['rubocop'].invoke
module Annotate
module Integration
ABSOLUTE_GEM_ROOT=File.expand_path('../../', __FILE__)
......@@ -49,7 +54,7 @@ module Annotate
end
def self.nuke_all_cruft
SCENARIOS.each do |test_rig, base_dir, test_name|
SCENARIOS.each do |test_rig, _base_dir, _test_name|
nuke_cruft(test_rig)
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