diff --git a/.rubocop.yml b/.rubocop.yml index f77cd3d9..e73a5de6 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -2,7 +2,6 @@ inherit_from: - .rubocop_standardrb.yml - .rubocop_standardrb_overrides.yml - - .rubocop_todo.yml AllCops: NewCops: disable diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index 852a55aa..00000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,691 +0,0 @@ -# This configuration was generated by -# `rubocop --auto-gen-config --no-exclude-limit --no-auto-gen-timestamp` -# using RuboCop version 1.80.2. -# 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: 26 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: with_first_argument, with_fixed_indentation -Layout/ArgumentAlignment: - Exclude: - - 'lib/pliny/commands/generator/endpoint.rb' - - 'lib/pliny/commands/generator/mediator.rb' - - 'lib/pliny/commands/generator/model.rb' - - 'lib/pliny/commands/generator/serializer.rb' - - 'lib/template/config/initializers/database.rb' - - 'lib/template/lib/routes.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleAlignWith, Severity. -# SupportedStylesAlignWith: start_of_line, begin -Layout/BeginEndAlignment: - Exclude: - - 'spec/log_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EmptyLineBetweenMethodDefs, EmptyLineBetweenClassDefs, EmptyLineBetweenModuleDefs, DefLikeMacros, AllowAdjacentOneLineDefs, NumberOfEmptyLines. -Layout/EmptyLineBetweenDefs: - Exclude: - - 'spec/helpers/serialize_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Layout/EmptyLines: - Exclude: - - 'spec/commands/generator/schema_spec.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, no_empty_lines -Layout/EmptyLinesAroundBlockBody: - Exclude: - - 'spec/commands/generator/endpoint_spec.rb' - - 'spec/config_helpers_spec.rb' - - 'spec/log_spec.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only -Layout/EmptyLinesAroundClassBody: - Exclude: - - 'lib/pliny/middleware/cors.rb' - - 'lib/pliny/router.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines -Layout/EmptyLinesAroundModuleBody: - Exclude: - - 'lib/pliny/config_helpers.rb' - -# Offense count: 49 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. -Layout/ExtraSpacing: - Exclude: - - 'lib/pliny/commands/updater.rb' - - 'lib/pliny/errors.rb' - - 'lib/pliny/middleware/cors.rb' - - 'lib/template/config/config.rb' - - 'pliny.gemspec' - - 'spec/db_support_spec.rb' - - 'spec/error_reporters/rollbar_spec.rb' - - 'spec/error_reporters_spec.rb' - - 'spec/integration_spec.rb' - -# Offense count: 63 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. -# SupportedHashRocketStyles: key, separator, table -# SupportedColonStyles: key, separator, table -# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit -Layout/HashAlignment: - Exclude: - - 'lib/pliny/errors.rb' - - 'lib/pliny/log.rb' - - 'lib/pliny/middleware/cors.rb' - - 'lib/pliny/middleware/instruments.rb' - - 'spec/commands/generator/endpoint_spec.rb' - - 'spec/middleware/instruments_spec.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -Layout/HeredocIndentation: - Exclude: - - 'lib/pliny/middleware/versioning.rb' - - 'spec/middleware/versioning_spec.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -Layout/LeadingEmptyLines: - Exclude: - - 'lib/template/Rakefile' - - 'lib/template/lib/tasks/spec.rake' - -# Offense count: 6 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: symmetrical, new_line, same_line -Layout/MultilineMethodCallBraceLayout: - Exclude: - - 'lib/pliny/log.rb' - - 'spec/errors_spec.rb' - - 'spec/metrics/backends/logger_spec.rb' - - 'spec/middleware/canonical_log_line_spec.rb' - -# Offense count: 7 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -Layout/SpaceAroundEqualsInParameterDefault: - Exclude: - - 'lib/pliny/config_helpers.rb' - - 'lib/pliny/db_support.rb' - - 'lib/pliny/middleware/request_store/clear.rb' - - 'lib/pliny/middleware/request_store/seed.rb' - - 'lib/pliny/middleware/versioning.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator, EnforcedStyleForRationalLiterals. -# SupportedStylesForExponentOperator: space, no_space -# SupportedStylesForRationalLiterals: space, no_space -Layout/SpaceAroundOperators: - Exclude: - - 'lib/pliny/config_helpers.rb' - - 'lib/pliny/middleware/metrics.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceBeforeBlockBraces: - Exclude: - - 'lib/pliny/config_helpers.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: require_no_space, require_space -Layout/SpaceInLambdaLiteral: - Exclude: - - 'lib/pliny/config_helpers.rb' - - 'lib/template/lib/routes.rb' - - 'spec/log_spec.rb' - - 'spec/middleware/canonical_log_line_spec.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBrackets: space, no_space -Layout/SpaceInsideArrayLiteralBrackets: - Exclude: - - 'lib/pliny/metrics/backends/logger.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideBlockBraces: - Exclude: - - 'lib/pliny/config_helpers.rb' - - 'spec/metrics_spec.rb' - -# Offense count: 39 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideHashLiteralBraces: - Exclude: - - 'spec/error_reporters/rollbar_spec.rb' - - 'spec/helpers/params_spec.rb' - - 'spec/middleware/versioning_spec.rb' - - 'spec/router_spec.rb' - -# Offense count: 9 -# This cop supports safe autocorrection (--autocorrect). -Layout/SpaceInsidePercentLiteralDelimiters: - Exclude: - - 'lib/pliny/middleware/cors.rb' - - 'pliny.gemspec' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowInHeredoc. -Layout/TrailingWhitespace: - Exclude: - - 'spec/commands/generator/base_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -Lint/AmbiguousRegexpLiteral: - Exclude: - - 'spec/commands/generator/base_spec.rb' - - 'spec/helpers/params_spec.rb' - -# Offense count: 6 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: AllowSafeAssignment. -Lint/AssignmentInCondition: - Exclude: - - 'lib/pliny/commands/updater.rb' - - 'lib/pliny/middleware/canonical_log_line.rb' - - 'lib/pliny/middleware/instruments.rb' - - 'lib/pliny/middleware/request_id.rb' - -# Offense count: 4 -# Configuration parameters: AllowedMethods. -# AllowedMethods: enums -Lint/ConstantDefinitionInBlock: - Exclude: - - 'spec/canonical_log_line_helpers_spec.rb' - - 'spec/helpers/serialize_spec.rb' - - 'spec/helpers/zulu_time_spec.rb' - - 'spec/middleware/rescue_errors_spec.rb' - -# Offense count: 1 -Lint/IneffectiveAccessModifier: - Exclude: - - 'lib/pliny/metrics/backends/logger.rb' - -# Offense count: 1 -# Configuration parameters: MaximumRangeSize. -Lint/MissingCopEnableDirective: - Exclude: - - 'lib/template/bin/run' - -# Offense count: 1 -Lint/RescueException: - Exclude: - - 'lib/pliny/error_reporters/rollbar.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -Lint/UselessAssignment: - Exclude: - - 'spec/integration_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: CheckForMethodsWithNoSideEffects. -Lint/Void: - Exclude: - - 'lib/pliny/log.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: lowercase, uppercase -Naming/HeredocDelimiterCase: - Exclude: - - 'lib/pliny/helpers/serialize.rb' - - 'lib/pliny/middleware/versioning.rb' - - 'spec/middleware/versioning_spec.rb' - -# Offense count: 1 -Security/Eval: - Exclude: - - 'spec/commands/generator/endpoint_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: prefer_alias, prefer_alias_method -Style/Alias: - Exclude: - - 'lib/pliny/utils.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: is_a?, kind_of? -Style/ClassCheck: - Exclude: - - 'lib/pliny/config_helpers.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, AllowInnerBackticks. -# SupportedStyles: backticks, percent_x, mixed -Style/CommandLiteral: - Exclude: - - 'pliny.gemspec' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -Style/ComparableBetween: - Exclude: - - 'spec/metrics_spec.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -Style/EmptyLiteral: - Exclude: - - 'spec/commands/generator/endpoint_spec.rb' - - 'spec/log_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: compact, expanded -Style/EmptyMethod: - Exclude: - - 'spec/helpers/serialize_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/FileWrite: - Exclude: - - 'lib/pliny/commands/creator.rb' - -# Offense count: 115 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: always, always_true, never -Style/FrozenStringLiteralComment: - Exclude: - - '**/*.arb' - - 'Gemfile' - - 'Rakefile' - - 'bin/pliny-generate' - - 'bin/pliny-new' - - 'bin/pliny-update' - - 'lib/pliny.rb' - - 'lib/pliny/canonical_log_line_helpers.rb' - - 'lib/pliny/commands/creator.rb' - - 'lib/pliny/commands/generator.rb' - - 'lib/pliny/commands/generator/base.rb' - - 'lib/pliny/commands/generator/endpoint.rb' - - 'lib/pliny/commands/generator/mediator.rb' - - 'lib/pliny/commands/generator/migration.rb' - - 'lib/pliny/commands/generator/model.rb' - - 'lib/pliny/commands/generator/schema.rb' - - 'lib/pliny/commands/generator/serializer.rb' - - 'lib/pliny/commands/updater.rb' - - 'lib/pliny/config_helpers.rb' - - 'lib/pliny/db_support.rb' - - 'lib/pliny/error_reporters.rb' - - 'lib/pliny/error_reporters/rollbar.rb' - - 'lib/pliny/errors.rb' - - 'lib/pliny/helpers/encode.rb' - - 'lib/pliny/helpers/params.rb' - - 'lib/pliny/helpers/serialize.rb' - - 'lib/pliny/helpers/zulu_time.rb' - - 'lib/pliny/log.rb' - - 'lib/pliny/metrics.rb' - - 'lib/pliny/metrics/backends/logger.rb' - - 'lib/pliny/middleware/canonical_log_line.rb' - - 'lib/pliny/middleware/cors.rb' - - 'lib/pliny/middleware/instruments.rb' - - 'lib/pliny/middleware/metrics.rb' - - 'lib/pliny/middleware/request_id.rb' - - 'lib/pliny/middleware/request_store/clear.rb' - - 'lib/pliny/middleware/request_store/seed.rb' - - 'lib/pliny/middleware/rescue_errors.rb' - - 'lib/pliny/middleware/versioning.rb' - - 'lib/pliny/request_store.rb' - - 'lib/pliny/rollbar_logger.rb' - - 'lib/pliny/router.rb' - - 'lib/pliny/tasks.rb' - - 'lib/pliny/tasks/db.rake' - - 'lib/pliny/tasks/schema.rake' - - 'lib/pliny/utils.rb' - - 'lib/pliny/version.rb' - - 'lib/template/Gemfile' - - 'lib/template/Rakefile' - - 'lib/template/bin/console' - - 'lib/template/bin/run' - - 'lib/template/config.ru' - - 'lib/template/config/config.rb' - - 'lib/template/config/initializers/database.rb' - - 'lib/template/config/initializers/log.rb' - - 'lib/template/config/initializers/metrics.rb' - - 'lib/template/config/initializers/rollbar.rb' - - 'lib/template/config/puma.rb' - - 'lib/template/db/seeds.rb' - - 'lib/template/lib/application.rb' - - 'lib/template/lib/endpoints/base.rb' - - 'lib/template/lib/endpoints/health.rb' - - 'lib/template/lib/endpoints/root.rb' - - 'lib/template/lib/endpoints/schema.rb' - - 'lib/template/lib/initializer.rb' - - 'lib/template/lib/mediators/base.rb' - - 'lib/template/lib/routes.rb' - - 'lib/template/lib/serializers/base.rb' - - 'lib/template/lib/tasks/rubocop.rake' - - 'lib/template/lib/tasks/spec.rake' - - 'lib/template/spec/endpoints/health_spec.rb' - - 'lib/template/spec/endpoints/schema_spec.rb' - - 'lib/template/spec/spec_helper.rb' - - 'lib/template/spec/spec_support/auto_define_rack_app.rb' - - 'lib/template/spec/spec_support/coverage.rb' - - 'lib/template/spec/spec_support/log.rb' - - 'pliny.gemspec' - - 'spec/canonical_log_line_helpers_spec.rb' - - 'spec/commands/creator_spec.rb' - - 'spec/commands/generator/base_spec.rb' - - 'spec/commands/generator/endpoint_spec.rb' - - 'spec/commands/generator/mediator_spec.rb' - - 'spec/commands/generator/migration_spec.rb' - - 'spec/commands/generator/model_spec.rb' - - 'spec/commands/generator/schema_spec.rb' - - 'spec/commands/generator/serializer_spec.rb' - - 'spec/commands/generator_spec.rb' - - 'spec/commands/updater_spec.rb' - - 'spec/config_helpers_spec.rb' - - 'spec/db_support_spec.rb' - - 'spec/error_reporters/rollbar_spec.rb' - - 'spec/error_reporters_spec.rb' - - 'spec/errors_spec.rb' - - 'spec/helpers/encode_spec.rb' - - 'spec/helpers/params_spec.rb' - - 'spec/helpers/serialize_spec.rb' - - 'spec/helpers/zulu_time_spec.rb' - - 'spec/integration_spec.rb' - - 'spec/log_spec.rb' - - 'spec/metrics/backends/logger_spec.rb' - - 'spec/metrics_spec.rb' - - 'spec/middleware/canonical_log_line_spec.rb' - - 'spec/middleware/cors_spec.rb' - - 'spec/middleware/instruments_spec.rb' - - 'spec/middleware/metrics_spec.rb' - - 'spec/middleware/request_id_spec.rb' - - 'spec/middleware/request_store/clear_spec.rb' - - 'spec/middleware/request_store/seed_spec.rb' - - 'spec/middleware/rescue_errors_spec.rb' - - 'spec/middleware/versioning_spec.rb' - - 'spec/request_store_spec.rb' - - 'spec/rollbar_logger_spec.rb' - - 'spec/router_spec.rb' - - 'spec/spec_helper.rb' - - 'spec/support/config.rb' - - 'spec/support/endpoints.rb' - -# Offense count: 5 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: AllowSplatArgument. -Style/HashConversion: - Exclude: - - 'lib/pliny/metrics.rb' - - 'spec/integration_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowIfModifier. -Style/IfInsideElse: - Exclude: - - 'lib/pliny/db_support.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: predicate, comparison -Style/NilComparison: - Exclude: - - 'lib/pliny/log.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/OrAssignment: - Exclude: - - 'lib/pliny/middleware/versioning.rb' - -# Offense count: 12 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Exclude: - - 'lib/pliny/db_support.rb' - - 'lib/pliny/log.rb' - - 'lib/pliny/middleware/cors.rb' - - 'lib/pliny/middleware/request_id.rb' - - 'lib/template/lib/initializer.rb' - - 'pliny.gemspec' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantBegin: - Exclude: - - 'lib/pliny/error_reporters.rb' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -Style/RedundantInterpolation: - Exclude: - - 'lib/pliny/log.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantRegexpArgument: - Exclude: - - 'lib/pliny/log.rb' - -# Offense count: 8 -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantRegexpCharacterClass: - Exclude: - - 'spec/integration_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantRegexpEscape: - Exclude: - - 'lib/pliny/commands/updater.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowMultipleReturnValues. -Style/RedundantReturn: - Exclude: - - 'lib/pliny/db_support.rb' - - 'spec/integration_spec.rb' - -# Offense count: 4 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. -# AllowedMethods: present?, blank?, presence, try, try! -Style/SafeNavigation: - Exclude: - - 'lib/pliny/config_helpers.rb' - - 'lib/pliny/helpers/zulu_time.rb' - - 'lib/pliny/log.rb' - - 'lib/pliny/request_store.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -Style/SelfAssignment: - Exclude: - - 'lib/pliny/errors.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowIfMethodIsEmpty. -Style/SingleLineMethods: - Exclude: - - 'spec/helpers/serialize_spec.rb' - -# Offense count: 4 -# This cop supports unsafe autocorrection (--autocorrect-all). -Style/SlicingWithRange: - Exclude: - - 'lib/pliny/tasks/db.rake' - - 'spec/integration_spec.rb' - -# Offense count: 477 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Exclude: - - 'Rakefile' - - 'bin/pliny-generate' - - 'bin/pliny-new' - - 'bin/pliny-update' - - 'lib/pliny/commands/creator.rb' - - 'lib/pliny/commands/generator.rb' - - 'lib/pliny/commands/generator/base.rb' - - 'lib/pliny/commands/generator/endpoint.rb' - - 'lib/pliny/commands/generator/mediator.rb' - - 'lib/pliny/commands/generator/migration.rb' - - 'lib/pliny/commands/generator/model.rb' - - 'lib/pliny/commands/generator/schema.rb' - - 'lib/pliny/commands/generator/serializer.rb' - - 'lib/pliny/config_helpers.rb' - - 'lib/pliny/error_reporters/rollbar.rb' - - 'lib/pliny/errors.rb' - - 'lib/pliny/helpers/encode.rb' - - 'lib/pliny/helpers/serialize.rb' - - 'lib/pliny/middleware/cors.rb' - - 'lib/pliny/middleware/versioning.rb' - - 'lib/pliny/rollbar_logger.rb' - - 'lib/pliny/router.rb' - - 'lib/pliny/tasks/schema.rake' - - 'lib/pliny/utils.rb' - - 'spec/commands/generator/base_spec.rb' - - 'spec/commands/generator/endpoint_spec.rb' - - 'spec/commands/generator/mediator_spec.rb' - - 'spec/commands/generator/migration_spec.rb' - - 'spec/commands/generator/model_spec.rb' - - 'spec/commands/generator/schema_spec.rb' - - 'spec/commands/generator/serializer_spec.rb' - - 'spec/commands/generator_spec.rb' - - 'spec/config_helpers_spec.rb' - - 'spec/db_support_spec.rb' - - 'spec/integration_spec.rb' - - 'spec/log_spec.rb' - - 'spec/metrics/backends/logger_spec.rb' - - 'spec/metrics_spec.rb' - - 'spec/middleware/versioning_spec.rb' - - 'spec/rollbar_logger_spec.rb' - - 'spec/router_spec.rb' - - 'spec/spec_helper.rb' - -# Offense count: 6 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiteralsInInterpolation: - Exclude: - - 'lib/pliny/db_support.rb' - -# Offense count: 32 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInArguments: - Exclude: - - 'lib/pliny/commands/generator/endpoint.rb' - - 'lib/pliny/commands/generator/mediator.rb' - - 'lib/pliny/commands/generator/model.rb' - - 'lib/pliny/commands/generator/serializer.rb' - - 'lib/pliny/log.rb' - - 'lib/pliny/middleware/instruments.rb' - - 'lib/template/config/initializers/database.rb' - - 'lib/template/lib/tasks/spec.rake' - - 'spec/canonical_log_line_helpers_spec.rb' - - 'spec/commands/generator/endpoint_spec.rb' - - 'spec/error_reporters/rollbar_spec.rb' - - 'spec/errors_spec.rb' - - 'spec/metrics_spec.rb' - - 'spec/middleware/instruments_spec.rb' - -# Offense count: 7 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, diff_comma, no_comma -Style/TrailingCommaInArrayLiteral: - Exclude: - - 'lib/pliny/db_support.rb' - - 'lib/pliny/middleware/versioning.rb' - - 'lib/template/bin/console' - - 'spec/commands/generator/base_spec.rb' - - 'spec/db_support_spec.rb' - -# Offense count: 6 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, diff_comma, no_comma -Style/TrailingCommaInHashLiteral: - Exclude: - - 'lib/pliny/db_support.rb' - - 'lib/pliny/middleware/cors.rb' - - 'lib/pliny/middleware/instruments.rb' - - 'lib/pliny/request_store.rb' - - 'spec/error_reporters/rollbar_spec.rb' - - 'spec/request_store_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, AllowedMethods. -# AllowedMethods: 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: - - 'spec/middleware/rescue_errors_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/UnlessElse: - Exclude: - - 'lib/pliny/log.rb' - -# Offense count: 2 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: forbid_for_all_comparison_operators, forbid_for_equality_operators_only, require_for_all_comparison_operators, require_for_equality_operators_only -Style/YodaCondition: - Exclude: - - 'spec/metrics_spec.rb' - - 'spec/middleware/metrics_spec.rb' diff --git a/Gemfile b/Gemfile index cd7558b7..fd3e4b2c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + source "https://rubygems.org" gemspec diff --git a/Rakefile b/Rakefile index ca385ce9..a7f54a3b 100644 --- a/Rakefile +++ b/Rakefile @@ -1,7 +1,9 @@ +# frozen_string_literal: true + $:.unshift File.expand_path("../lib", __FILE__) require "pliny/version" -require 'rspec/core/rake_task' +require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) task default: :spec @@ -44,9 +46,9 @@ task :release do sh "rm pliny-#{new_version}.gem" end -desc 'Open a irb/pry session preloaded with pliny' +desc "Open a irb/pry session preloaded with pliny" task :console do - require 'pry' - require 'pliny' + require "pry" + require "pliny" Pry.start end diff --git a/bin/pliny-generate b/bin/pliny-generate index 89cee34b..859e2349 100755 --- a/bin/pliny-generate +++ b/bin/pliny-generate @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# frozen_string_literal: true -require_relative '../lib/pliny/commands/generator' +require_relative "../lib/pliny/commands/generator" Pliny::Commands::Generator.start diff --git a/bin/pliny-new b/bin/pliny-new index 733deae3..8101226f 100755 --- a/bin/pliny-new +++ b/bin/pliny-new @@ -1,7 +1,8 @@ #!/usr/bin/env ruby +# frozen_string_literal: true require "optparse" -require_relative '../lib/pliny/commands/creator' +require_relative "../lib/pliny/commands/creator" OptionParser.new do |options| opts = {} diff --git a/bin/pliny-update b/bin/pliny-update index bdfd4a3b..8516f2d1 100755 --- a/bin/pliny-update +++ b/bin/pliny-update @@ -1,6 +1,7 @@ #!/usr/bin/env ruby +# frozen_string_literal: true require "optparse" -require_relative '../lib/pliny/commands/updater' +require_relative "../lib/pliny/commands/updater" Pliny::Commands::Updater.run diff --git a/lib/pliny.rb b/lib/pliny.rb index bedb6e98..6f6b7b40 100644 --- a/lib/pliny.rb +++ b/lib/pliny.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "json" require "sinatra/base" diff --git a/lib/pliny/canonical_log_line_helpers.rb b/lib/pliny/canonical_log_line_helpers.rb index 413fb60a..0157ef24 100644 --- a/lib/pliny/canonical_log_line_helpers.rb +++ b/lib/pliny/canonical_log_line_helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny # Helpers to produce a canonical log line. This mostly amounts to a set of # accessors that do basic type checking combined with tracking an internal diff --git a/lib/pliny/commands/creator.rb b/lib/pliny/commands/creator.rb index dd971e63..d2ef5f02 100644 --- a/lib/pliny/commands/creator.rb +++ b/lib/pliny/commands/creator.rb @@ -1,9 +1,11 @@ -require 'fileutils' -require 'pathname' -require 'pliny/version' -require 'uri' -require 'erb' -require 'ostruct' +# frozen_string_literal: true + +require "fileutils" +require "pathname" +require "pliny/version" +require "uri" +require "erb" +require "ostruct" module Pliny::Commands class Creator @@ -25,7 +27,7 @@ def run! FileUtils.copy_entry template_dir, app_dir FileUtils.rm_rf("#{app_dir}/.git") parse_erb_files - display 'Pliny app created. To start, run:' + display "Pliny app created. To start, run:" display "cd #{app_dir} && bin/setup" end @@ -33,15 +35,13 @@ def run! def parse_erb_files Dir.glob("#{app_dir}/{*,.*}.erb").each do |file| - static_file = file.gsub(/\.erb$/, '') + static_file = file.gsub(/\.erb$/, "") template = ERB.new(File.read(file)) context = OpenStruct.new(app_name: name) content = template.result(context.instance_eval { binding }) - File.open(static_file, "w") do |f| - f.write content - end + File.write(static_file, content) FileUtils.rm(file) end end @@ -55,7 +55,7 @@ def name end def template_dir - File.expand_path('../../template', File.dirname(__FILE__)) + File.expand_path("../../template", File.dirname(__FILE__)) end def app_dir diff --git a/lib/pliny/commands/generator.rb b/lib/pliny/commands/generator.rb index 91dea1b1..4a42340f 100644 --- a/lib/pliny/commands/generator.rb +++ b/lib/pliny/commands/generator.rb @@ -1,12 +1,14 @@ -require 'pliny/version' -require 'thor' +# frozen_string_literal: true + +require "pliny/version" +require "thor" module Pliny::Commands class Generator < Thor - desc 'endpoint NAME', 'Generates an endpoint' + desc "endpoint NAME", "Generates an endpoint" method_option :scaffold, type: :boolean, default: false, hide: true def endpoint(name) - require_relative 'generator/endpoint' + require_relative "generator/endpoint" ep = Endpoint.new(name, options) ep.create @@ -14,27 +16,27 @@ def endpoint(name) ep.create_acceptance_test end - desc 'mediator NAME', 'Generates a mediator' + desc "mediator NAME", "Generates a mediator" def mediator(name) - require_relative 'generator/mediator' + require_relative "generator/mediator" md = Mediator.new(name, options) md.create md.create_test end - desc 'migration NAME', 'Generates a migration' + desc "migration NAME", "Generates a migration" def migration(name) - require_relative 'generator/migration' + require_relative "generator/migration" mg = Migration.new(name, options) mg.create end - desc 'model NAME', 'Generates a model' - method_option :paranoid, type: :boolean, default: false, desc: 'adds paranoid support to model' + desc "model NAME", "Generates a model" + method_option :paranoid, type: :boolean, default: false, desc: "adds paranoid support to model" def model(name) - require_relative 'generator/model' + require_relative "generator/model" md = Model.new(name, options) md.create @@ -42,8 +44,8 @@ def model(name) md.create_test end - desc 'scaffold NAME', 'Generates a scaffold of endpoint, model, schema and serializer' - method_option :paranoid, type: :boolean, default: false, desc: 'adds paranoid support to model' + desc "scaffold NAME", "Generates a scaffold of endpoint, model, schema and serializer" + method_option :paranoid, type: :boolean, default: false, desc: "adds paranoid support to model" method_option :scaffold, type: :boolean, default: true, hide: true def scaffold(name) endpoint(name) @@ -52,18 +54,18 @@ def scaffold(name) serializer(name) end - desc 'schema NAME', 'Generates a schema' + desc "schema NAME", "Generates a schema" def schema(name) - require_relative 'generator/schema' + require_relative "generator/schema" sc = Schema.new(name, options) sc.create sc.rebuild end - desc 'serializer NAME', 'Generates a serializer' + desc "serializer NAME", "Generates a serializer" def serializer(name) - require_relative 'generator/serializer' + require_relative "generator/serializer" se = Serializer.new(name, options) se.create diff --git a/lib/pliny/commands/generator/base.rb b/lib/pliny/commands/generator/base.rb index 74937f86..06335e7f 100644 --- a/lib/pliny/commands/generator/base.rb +++ b/lib/pliny/commands/generator/base.rb @@ -1,8 +1,10 @@ -require 'active_support/inflector' -require 'ostruct' -require 'erb' -require 'fileutils' -require 'pliny' +# frozen_string_literal: true + +require "active_support/inflector" +require "ostruct" +require "erb" +require "fileutils" +require "pliny" module Pliny::Commands class Generator @@ -32,7 +34,7 @@ def pluralized_file_name end def table_name - name.tableize.tr('/', '_') + name.tableize.tr("/", "_") end def display(msg) @@ -41,7 +43,7 @@ def display(msg) def render_template(template_file, vars = {}) template_path = File.dirname(__FILE__) + "/../../templates/#{template_file}" - template = ERB.new(File.read(template_path), trim_mode: '>') + template = ERB.new(File.read(template_path), trim_mode: ">") context = OpenStruct.new(vars) template.result(context.instance_eval { binding }) end @@ -54,7 +56,7 @@ def write_template(template_file, destination_path, vars = {}) def write_file(destination_path) FileUtils.mkdir_p(File.dirname(destination_path)) - File.open(destination_path, 'w') do |f| + File.open(destination_path, "w") do |f| f.puts yield end end @@ -62,7 +64,7 @@ def write_file(destination_path) private def normalize_name(name) - name.underscore.tr(' ', '_') + name.underscore.tr(" ", "_") end end end diff --git a/lib/pliny/commands/generator/endpoint.rb b/lib/pliny/commands/generator/endpoint.rb index 26aa92ce..80247baf 100644 --- a/lib/pliny/commands/generator/endpoint.rb +++ b/lib/pliny/commands/generator/endpoint.rb @@ -1,43 +1,45 @@ -require_relative 'base' +# frozen_string_literal: true + +require_relative "base" module Pliny::Commands class Generator class Endpoint < Base def create endpoint = "./lib/endpoints/#{pluralized_file_name}.rb" - template = options[:scaffold] ? 'endpoint_scaffold.erb' : 'endpoint.erb' + template = options[:scaffold] ? "endpoint_scaffold.erb" : "endpoint.erb" write_template(template, endpoint, - plural_class_name: plural_class_name, - singular_class_name: singular_class_name, - field_name: field_name, - url_path: url_path) + plural_class_name: plural_class_name, + singular_class_name: singular_class_name, + field_name: field_name, + url_path: url_path,) display "created endpoint file #{endpoint}" - display 'add the following to lib/routes.rb:' + display "add the following to lib/routes.rb:" display " mount Endpoints::#{plural_class_name}" end def create_test test = "./spec/endpoints/#{pluralized_file_name}_spec.rb" - write_template('endpoint_test.erb', test, - plural_class_name: plural_class_name, - singular_class_name: singular_class_name, - url_path: url_path) + write_template("endpoint_test.erb", test, + plural_class_name: plural_class_name, + singular_class_name: singular_class_name, + url_path: url_path,) display "created test #{test}" end def create_acceptance_test test = "./spec/acceptance/#{pluralized_file_name}_spec.rb" - template = options[:scaffold] ? 'endpoint_scaffold_acceptance_test.erb' : 'endpoint_acceptance_test.erb' + template = options[:scaffold] ? "endpoint_scaffold_acceptance_test.erb" : "endpoint_acceptance_test.erb" write_template(template, test, - plural_class_name: plural_class_name, - field_name: field_name, - singular_class_name: singular_class_name, - url_path: url_path) + plural_class_name: plural_class_name, + field_name: field_name, + singular_class_name: singular_class_name, + url_path: url_path,) display "created test #{test}" end def url_path - '/' + name.pluralize.tr('_', '-') + "/" + name.pluralize.tr("_", "-") end end end diff --git a/lib/pliny/commands/generator/mediator.rb b/lib/pliny/commands/generator/mediator.rb index d70bd5bd..60304f5f 100644 --- a/lib/pliny/commands/generator/mediator.rb +++ b/lib/pliny/commands/generator/mediator.rb @@ -1,19 +1,21 @@ -require_relative 'base' +# frozen_string_literal: true + +require_relative "base" module Pliny::Commands class Generator class Mediator < Base def create mediator = "./lib/mediators/#{field_name}.rb" - write_template('mediator.erb', mediator, - singular_class_name: singular_class_name) + write_template("mediator.erb", mediator, + singular_class_name: singular_class_name,) display "created mediator file #{mediator}" end def create_test test = "./spec/mediators/#{field_name}_spec.rb" - write_template('mediator_test.erb', test, - singular_class_name: singular_class_name) + write_template("mediator_test.erb", test, + singular_class_name: singular_class_name,) display "created test #{test}" end end diff --git a/lib/pliny/commands/generator/migration.rb b/lib/pliny/commands/generator/migration.rb index dd816fa1..50e7d337 100644 --- a/lib/pliny/commands/generator/migration.rb +++ b/lib/pliny/commands/generator/migration.rb @@ -1,11 +1,13 @@ -require_relative 'base' +# frozen_string_literal: true + +require_relative "base" module Pliny::Commands class Generator class Migration < Base def create migration = "./db/migrate/#{Time.now.to_i}_#{name}.rb" - write_template('migration.erb', migration) + write_template("migration.erb", migration) display "created migration #{migration}" end end diff --git a/lib/pliny/commands/generator/model.rb b/lib/pliny/commands/generator/model.rb index 6b65a49a..fc93c72c 100644 --- a/lib/pliny/commands/generator/model.rb +++ b/lib/pliny/commands/generator/model.rb @@ -1,28 +1,30 @@ -require_relative 'base' +# frozen_string_literal: true + +require_relative "base" module Pliny::Commands class Generator class Model < Base def create model = "./lib/models/#{field_name}.rb" - write_template('model.erb', model, - singular_class_name: singular_class_name, - paranoid: options[:paranoid]) + write_template("model.erb", model, + singular_class_name: singular_class_name, + paranoid: options[:paranoid],) display "created model file #{model}" end def create_migration migration = "./db/migrate/#{Time.now.to_i}_create_#{table_name}.rb" - write_template('model_migration.erb', migration, - table_name: table_name, - paranoid: options[:paranoid]) + write_template("model_migration.erb", migration, + table_name: table_name, + paranoid: options[:paranoid],) display "created migration #{migration}" end def create_test test = "./spec/models/#{field_name}_spec.rb" - write_template('model_test.erb', test, - singular_class_name: singular_class_name) + write_template("model_test.erb", test, + singular_class_name: singular_class_name,) display "created test #{test}" end end diff --git a/lib/pliny/commands/generator/schema.rb b/lib/pliny/commands/generator/schema.rb index 293cae3e..62d31f49 100644 --- a/lib/pliny/commands/generator/schema.rb +++ b/lib/pliny/commands/generator/schema.rb @@ -1,5 +1,7 @@ -require_relative 'base' -require 'prmd' +# frozen_string_literal: true + +require_relative "base" +require "prmd" module Pliny::Commands class Generator diff --git a/lib/pliny/commands/generator/serializer.rb b/lib/pliny/commands/generator/serializer.rb index 24631417..486bfcbe 100644 --- a/lib/pliny/commands/generator/serializer.rb +++ b/lib/pliny/commands/generator/serializer.rb @@ -1,19 +1,21 @@ -require_relative 'base' +# frozen_string_literal: true + +require_relative "base" module Pliny::Commands class Generator class Serializer < Base def create serializer = "./lib/serializers/#{field_name}.rb" - write_template('serializer.erb', serializer, - singular_class_name: singular_class_name) + write_template("serializer.erb", serializer, + singular_class_name: singular_class_name,) display "created serializer file #{serializer}" end def create_test test = "./spec/serializers/#{field_name}_spec.rb" - write_template('serializer_test.erb', test, - singular_class_name: singular_class_name) + write_template("serializer_test.erb", test, + singular_class_name: singular_class_name,) display "created test #{test}" end end diff --git a/lib/pliny/commands/updater.rb b/lib/pliny/commands/updater.rb index d60039de..4bd78135 100644 --- a/lib/pliny/commands/updater.rb +++ b/lib/pliny/commands/updater.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "fileutils" require "pathname" require "pliny/version" @@ -21,7 +23,7 @@ def run! end version_current = get_current_version - version_target = Gem::Version.new(Pliny::VERSION) + version_target = Gem::Version.new(Pliny::VERSION) if version_current == version_target display "Version #{version_current} is current, nothing to update." @@ -50,7 +52,7 @@ def ensure_repo_available def get_current_version File.read("./Gemfile.lock").split("\n").each do |line| - next unless pliny_version = line.match(/pliny \(([\d+\.]+)\)/) + next unless (pliny_version = line.match(/pliny \(([\d+.]+)\)/)) return Gem::Version.new(pliny_version[1]) end end diff --git a/lib/pliny/config_helpers.rb b/lib/pliny/config_helpers.rb index 27a3ecc3..ed2453cc 100644 --- a/lib/pliny/config_helpers.rb +++ b/lib/pliny/config_helpers.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + module Pliny module CastingConfigHelpers - def mandatory(name, method=nil) + def mandatory(name, method = nil) value = cast(ENV.fetch(name.to_s.upcase), method) create(name, value) end - def optional(name, method=nil) + def optional(name, method = nil) value = cast(ENV[name.to_s.upcase], method) create(name, value) end - def override(name, default, method=nil) + def override(name, default, method = nil) value = cast(ENV.fetch(name.to_s.upcase, default), method) create(name, value) end @@ -24,7 +26,7 @@ def float end def bool - ->(v) { v.to_s=='true'} + ->(v) { v.to_s == "true" } end def string @@ -42,10 +44,8 @@ def symbol # optional :notype, array # => ['a', 'b'] def array(method = nil) - -> (v) do - if v - v.split(",").map{|a| cast(a, method) } - end + ->(v) do + v&.split(",")&.map { |a| cast(a, method) } end end @@ -76,7 +76,7 @@ def cast(value, method) def create(name, value) instance_variable_set(:"@#{name}", value) instance_eval "def #{name}; @#{name} end", __FILE__, __LINE__ - if value.kind_of?(TrueClass) || value.kind_of?(FalseClass) || value.kind_of?(NilClass) + if value.is_a?(TrueClass) || value.is_a?(FalseClass) || value.is_a?(NilClass) instance_eval "def #{name}?; !!@#{name} end", __FILE__, __LINE__ end end @@ -88,10 +88,10 @@ def env # PLINY_ENV is deprecated, but it might be still used by someone. def legacy_env - if ENV.key?('PLINY_ENV') + if ENV.key?("PLINY_ENV") warn "PLINY_ENV is deprecated in favour of APP_ENV, " \ "update .env file or application configuration." - ENV['PLINY_ENV'] + ENV["PLINY_ENV"] end end end @@ -130,7 +130,6 @@ def self.add_question_method(attr) end end end - end # Supress the "use RbConfig instead" warning diff --git a/lib/pliny/db_support.rb b/lib/pliny/db_support.rb index 0c3f755e..4530a38e 100644 --- a/lib/pliny/db_support.rb +++ b/lib/pliny/db_support.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "logger" require "sequel" require "sequel/extensions/migration" @@ -15,12 +17,12 @@ def self.setup?(database_url) @db = Sequel.connect(database_url) @db.test_connection @db.disconnect - return true + true rescue Sequel::DatabaseConnectionError - return false + false end - def self.run(url, sequel_log_io=StringIO.new) + def self.run(url, sequel_log_io = StringIO.new) logger = Logger.new(sequel_log_io) instance = new(url, logger) yield instance @@ -39,11 +41,11 @@ def initialize(url, sequel_logger) def exists?(name) res = db.fetch("SELECT 1 FROM pg_database WHERE datname = ?", name) - return res.count > 0 + res.count > 0 end def create(name) - db.run(%{CREATE DATABASE "#{name}"}) + db.run(%(CREATE DATABASE "#{name}")) end def migrate(target = nil) @@ -79,32 +81,30 @@ def status else :down end + elsif present_in_database + :file_missing else - if present_in_database - :file_missing - else - raise "error" # FIXME: better message - end + raise "error" # FIXME: better message end end end class MigrationStatusPresenter PADDING = 2 - UP = "UP".freeze - DOWN = "DOWN".freeze - FILE_MISSING = "FILE MISSING".freeze + UP = "UP" + DOWN = "DOWN" + FILE_MISSING = "FILE MISSING" STATUS_MAP = { up: UP, down: DOWN, - file_missing: FILE_MISSING + file_missing: FILE_MISSING, }.freeze STATUS_OPTIONS = [ UP, DOWN, - FILE_MISSING + FILE_MISSING, ].freeze attr_reader :migration_statuses @@ -125,7 +125,7 @@ def header [ barrier_row, header_row, - barrier_row + barrier_row, ] end @@ -137,20 +137,20 @@ def statuses def footer [ - barrier_row + barrier_row, ] end def barrier_row - "+#{'-' * (longest_status + PADDING)}+#{'-' * (longest_migration_name + PADDING)}+" + "+#{"-" * (longest_status + PADDING)}+#{"-" * (longest_migration_name + PADDING)}+" end def header_row - "|#{'STATUS'.center(longest_status + PADDING)}|#{'MIGRATION'.center(longest_migration_name + PADDING)}|" + "|#{"STATUS".center(longest_status + PADDING)}|#{"MIGRATION".center(longest_migration_name + PADDING)}|" end def status_row(migration_status) - "|#{STATUS_MAP[migration_status.status].center(longest_status + PADDING)}|#{' ' * (PADDING / 2)}#{migration_status.filename.ljust(longest_migration_name)}#{' ' * (PADDING / 2)}|" + "|#{STATUS_MAP[migration_status.status].center(longest_status + PADDING)}|#{" " * (PADDING / 2)}#{migration_status.filename.ljust(longest_migration_name)}#{" " * (PADDING / 2)}|" end private @@ -210,7 +210,7 @@ def disconnect private - MIGRATION_DIR = "./db/migrate".freeze + MIGRATION_DIR = "./db/migrate" private_constant :MIGRATION_DIR end end diff --git a/lib/pliny/error_reporters.rb b/lib/pliny/error_reporters.rb index d7723b25..159b2176 100644 --- a/lib/pliny/error_reporters.rb +++ b/lib/pliny/error_reporters.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::ErrorReporters extend self @@ -9,11 +11,9 @@ def notify(exception, context: {}, rack_env: {}) Pliny.log_exception(exception) error_reporters.each do |reporter| - begin - reporter.new.notify(exception, context: context, rack_env: rack_env) - rescue - Pliny.log_exception($!) - end + reporter.new.notify(exception, context: context, rack_env: rack_env) + rescue + Pliny.log_exception($!) end end end diff --git a/lib/pliny/error_reporters/rollbar.rb b/lib/pliny/error_reporters/rollbar.rb index f37c66cd..10d83b29 100644 --- a/lib/pliny/error_reporters/rollbar.rb +++ b/lib/pliny/error_reporters/rollbar.rb @@ -1,5 +1,7 @@ -require 'rollbar/exception_reporter' -require 'rollbar/request_data_extractor' +# frozen_string_literal: true + +require "rollbar/exception_reporter" +require "rollbar/request_data_extractor" module Pliny module ErrorReporters @@ -24,7 +26,7 @@ def fetch_scope(context:, rack_env:) scope[:person] = proc { extract_person_data_from_controller(rack_env) } end scope - rescue Exception => e + rescue Exception => e # rubocop:disable Lint/RescueException report_exception_to_rollbar(rack_env, e) raise end diff --git a/lib/pliny/errors.rb b/lib/pliny/errors.rb index 69db9f23..bf049ddc 100644 --- a/lib/pliny/errors.rb +++ b/lib/pliny/errors.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny module Errors class Error < StandardError @@ -19,9 +21,9 @@ class HTTPStatusError < Error attr_accessor :status def initialize(message = nil, id = nil, status = nil) - meta = Pliny::Errors::META[self.class] - message = message || meta[1] + "." - id = id || meta[1].downcase.tr(' ', '_').to_sym + meta = Pliny::Errors::META[self.class] + message ||= meta[1] + "." + id ||= meta[1].downcase.tr(" ", "_").to_sym @status = status || meta[0] super(message, id) end @@ -71,47 +73,47 @@ class GatewayTimeout < HTTPStatusError; end # 504 # Messages for nicer exceptions, from rfc2616 META = { - Continue => [100, 'Continue'], - SwitchingProtocols => [101, 'Switching protocols'], - OK => [200, 'OK'], - Created => [201, 'Created'], - Accepted => [202, 'Accepted'], - NonAuthoritativeInformation => [203, 'Non-authoritative information'], - NoContent => [204, 'No content'], - ResetContent => [205, 'Reset content'], - PartialContent => [206, 'Partial content'], - MultipleChoices => [300, 'Multiple choices'], - MovedPermanently => [301, 'Moved permanently'], - Found => [302, 'Found'], - SeeOther => [303, 'See other'], - NotModified => [304, 'Not modified'], - UseProxy => [305, 'Use proxy'], - TemporaryRedirect => [307, 'Temporary redirect'], - BadRequest => [400, 'Bad request'], - Unauthorized => [401, 'Unauthorized'], - PaymentRequired => [402, 'Payment required'], - Forbidden => [403, 'Forbidden'], - NotFound => [404, 'Not found'], - MethodNotAllowed => [405, 'Method not allowed'], - NotAcceptable => [406, 'Not acceptable'], - ProxyAuthenticationRequired => [407, 'Proxy authentication required'], - RequestTimeout => [408, 'Request timeout'], - Conflict => [409, 'Conflict'], - Gone => [410, 'Gone'], - LengthRequired => [411, 'Length required'], - PreconditionFailed => [412, 'Precondition failed'], - RequestEntityTooLarge => [413, 'Request entity too large'], - RequestURITooLong => [414, 'Request-URI too long'], - UnsupportedMediaType => [415, 'Unsupported media type'], - RequestedRangeNotSatisfiable => [416, 'Requested range not satisfiable'], - ExpectationFailed => [417, 'Expectation failed'], - UnprocessableEntity => [422, 'Unprocessable entity'], - TooManyRequests => [429, 'Too many requests'], - InternalServerError => [500, 'Internal server error'], - NotImplemented => [501, 'Not implemented'], - BadGateway => [502, 'Bad gateway'], - ServiceUnavailable => [503, 'Service unavailable'], - GatewayTimeout => [504, 'Gateway timeout'], + Continue => [100, "Continue"], + SwitchingProtocols => [101, "Switching protocols"], + OK => [200, "OK"], + Created => [201, "Created"], + Accepted => [202, "Accepted"], + NonAuthoritativeInformation => [203, "Non-authoritative information"], + NoContent => [204, "No content"], + ResetContent => [205, "Reset content"], + PartialContent => [206, "Partial content"], + MultipleChoices => [300, "Multiple choices"], + MovedPermanently => [301, "Moved permanently"], + Found => [302, "Found"], + SeeOther => [303, "See other"], + NotModified => [304, "Not modified"], + UseProxy => [305, "Use proxy"], + TemporaryRedirect => [307, "Temporary redirect"], + BadRequest => [400, "Bad request"], + Unauthorized => [401, "Unauthorized"], + PaymentRequired => [402, "Payment required"], + Forbidden => [403, "Forbidden"], + NotFound => [404, "Not found"], + MethodNotAllowed => [405, "Method not allowed"], + NotAcceptable => [406, "Not acceptable"], + ProxyAuthenticationRequired => [407, "Proxy authentication required"], + RequestTimeout => [408, "Request timeout"], + Conflict => [409, "Conflict"], + Gone => [410, "Gone"], + LengthRequired => [411, "Length required"], + PreconditionFailed => [412, "Precondition failed"], + RequestEntityTooLarge => [413, "Request entity too large"], + RequestURITooLong => [414, "Request-URI too long"], + UnsupportedMediaType => [415, "Unsupported media type"], + RequestedRangeNotSatisfiable => [416, "Requested range not satisfiable"], + ExpectationFailed => [417, "Expectation failed"], + UnprocessableEntity => [422, "Unprocessable entity"], + TooManyRequests => [429, "Too many requests"], + InternalServerError => [500, "Internal server error"], + NotImplemented => [501, "Not implemented"], + BadGateway => [502, "Bad gateway"], + ServiceUnavailable => [503, "Service unavailable"], + GatewayTimeout => [504, "Gateway timeout"], }.freeze end end diff --git a/lib/pliny/helpers/encode.rb b/lib/pliny/helpers/encode.rb index ec531b4b..a81908fc 100644 --- a/lib/pliny/helpers/encode.rb +++ b/lib/pliny/helpers/encode.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + module Pliny::Helpers module Encode def encode(object) - content_type :json, charset: 'utf-8' - if params[:pretty] == 'true' || Config.pretty_json + content_type :json, charset: "utf-8" + if params[:pretty] == "true" || Config.pretty_json JSON.pretty_generate(object) else JSON.generate(object) diff --git a/lib/pliny/helpers/params.rb b/lib/pliny/helpers/params.rb index d15aa6b7..9acab394 100644 --- a/lib/pliny/helpers/params.rb +++ b/lib/pliny/helpers/params.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::Helpers module Params def body_params diff --git a/lib/pliny/helpers/serialize.rb b/lib/pliny/helpers/serialize.rb index 9fe65859..62dbc206 100644 --- a/lib/pliny/helpers/serialize.rb +++ b/lib/pliny/helpers/serialize.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::Helpers module Serialize def self.registered(base) @@ -10,17 +12,17 @@ def serialize(data, structure = :default) serializer_class = settings.serializer_class if serializer_class.nil? - raise <<~eos.strip + raise <<~EOS.strip No serializer has been specified for this endpoint. Please specify one with `serializer Serializers::ModelName` in the endpoint. - eos + EOS end - env['pliny.serializer_arity'] = data.respond_to?(:size) ? data.size : 1 + env["pliny.serializer_arity"] = data.respond_to?(:size) ? data.size : 1 start = Time.now serializer_class.new(structure).serialize(data).tap do - env['pliny.serializer_timing'] = (Time.now - start).to_f + env["pliny.serializer_timing"] = (Time.now - start).to_f end end end diff --git a/lib/pliny/helpers/zulu_time.rb b/lib/pliny/helpers/zulu_time.rb index 5c05c3d3..f804881d 100644 --- a/lib/pliny/helpers/zulu_time.rb +++ b/lib/pliny/helpers/zulu_time.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module Pliny::Helpers module ZuluTime def zulu_time(time) - time ? time.getutc.strftime("%Y-%m-%dT%H:%M:%SZ") : nil + time&.getutc&.strftime("%Y-%m-%dT%H:%M:%SZ") end end end diff --git a/lib/pliny/log.rb b/lib/pliny/log.rb index 308e4d11..41d21a0e 100644 --- a/lib/pliny/log.rb +++ b/lib/pliny/log.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny module Log def log(data, &block) @@ -16,22 +18,20 @@ def log_exception(e, data = {}) exception_id = e.object_id # Log backtrace in reverse order for easier digestion. - if e.backtrace - e.backtrace.reverse.each do |backtrace| - log_to_stream(stderr || $stderr, merge_log_contexts( - exception_id: exception_id, - backtrace: backtrace - )) - end + e.backtrace&.reverse&.each do |backtrace| + log_to_stream(stderr || $stderr, merge_log_contexts( + exception_id: exception_id, + backtrace: backtrace, + ),) end # then log the exception message last so that it's as close to the end of # a log trace as possible data.merge!( - exception: true, - class: e.class.name, - message: e.message, - exception_id: exception_id + exception: true, + class: e.class.name, + message: e.message, + exception_id: exception_id, ) data[:status] = e.status if e.respond_to?(:status) @@ -42,10 +42,9 @@ def log_exception(e, data = {}) def context(data, &block) old = local_context self.local_context = old.merge(data) - res = block.call + block.call ensure self.local_context = old - res end def default_context=(default_context) @@ -102,24 +101,26 @@ def log_context end def log_to_stream(stream, data, &block) - unless block - data = log_scrubber.call(data) if log_scrubber - str = unparse(data) - stream.print(str + "\n") - else + if block data = data.dup start = Time.now log_to_stream(stream, data.merge(at: "start")) begin res = yield log_to_stream(stream, data.merge( - at: "finish", elapsed: (Time.now - start).to_f)) + at: "finish", elapsed: (Time.now - start).to_f, + ),) res rescue log_to_stream(stream, data.merge( - at: "exception", elapsed: (Time.now - start).to_f)) + at: "exception", elapsed: (Time.now - start).to_f, + ),) raise $! end + else + data = log_scrubber.call(data) if log_scrubber + str = unparse(data) + stream.print(str + "\n") end end @@ -129,11 +130,11 @@ def replace_newlines(v) def quote_string(v) if !v.include?('"') - %{"#{v}"} + %("#{v}") elsif !v.include?("'") - %{'#{v}'} + %('#{v}') else - %{"#{v.gsub(/"/, '\\"')}"} + %("#{v.gsub('"', '\\"')}") end end @@ -144,7 +145,7 @@ def unparse(attrs) def unparse_pair(k, v) v = v.call if v.is_a?(Proc) - if v == nil + if v.nil? nil elsif v == true k @@ -153,7 +154,7 @@ def unparse_pair(k, v) elsif v.is_a?(Time) "#{k}=#{v.iso8601}" else - v = "#{v}" + v = v.to_s v = replace_newlines(v) v = quote_string(v) if v =~ /\s/ diff --git a/lib/pliny/metrics.rb b/lib/pliny/metrics.rb index 7d8ecf9d..56ec8935 100644 --- a/lib/pliny/metrics.rb +++ b/lib/pliny/metrics.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny module Metrics extend self @@ -7,7 +9,7 @@ module Metrics @backends = [Backends::Logger] def count(*names, value: 1) - counts = Hash[names.map { |n| ["#{Config.app_name}.#{n}", value] }] + counts = names.map { |n| ["#{Config.app_name}.#{n}", value] }.to_h backends.each do |backend| report_and_catch { backend.report_counts(counts) } @@ -32,7 +34,7 @@ def measure(*inputs, &block) 0 end - measures = Hash[inputs.map { |n| ["#{Config.app_name}.#{n}", measurement] }] + measures = inputs.map { |n| ["#{Config.app_name}.#{n}", measurement] }.to_h backends.each do |backend| report_and_catch { backend.report_measures(measures) } diff --git a/lib/pliny/metrics/backends/logger.rb b/lib/pliny/metrics/backends/logger.rb index 887af51f..c141be37 100644 --- a/lib/pliny/metrics/backends/logger.rb +++ b/lib/pliny/metrics/backends/logger.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny module Metrics module Backends @@ -10,11 +12,11 @@ def self.report_measures(measures) Pliny.log(add_prefix(:measure, measures)) end - private - def self.add_prefix(type, metrics) - metrics.map { |k, v| [ "#{type}##{k}", v ] }.to_h + metrics.map { |k, v| ["#{type}##{k}", v] }.to_h end + + private_class_method :add_prefix end end end diff --git a/lib/pliny/middleware/canonical_log_line.rb b/lib/pliny/middleware/canonical_log_line.rb index 2b088210..4598e407 100644 --- a/lib/pliny/middleware/canonical_log_line.rb +++ b/lib/pliny/middleware/canonical_log_line.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::Middleware # Emits a "canonical log line", i.e. a single log line that contains as much # relevant information about a request as possible and which makes for a @@ -75,7 +77,7 @@ def call(env) # error # - if error = env["pliny.error"] + if (error = env["pliny.error"]) line.error_class = error.class.name line.error_message = error.message if error.is_a?(Pliny::Errors::Error) @@ -93,7 +95,7 @@ def call(env) line.request_method = request.request_method line.request_path = request.path_info line.request_user_agent = request.user_agent - if route = env["sinatra.route"] + if (route = env["sinatra.route"]) line.request_route_signature = route.split(" ").last end @@ -101,7 +103,7 @@ def call(env) # response # - if length = headers["Content-Length"] + if (length = headers["Content-Length"]) line.response_length = length.to_i end line.response_status = status diff --git a/lib/pliny/middleware/cors.rb b/lib/pliny/middleware/cors.rb index 430ebd18..ca13e69a 100644 --- a/lib/pliny/middleware/cors.rb +++ b/lib/pliny/middleware/cors.rb @@ -1,12 +1,13 @@ +# frozen_string_literal: true + module Pliny::Middleware class CORS - - ALLOW_METHODS = - %w( GET POST PUT PATCH DELETE OPTIONS ).freeze - ALLOW_HEADERS = - %w( Content-Type Accept Authorization Cache-Control If-None-Match If-Modified-Since Origin).freeze + ALLOW_METHODS = + %w[GET POST PUT PATCH DELETE OPTIONS].freeze + ALLOW_HEADERS = + %w[Content-Type Accept Authorization Cache-Control If-None-Match If-Modified-Since Origin].freeze EXPOSE_HEADERS = - %w( Cache-Control Content-Language Content-Type Expires Last-Modified Pragma ).freeze + %w[Cache-Control Content-Language Content-Type Expires Last-Modified Pragma].freeze @@additional_headers = [] @@ -44,12 +45,12 @@ def allow_headers def cors_headers(env) { - 'access-control-allow-origin' => env["HTTP_ORIGIN"], - 'access-control-allow-methods' => ALLOW_METHODS.join(', '), - 'access-control-allow-headers' => allow_headers.join(', '), - 'access-control-allow-credentials' => "true", - 'access-control-max-age' => "1728000", - 'access-control-expose-headers' => EXPOSE_HEADERS.join(', ') + "access-control-allow-origin" => env["HTTP_ORIGIN"], + "access-control-allow-methods" => ALLOW_METHODS.join(", "), + "access-control-allow-headers" => allow_headers.join(", "), + "access-control-allow-credentials" => "true", + "access-control-max-age" => "1728000", + "access-control-expose-headers" => EXPOSE_HEADERS.join(", "), } end end diff --git a/lib/pliny/middleware/instruments.rb b/lib/pliny/middleware/instruments.rb index a9b91f22..f9e095b3 100644 --- a/lib/pliny/middleware/instruments.rb +++ b/lib/pliny/middleware/instruments.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::Middleware class Instruments def initialize(app) @@ -9,24 +11,24 @@ def call(env) data = { instrumentation: true, - method: env["REQUEST_METHOD"], - path: env["PATH_INFO"] + method: env["REQUEST_METHOD"], + path: env["PATH_INFO"], } Pliny.log(data.merge(at: "start")) status, headers, response = @app.call(env) - if route = env["sinatra.route"] + if (route = env["sinatra.route"]) data.merge!(route_signature: route.split(" ").last) end elapsed = (Time.now - start).to_f Pliny.log(data.merge( - at: "finish", - status: status, - length: headers["Content-Length"], - elapsed: elapsed + at: "finish", + status: status, + length: headers["Content-Length"], + elapsed: elapsed, )) [status, headers, response] diff --git a/lib/pliny/middleware/metrics.rb b/lib/pliny/middleware/metrics.rb index aa3f543b..671b38d3 100644 --- a/lib/pliny/middleware/metrics.rb +++ b/lib/pliny/middleware/metrics.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::Middleware class Metrics def initialize(app) @@ -18,7 +20,7 @@ def call(env) elapsed = (Time.now - start).to_f Pliny::Metrics.measure("requests.latency", value: elapsed) - status_level = "#{status/100}xx" + status_level = "#{status / 100}xx" Pliny::Metrics.count("requests.status.#{status_level}") end diff --git a/lib/pliny/middleware/request_id.rb b/lib/pliny/middleware/request_id.rb index 1c620662..e4692da7 100644 --- a/lib/pliny/middleware/request_id.rb +++ b/lib/pliny/middleware/request_id.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # please add changes here to core's Instruments as well module Pliny::Middleware @@ -47,8 +49,8 @@ def raw_request_ids(env) # field as to whether it should be prefixed with `X-` or not. API went # with no prefix, but Hermes went with one. Support both formats on # input. - %w(HTTP_REQUEST_ID HTTP_X_REQUEST_ID).inject([]) do |request_ids, key| - if ids = env[key] + %w[HTTP_REQUEST_ID HTTP_X_REQUEST_ID].inject([]) do |request_ids, key| + if (ids = env[key]) request_ids += ids.split(",") end request_ids diff --git a/lib/pliny/middleware/request_store/clear.rb b/lib/pliny/middleware/request_store/clear.rb index 327fe9f0..e521c005 100644 --- a/lib/pliny/middleware/request_store/clear.rb +++ b/lib/pliny/middleware/request_store/clear.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + module Pliny::Middleware::RequestStore class Clear - def initialize(app, options={}) + def initialize(app, options = {}) @app = app @store = options[:store] || Pliny::RequestStore end diff --git a/lib/pliny/middleware/request_store/seed.rb b/lib/pliny/middleware/request_store/seed.rb index 7f4ffec8..11cd8b8d 100644 --- a/lib/pliny/middleware/request_store/seed.rb +++ b/lib/pliny/middleware/request_store/seed.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + module Pliny::Middleware::RequestStore class Seed - def initialize(app, options={}) + def initialize(app, options = {}) @app = app @store = options[:store] || Pliny::RequestStore end diff --git a/lib/pliny/middleware/rescue_errors.rb b/lib/pliny/middleware/rescue_errors.rb index 6809a1cf..bbc2b1db 100644 --- a/lib/pliny/middleware/rescue_errors.rb +++ b/lib/pliny/middleware/rescue_errors.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny::Middleware class RescueErrors def initialize(app, options = {}) diff --git a/lib/pliny/middleware/versioning.rb b/lib/pliny/middleware/versioning.rb index 3fa5d2fc..7001f488 100644 --- a/lib/pliny/middleware/versioning.rb +++ b/lib/pliny/middleware/versioning.rb @@ -1,8 +1,10 @@ -require 'http_accept' +# frozen_string_literal: true + +require "http_accept" module Pliny::Middleware class Versioning - def initialize(app, options={}) + def initialize(app, options = {}) @app = app @default = options[:default] || raise("missing=default") @app_name = options[:app_name] || raise("missing=app_name") @@ -22,17 +24,15 @@ def detect_api_version(env) version = nil media_types.map! do |media_type| if accept_headers.include?(media_type.format) - unless media_type.params['version'] - error = { id: :bad_version, message: <<-eos } -Please specify a version along with the MIME type. For example, `Accept: application/vnd.#{@app_name}+json; version=1`. - eos + unless media_type.params["version"] + error = { id: :bad_version, message: <<~EOS } + Please specify a version along with the MIME type. For example, `Accept: application/vnd.#{@app_name}+json; version=1`. + EOS return [400, { "content-type" => "application/json; charset=utf-8" }, - [JSON.generate(error)]] + [JSON.generate(error)],] end - unless version - version = media_type.params["version"] - end + version ||= media_type.params["version"] # replace the MIME with a simplified version for easier # parsing down the stack @@ -41,7 +41,7 @@ def detect_api_version(env) end media_type.to_s end - env['HTTP_ACCEPT'] = media_types.join(', ') + env["HTTP_ACCEPT"] = media_types.join(", ") version ||= @default set_api_version(env, version) diff --git a/lib/pliny/request_store.rb b/lib/pliny/request_store.rb index 4d5d190f..aaf4d5f3 100644 --- a/lib/pliny/request_store.rb +++ b/lib/pliny/request_store.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny module RequestStore def self.clear! @@ -6,12 +8,12 @@ def self.clear! def self.seed(env) store[:request_id] = - env["REQUEST_IDS"] ? env["REQUEST_IDS"].join(",") : nil + env["REQUEST_IDS"]&.join(",") # a global context that evolves over the lifetime of the request, and is # used to tag all log messages that it produces store[:log_context] = { - request_id: store[:request_id] + request_id: store[:request_id], } end diff --git a/lib/pliny/rollbar_logger.rb b/lib/pliny/rollbar_logger.rb index 7aa67511..f6cb208a 100644 --- a/lib/pliny/rollbar_logger.rb +++ b/lib/pliny/rollbar_logger.rb @@ -1,19 +1,21 @@ +# frozen_string_literal: true + module Pliny class RollbarLogger def debug(message) - log('debug', message) + log("debug", message) end def info(message) - log('info', message) + log("info", message) end def warn(message) - log('warn', message) + log("warn", message) end def error(message) - log('error', message) + log("error", message) end def log(level, message) diff --git a/lib/pliny/router.rb b/lib/pliny/router.rb index a90fdd1c..233964f6 100644 --- a/lib/pliny/router.rb +++ b/lib/pliny/router.rb @@ -1,8 +1,9 @@ -require 'sinatra/router' +# frozen_string_literal: true + +require "sinatra/router" module Pliny class Router < Sinatra::Router - # yield to a builder block in which all defined apps will only respond for # the given version def version(*versions, &block) diff --git a/lib/pliny/tasks.rb b/lib/pliny/tasks.rb index 4a1eddea..882a690d 100644 --- a/lib/pliny/tasks.rb +++ b/lib/pliny/tasks.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Dir[File.expand_path("../tasks", __FILE__) + "/*.rake"].sort.each do |f| load(f) end diff --git a/lib/pliny/tasks/db.rake b/lib/pliny/tasks/db.rake index 1ae7ada8..677e67ed 100644 --- a/lib/pliny/tasks/db.rake +++ b/lib/pliny/tasks/db.rake @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "logger" require "uri" require "pliny/utils" @@ -165,7 +167,7 @@ begin end def name_from_uri(uri) - URI.parse(uri).path[1..-1] + URI.parse(uri).path[1..] end end rescue LoadError diff --git a/lib/pliny/tasks/schema.rake b/lib/pliny/tasks/schema.rake index cc790ce0..e20af339 100644 --- a/lib/pliny/tasks/schema.rake +++ b/lib/pliny/tasks/schema.rake @@ -1,5 +1,7 @@ +# frozen_string_literal: true + desc "Rebuild schema.json" task :schema do - require 'pliny/commands/generator/schema' + require "pliny/commands/generator/schema" Pliny::Commands::Generator::Schema.new(nil).rebuild end diff --git a/lib/pliny/utils.rb b/lib/pliny/utils.rb index 2b32c6d9..cea4244c 100644 --- a/lib/pliny/utils.rb +++ b/lib/pliny/utils.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + module Pliny module Utils def self.parse_env(file) env = {} File.open(file).each do |line| - line = line.gsub(/#.*$/, '').strip + line = line.gsub(/#.*$/, "").strip next if line.empty? var, value = line.split("=", 2) value.gsub!(/^['"](.*)['"]$/, '\1') @@ -27,7 +29,7 @@ def self.require_glob(path) end class << self - alias :require_relative_glob :require_glob + alias_method :require_relative_glob, :require_glob end end end diff --git a/lib/pliny/version.rb b/lib/pliny/version.rb index 8b204fcc..6388bc83 100644 --- a/lib/pliny/version.rb +++ b/lib/pliny/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Pliny VERSION = "1.2.0" end diff --git a/lib/template/.rubocop.yml b/lib/template/.rubocop.yml index 0450d15d..eb43772b 100644 --- a/lib/template/.rubocop.yml +++ b/lib/template/.rubocop.yml @@ -23,6 +23,3 @@ Style/Documentation: Style/StringLiterals: Enabled: true EnforcedStyle: double_quotes - -Style/FrozenStringLiteralComment: - Enabled: false diff --git a/lib/template/Gemfile b/lib/template/Gemfile index 10ff6d33..bf0dc99b 100644 --- a/lib/template/Gemfile +++ b/lib/template/Gemfile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + source "https://rubygems.org" ruby "2.4.0" diff --git a/lib/template/Rakefile b/lib/template/Rakefile index 861b2e2b..2f90a0ad 100644 --- a/lib/template/Rakefile +++ b/lib/template/Rakefile @@ -1,3 +1,4 @@ +# frozen_string_literal: true require "pliny/tasks" diff --git a/lib/template/bin/console b/lib/template/bin/console index 31e16488..515a246a 100755 --- a/lib/template/bin/console +++ b/lib/template/bin/console @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# frozen_string_literal: true require_relative "../lib/application" @@ -15,7 +16,7 @@ Pry.prompt = [ proc do |target_self, nest_level, pry| basic_prompt(target_self, nest_level, pry) + "* " - end + end, ] Pry.start diff --git a/lib/template/bin/run b/lib/template/bin/run index 45dc3835..638bd462 100755 --- a/lib/template/bin/run +++ b/lib/template/bin/run @@ -1,7 +1,10 @@ #!/usr/bin/env ruby +# frozen_string_literal: true # rubocop:disable Security/Eval require_relative "../lib/application" eval ARGV.join(" ") + +# rubocop:enable Security/Eval diff --git a/lib/template/config.ru b/lib/template/config.ru index 0d3a5a85..8a2f9995 100644 --- a/lib/template/config.ru +++ b/lib/template/config.ru @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require_relative "lib/application" $stdout.sync = true diff --git a/lib/template/config/config.rb b/lib/template/config/config.rb index 713d6c4a..2406e2ec 100644 --- a/lib/template/config/config.rb +++ b/lib/template/config/config.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "pliny/config_helpers" # Access all config keys like the following: @@ -13,23 +15,23 @@ module Config mandatory :database_url, string # Optional -- value is returned or `nil` if it wasn't present. - optional :app_name, string - optional :versioning_default, string + optional :app_name, string + optional :versioning_default, string optional :versioning_app_name, string # Override -- value is returned or the set default. - override :database_timeout, 10, int - override :db_pool, 5, int - override :deployment, "production", string - override :force_ssl, true, bool - override :app_env, "production", string - override :port, 5000, int - override :pretty_json, false, bool - override :puma_max_threads, 16, int - override :puma_min_threads, 1, int - override :puma_workers, 3, int - override :raise_errors, false, bool - override :root, File.expand_path("../../", __FILE__), string - override :timeout, 10, int - override :versioning, false, bool + override :database_timeout, 10, int + override :db_pool, 5, int + override :deployment, "production", string + override :force_ssl, true, bool + override :app_env, "production", string + override :port, 5000, int + override :pretty_json, false, bool + override :puma_max_threads, 16, int + override :puma_min_threads, 1, int + override :puma_workers, 3, int + override :raise_errors, false, bool + override :root, File.expand_path("../../", __FILE__), string + override :timeout, 10, int + override :versioning, false, bool end diff --git a/lib/template/config/initializers/database.rb b/lib/template/config/initializers/database.rb index 1f1bff95..0b6d5fd1 100644 --- a/lib/template/config/initializers/database.rb +++ b/lib/template/config/initializers/database.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + database_setup_proc = lambda do |conn| # identify postgres connections coming from this process in pg_stat_activity process_identifier = ENV["DYNO"] || File.basename($PROGRAM_NAME).gsub(/\W+/, "_") @@ -6,5 +8,5 @@ end DB = Sequel.connect(Config.database_url, - max_connections: Config.db_pool, - after_connect: database_setup_proc) + max_connections: Config.db_pool, + after_connect: database_setup_proc,) diff --git a/lib/template/config/initializers/log.rb b/lib/template/config/initializers/log.rb index 2f3bb2ec..0f62e728 100644 --- a/lib/template/config/initializers/log.rb +++ b/lib/template/config/initializers/log.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Pliny.default_context = {} Pliny.default_context[:app] = Config.app_name if Config.app_name Pliny.default_context[:deployment] = Config.deployment diff --git a/lib/template/config/initializers/metrics.rb b/lib/template/config/initializers/metrics.rb index c2b8aa09..ea59d6bf 100644 --- a/lib/template/config/initializers/metrics.rb +++ b/lib/template/config/initializers/metrics.rb @@ -1 +1,3 @@ +# frozen_string_literal: true + Pliny::Metrics.backends = [Pliny::Metrics::Backends::Logger] diff --git a/lib/template/config/initializers/rollbar.rb b/lib/template/config/initializers/rollbar.rb index 79329f26..365e584b 100644 --- a/lib/template/config/initializers/rollbar.rb +++ b/lib/template/config/initializers/rollbar.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "pliny/error_reporters/rollbar" Pliny::ErrorReporters.error_reporters << Pliny::ErrorReporters::Rollbar diff --git a/lib/template/config/puma.rb b/lib/template/config/puma.rb index 53a24c02..0d1100b8 100644 --- a/lib/template/config/puma.rb +++ b/lib/template/config/puma.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "./config/config" environment Config.rack_env diff --git a/lib/template/db/seeds.rb b/lib/template/db/seeds.rb index 0f14889d..d462bd7f 100644 --- a/lib/template/db/seeds.rb +++ b/lib/template/db/seeds.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # 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 diff --git a/lib/template/lib/application.rb b/lib/template/lib/application.rb index 898a00b5..32320b85 100644 --- a/lib/template/lib/application.rb +++ b/lib/template/lib/application.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "bundler" Bundler.require diff --git a/lib/template/lib/endpoints/base.rb b/lib/template/lib/endpoints/base.rb index dd925574..1729086a 100644 --- a/lib/template/lib/endpoints/base.rb +++ b/lib/template/lib/endpoints/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Endpoints # The base class for all Sinatra-based endpoints. Use sparingly. class Base < Sinatra::Base diff --git a/lib/template/lib/endpoints/health.rb b/lib/template/lib/endpoints/health.rb index f44eb836..9bc14e65 100644 --- a/lib/template/lib/endpoints/health.rb +++ b/lib/template/lib/endpoints/health.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Endpoints class Health < Base namespace "/health" do diff --git a/lib/template/lib/endpoints/root.rb b/lib/template/lib/endpoints/root.rb index 22297709..dd4a7fe3 100644 --- a/lib/template/lib/endpoints/root.rb +++ b/lib/template/lib/endpoints/root.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Endpoints class Root < Base get "/" do diff --git a/lib/template/lib/endpoints/schema.rb b/lib/template/lib/endpoints/schema.rb index 94e50bb2..7fd982ea 100644 --- a/lib/template/lib/endpoints/schema.rb +++ b/lib/template/lib/endpoints/schema.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Endpoints class Schema < Base get "/schema.json" do diff --git a/lib/template/lib/initializer.rb b/lib/template/lib/initializer.rb index 1360c70c..e8e580b8 100644 --- a/lib/template/lib/initializer.rb +++ b/lib/template/lib/initializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Initializer def self.run require_config @@ -11,7 +13,7 @@ def self.require_config end def self.require_lib - require! %w( + require! %w[ lib/serializers/base lib/serializers/**/* lib/endpoints/base @@ -19,13 +21,13 @@ def self.require_lib lib/mediators/base lib/mediators/**/* lib/routes - ) + ] end def self.require_models - require! %w( + require! %w[ lib/models/**/* - ) + ] end def self.require_initializers diff --git a/lib/template/lib/mediators/base.rb b/lib/template/lib/mediators/base.rb index f0cb45b8..d138552e 100644 --- a/lib/template/lib/mediators/base.rb +++ b/lib/template/lib/mediators/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Mediators class Base def self.run(options = {}) diff --git a/lib/template/lib/routes.rb b/lib/template/lib/routes.rb index 832e13cc..4d59222f 100644 --- a/lib/template/lib/routes.rb +++ b/lib/template/lib/routes.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Routes = Rack::Builder.new do use Pliny::Middleware::RequestStore::Clear, store: Pliny::RequestStore use Pliny::Middleware::CORS @@ -6,18 +8,18 @@ use Pliny::Middleware::Metrics use Pliny::Middleware::Instruments use Pliny::Middleware::CanonicalLogLine, - emitter: -> (data) { - Pliny.log_with_default_context({ canonical_log_line: true }.merge(data)) - } + emitter: ->(data) { + Pliny.log_with_default_context({ canonical_log_line: true }.merge(data)) + } use Pliny::Middleware::RescueErrors, raise: Config.raise_errors? if Config.timeout.positive? use Rack::Timeout, - service_timeout: Config.timeout + service_timeout: Config.timeout end if Config.versioning? use Pliny::Middleware::Versioning, - default: Config.versioning_default, - app_name: Config.versioning_app_name + default: Config.versioning_default, + app_name: Config.versioning_app_name end use Rack::Deflater use Rack::MethodOverride diff --git a/lib/template/lib/serializers/base.rb b/lib/template/lib/serializers/base.rb index 8006eb20..ead7c738 100644 --- a/lib/template/lib/serializers/base.rb +++ b/lib/template/lib/serializers/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Serializers class Base extend Pliny::Helpers::ZuluTime diff --git a/lib/template/lib/tasks/rubocop.rake b/lib/template/lib/tasks/rubocop.rake index 3a3b67fb..b1ba8511 100644 --- a/lib/template/lib/tasks/rubocop.rake +++ b/lib/template/lib/tasks/rubocop.rake @@ -1,3 +1,5 @@ +# frozen_string_literal: true + if Gem.loaded_specs.has_key?("rubocop-rspec") require "rubocop/rake_task" diff --git a/lib/template/lib/tasks/spec.rake b/lib/template/lib/tasks/spec.rake index f8d1a98c..890cdb67 100644 --- a/lib/template/lib/tasks/spec.rake +++ b/lib/template/lib/tasks/spec.rake @@ -1,3 +1,4 @@ +# frozen_string_literal: true # define our own version of the spec task because rspec might not be available # in the production environment, so we can't rely on RSpec::Core::RakeTask @@ -6,7 +7,7 @@ task :spec do require "rspec/core" code = RSpec::Core::Runner.run( ["./spec"], - $stderr, $stdout + $stderr, $stdout, ) exit(code) unless code.zero? end diff --git a/lib/template/spec/endpoints/health_spec.rb b/lib/template/spec/endpoints/health_spec.rb index ec0bc431..d4116305 100644 --- a/lib/template/spec/endpoints/health_spec.rb +++ b/lib/template/spec/endpoints/health_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" RSpec.describe Endpoints::Health do diff --git a/lib/template/spec/endpoints/schema_spec.rb b/lib/template/spec/endpoints/schema_spec.rb index 31c9cbc0..9e114056 100644 --- a/lib/template/spec/endpoints/schema_spec.rb +++ b/lib/template/spec/endpoints/schema_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" RSpec.describe Endpoints::Schema do diff --git a/lib/template/spec/spec_helper.rb b/lib/template/spec/spec_helper.rb index b12d1b6a..f0aee210 100644 --- a/lib/template/spec/spec_helper.rb +++ b/lib/template/spec/spec_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only diff --git a/lib/template/spec/spec_support/auto_define_rack_app.rb b/lib/template/spec/spec_support/auto_define_rack_app.rb index 1352c44a..1e858860 100644 --- a/lib/template/spec/spec_support/auto_define_rack_app.rb +++ b/lib/template/spec/spec_support/auto_define_rack_app.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.configure do |config| config.before(:context) do |spec| # weird ruby syntax, but test if the described_class inherits Sinatra::Base: diff --git a/lib/template/spec/spec_support/coverage.rb b/lib/template/spec/spec_support/coverage.rb index 8d5071a9..480cab6d 100644 --- a/lib/template/spec/spec_support/coverage.rb +++ b/lib/template/spec/spec_support/coverage.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # setting ENV["CI"] configures simplecov for continuous integration output # setting ENV["COVERAGE"] generates a report when running tests locally if ENV["COVERAGE"] || ENV["CI"] diff --git a/lib/template/spec/spec_support/log.rb b/lib/template/spec/spec_support/log.rb index 6034b8e6..e6d5d99b 100644 --- a/lib/template/spec/spec_support/log.rb +++ b/lib/template/spec/spec_support/log.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + unless ENV["TEST_LOGS"] == "true" module Pliny module Log diff --git a/pliny.gemspec b/pliny.gemspec index c25b76a7..662618c5 100644 --- a/pliny.gemspec +++ b/pliny.gemspec @@ -1,19 +1,21 @@ +# frozen_string_literal: true + $:.unshift File.expand_path("../lib", __FILE__) require "pliny/version" Gem::Specification.new do |gem| - gem.name = "pliny" + gem.name = "pliny" gem.version = Pliny::VERSION - gem.authors = ["Brandur Leach", "Pedro Belo"] - gem.email = ["brandur@mutelight.org", "pedrobelo@gmail.com"] - gem.homepage = "https://github.com/interagent/pliny" - gem.summary = "Basic tooling to support API apps in Sinatra" + gem.authors = ["Brandur Leach", "Pedro Belo"] + gem.email = ["brandur@mutelight.org", "pedrobelo@gmail.com"] + gem.homepage = "https://github.com/interagent/pliny" + gem.summary = "Basic tooling to support API apps in Sinatra" gem.description = "Pliny is a set of base classes and helpers to help developers write excellent APIs in Sinatra" - gem.license = "MIT" + gem.license = "MIT" - gem.executables = %x{ git ls-files }.split("\n").select { |d| d =~ /^bin\// }.map { |d| d.gsub(/^bin\//, "") } - gem.files = %x{ git ls-files }.split("\n").select { |d| d =~ %r{^(License|README|bin/|data/|ext/|lib/|spec/|test/)} } + gem.executables = `git ls-files`.split("\n").select { |d| d =~ /^bin\// }.map { |d| d.gsub(/^bin\//, "") } + gem.files = `git ls-files`.split("\n").select { |d| d =~ %r{^(License|README|bin/|data/|ext/|lib/|spec/|test/)} } gem.required_ruby_version = ">= 3.2" diff --git a/spec/canonical_log_line_helpers_spec.rb b/spec/canonical_log_line_helpers_spec.rb index 0290dec0..94702266 100644 --- a/spec/canonical_log_line_helpers_spec.rb +++ b/spec/canonical_log_line_helpers_spec.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require "spec_helper" -describe Pliny::CanonicalLogLineHelpers do - class TestCanonicalLogLine - include Pliny::CanonicalLogLineHelpers +class TestCanonicalLogLine + include Pliny::CanonicalLogLineHelpers - log_field :field_float, Float - log_field :field_integer, Integer - log_field :field_string, String - end + log_field :field_float, Float + log_field :field_integer, Integer + log_field :field_string, String +end +describe Pliny::CanonicalLogLineHelpers do it "allows a field to be set" do line = TestCanonicalLogLine.new line.field_string = "foo" @@ -34,6 +36,6 @@ class TestCanonicalLogLine line.field_integer = 42 line.field_string = "foo" assert_equal({ field_float: 3.14, field_integer: 42, field_string: "foo" }, - line.to_h) + line.to_h,) end end diff --git a/spec/commands/creator_spec.rb b/spec/commands/creator_spec.rb index 567c31a7..f89d04a7 100644 --- a/spec/commands/creator_spec.rb +++ b/spec/commands/creator_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "pliny/commands/creator" require "spec_helper" diff --git a/spec/commands/generator/base_spec.rb b/spec/commands/generator/base_spec.rb index 6b138245..90aab400 100644 --- a/spec/commands/generator/base_spec.rb +++ b/spec/commands/generator/base_spec.rb @@ -1,120 +1,122 @@ -require 'pliny/commands/generator' -require 'pliny/commands/generator/base' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/generator" +require "pliny/commands/generator/base" +require "spec_helper" describe Pliny::Commands::Generator::Base do def generator(name, options = {}, stream = StringIO.new) Pliny::Commands::Generator::Base.new(name, options, stream) end - describe '#name' do - it 'generates a normalized name given differents argument formats' do + describe "#name" do + it "generates a normalized name given differents argument formats" do [ - 'resource history', - 'resource-history', - 'resource_history', - 'ResourceHistory' + "resource history", + "resource-history", + "resource_history", + "ResourceHistory", ].each do |argument| actual = generator(argument).name - assert_equal 'resource_history', actual + assert_equal "resource_history", actual end end end - describe '#singular_class_name' do - it 'builds a class name for an endpoint' do - actual = generator('resource_histories').singular_class_name - assert_equal 'ResourceHistory', actual + describe "#singular_class_name" do + it "builds a class name for an endpoint" do + actual = generator("resource_histories").singular_class_name + assert_equal "ResourceHistory", actual end end - describe '#plural_class_name' do - it 'builds a class name for a model' do - actual = generator('resource_histories').plural_class_name - assert_equal 'ResourceHistories', actual + describe "#plural_class_name" do + it "builds a class name for a model" do + actual = generator("resource_histories").plural_class_name + assert_equal "ResourceHistories", actual end end - describe '#field_name' do - it 'uses the singular form' do - actual = generator('resource_histories').field_name - assert_equal 'resource_history', actual + describe "#field_name" do + it "uses the singular form" do + actual = generator("resource_histories").field_name + assert_equal "resource_history", actual end end - describe '#pluralized_file_name' do - it 'uses the plural form' do - actual = generator('resource_history').pluralized_file_name - assert_equal 'resource_histories', actual + describe "#pluralized_file_name" do + it "uses the plural form" do + actual = generator("resource_history").pluralized_file_name + assert_equal "resource_histories", actual end - describe 'when name with slashs' do - it 'handles slashs as directory' do - actual = generator('resource/history').pluralized_file_name - assert_equal 'resource/histories', actual + describe "when name with slashs" do + it "handles slashs as directory" do + actual = generator("resource/history").pluralized_file_name + assert_equal "resource/histories", actual end end end - describe '#table_name' do - it 'uses the plural form' do - actual = generator('resource_history').table_name - assert_equal 'resource_histories', actual + describe "#table_name" do + it "uses the plural form" do + actual = generator("resource_history").table_name + assert_equal "resource_histories", actual end - describe 'when name with slashs' do - it 'handles slashs as underscores' do - actual = generator('resource/history').table_name - assert_equal 'resource_histories', actual + describe "when name with slashs" do + it "handles slashs as underscores" do + actual = generator("resource/history").table_name + assert_equal "resource_histories", actual end end end - describe '#display' do - it 'puts given message into stream' do + describe "#display" do + it "puts given message into stream" do stream = StringIO.new - message = 'Hello world' - generator('resource_history', {}, stream).display(message) + message = "Hello world" + generator("resource_history", {}, stream).display(message) assert_includes stream.string, message end end - describe '#render_template' do - it 'renders template into a string' do - template = generator('resource_history').render_template('endpoint.erb') - assert_match /module Endpoints/, template + describe "#render_template" do + it "renders template into a string" do + template = generator("resource_history").render_template("endpoint.erb") + assert_match(/module Endpoints/, template) end end - describe '#write_template' do - let(:destination_path) { File.join(Dir.mktmpdir, 'endpoint.rb') } + describe "#write_template" do + let(:destination_path) { File.join(Dir.mktmpdir, "endpoint.rb") } before do - generator('resource_history').write_template('endpoint.erb', destination_path) + generator("resource_history").write_template("endpoint.erb", destination_path) end - it 'renders given template into a file by given path' do + it "renders given template into a file by given path" do assert File.exist?(destination_path) - assert_match /module Endpoints/, File.read(destination_path) + assert_match(/module Endpoints/, File.read(destination_path)) end end - - describe '#write_file' do - let(:destination_path) { File.join(Dir.mktmpdir, 'foo.txt') } + + describe "#write_file" do + let(:destination_path) { File.join(Dir.mktmpdir, "foo.txt") } before do - generator('resource_history').write_file(destination_path) do - 'Hello world' + generator("resource_history").write_file(destination_path) do + "Hello world" end end - it 'creates a file by given path' do + it "creates a file by given path" do assert File.exist?(destination_path) end - it 'writes given content into a file' do - assert_match /Hello world/, File.read(destination_path) + it "writes given content into a file" do + assert_match(/Hello world/, File.read(destination_path)) end end end diff --git a/spec/commands/generator/endpoint_spec.rb b/spec/commands/generator/endpoint_spec.rb index f73b7dc9..7accc51e 100644 --- a/spec/commands/generator/endpoint_spec.rb +++ b/spec/commands/generator/endpoint_spec.rb @@ -1,26 +1,28 @@ -require 'pliny/commands/generator' -require 'pliny/commands/generator/endpoint' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/generator" +require "pliny/commands/generator/endpoint" +require "spec_helper" describe Pliny::Commands::Generator::Endpoint do subject { Pliny::Commands::Generator::Endpoint.new(endpoint_name, {}, StringIO.new) } - let(:endpoint_name) { 'resource_history' } + let(:endpoint_name) { "resource_history" } - describe '#url_path' do - it 'builds a URL path' do - assert_equal '/resource-histories', subject.url_path + describe "#url_path" do + it "builds a URL path" do + assert_equal "/resource-histories", subject.url_path end end - describe 'template' do + describe "template" do before do # render the stub endpoint template to a string template = subject.render_template("endpoint.erb", plural_class_name: "Artists", - url_path: "/artists") + url_path: "/artists",) # eval and assign it to rack_app so tests are pointing to it - @rack_app = eval(template) + @rack_app = eval(template) # rubocop:disable Security/Eval end it "defines a stub GET /" do @@ -32,26 +34,25 @@ it "defines a stub POST /" do post "/artists" assert_equal 201, last_response.status - assert_equal Hash.new, JSON.parse(last_response.body) + assert_equal({}, JSON.parse(last_response.body)) end it "defines a stub GET /:id" do get "/artists/123" assert_equal 200, last_response.status - assert_equal Hash.new, JSON.parse(last_response.body) + assert_equal({}, JSON.parse(last_response.body)) end it "defines a stub PATCH /:id" do patch "/artists/123" assert_equal 200, last_response.status - assert_equal Hash.new, JSON.parse(last_response.body) + assert_equal({}, JSON.parse(last_response.body)) end it "defines a stub DELETE /:id" do delete "/artists/123" assert_equal 200, last_response.status - assert_equal Hash.new, JSON.parse(last_response.body) + assert_equal({}, JSON.parse(last_response.body)) end - end end diff --git a/spec/commands/generator/mediator_spec.rb b/spec/commands/generator/mediator_spec.rb index 78acf3aa..cb9d1a66 100644 --- a/spec/commands/generator/mediator_spec.rb +++ b/spec/commands/generator/mediator_spec.rb @@ -1,24 +1,26 @@ -require 'pliny/commands/generator/mediator' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/generator/mediator" +require "spec_helper" describe Pliny::Commands::Generator::Mediator do - subject { described_class.new('creator', {}, StringIO.new) } + subject { described_class.new("creator", {}, StringIO.new) } around do |example| Dir.chdir(Dir.mktmpdir, &example) end - describe '#create' do - it 'creates a mediator file' do + describe "#create" do + it "creates a mediator file" do subject.create - assert File.exist?('lib/mediators/creator.rb') + assert File.exist?("lib/mediators/creator.rb") end end - describe '#create_test' do - it 'creates a mediator test file' do + describe "#create_test" do + it "creates a mediator test file" do subject.create_test - assert File.exist?('spec/mediators/creator_spec.rb') + assert File.exist?("spec/mediators/creator_spec.rb") end end end diff --git a/spec/commands/generator/migration_spec.rb b/spec/commands/generator/migration_spec.rb index 4f421009..4479aa37 100644 --- a/spec/commands/generator/migration_spec.rb +++ b/spec/commands/generator/migration_spec.rb @@ -1,15 +1,17 @@ -require 'pliny/commands/generator/migration' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/generator/migration" +require "spec_helper" describe Pliny::Commands::Generator::Migration do - subject { described_class.new('create_artists', {}, StringIO.new) } + subject { described_class.new("create_artists", {}, StringIO.new) } around do |example| Dir.chdir(Dir.mktmpdir, &example) end - describe '#create' do - it 'creates a migration file' do + describe "#create" do + it "creates a migration file" do subject.create assert_equal 1, Dir.glob("db/migrate/*_create_artists.rb").size end diff --git a/spec/commands/generator/model_spec.rb b/spec/commands/generator/model_spec.rb index 5ebfe2ca..c6225625 100644 --- a/spec/commands/generator/model_spec.rb +++ b/spec/commands/generator/model_spec.rb @@ -1,31 +1,33 @@ -require 'pliny/commands/generator/model' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/generator/model" +require "spec_helper" describe Pliny::Commands::Generator::Model do - subject { described_class.new('artist', {}, StringIO.new) } + subject { described_class.new("artist", {}, StringIO.new) } around do |example| Dir.chdir(Dir.mktmpdir, &example) end - describe '#create' do - it 'creates a model file' do + describe "#create" do + it "creates a model file" do subject.create - assert File.exist?('lib/models/artist.rb') + assert File.exist?("lib/models/artist.rb") end end - describe '#create_migration' do - it 'creates a migration file' do + describe "#create_migration" do + it "creates a migration file" do subject.create_migration assert_equal 1, Dir.glob("db/migrate/*_create_artists.rb").size end end - describe '#create_test' do - it 'creates a model test file' do + describe "#create_test" do + it "creates a model test file" do subject.create_test - assert File.exist?('spec/models/artist_spec.rb') + assert File.exist?("spec/models/artist_spec.rb") end end end diff --git a/spec/commands/generator/schema_spec.rb b/spec/commands/generator/schema_spec.rb index 6a48d5e4..1b77b251 100644 --- a/spec/commands/generator/schema_spec.rb +++ b/spec/commands/generator/schema_spec.rb @@ -1,11 +1,13 @@ -require 'pliny/commands/creator' -require 'pliny/commands/generator' -require 'pliny/commands/generator/schema' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/creator" +require "pliny/commands/generator" +require "pliny/commands/generator/schema" +require "spec_helper" describe Pliny::Commands::Generator::Schema do let(:stream) { StringIO.new } - subject { Pliny::Commands::Generator::Schema.new('artist', {}, stream) } + subject { Pliny::Commands::Generator::Schema.new("artist", {}, stream) } around do |example| Dir.mktmpdir do |dir| @@ -16,66 +18,65 @@ end end - - describe '#create' do - context 'with new layout' do + describe "#create" do + context "with new layout" do before do subject.create end - it 'creates a schema' do - assert File.exist?('schema/schemata/artist.yaml') + it "creates a schema" do + assert File.exist?("schema/schemata/artist.yaml") end end - context 'with legacy layout' do + context "with legacy layout" do before do - FileUtils.mkdir_p('./docs/schema/schemata') - FileUtils.cp('./schema/meta.json', './docs/schema') + FileUtils.mkdir_p("./docs/schema/schemata") + FileUtils.cp("./schema/meta.json", "./docs/schema") subject.create end - it 'creates a legacy schema' do - assert File.exist?('docs/schema/schemata/artist.yaml') + it "creates a legacy schema" do + assert File.exist?("docs/schema/schemata/artist.yaml") end - it 'warns' do + it "warns" do assert_match(/WARNING/m, stream.string) end end end - describe '#rebuild' do - context 'with nil as the name argument (as used in schema.rake)' do - it 'rebuilds the schema with prmd' do + describe "#rebuild" do + context "with nil as the name argument (as used in schema.rake)" do + it "rebuilds the schema with prmd" do assert_output(/rebuilt/) do Pliny::Commands::Generator::Schema.new(nil).rebuild end end end - context 'with new layout' do + context "with new layout" do before do subject.rebuild end - it 'rebuilds schema.json' do - assert File.exist?('./schema/schema.json') + it "rebuilds schema.json" do + assert File.exist?("./schema/schema.json") end end - context 'with legacy layout' do + context "with legacy layout" do before do - FileUtils.mkdir_p('./docs/schema/schemata') - FileUtils.cp('./schema/meta.json', './docs/schema') + FileUtils.mkdir_p("./docs/schema/schemata") + FileUtils.cp("./schema/meta.json", "./docs/schema") subject.rebuild end - it 'rebuilds legacy schema.json' do - assert File.exist?('docs/schema.json') + it "rebuilds legacy schema.json" do + assert File.exist?("docs/schema.json") end - it 'warns' do + it "warns" do assert_match(/WARNING/m, stream.string) end end diff --git a/spec/commands/generator/serializer_spec.rb b/spec/commands/generator/serializer_spec.rb index 7f0745b8..c07db59f 100644 --- a/spec/commands/generator/serializer_spec.rb +++ b/spec/commands/generator/serializer_spec.rb @@ -1,24 +1,26 @@ -require 'pliny/commands/generator/serializer' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/generator/serializer" +require "spec_helper" describe Pliny::Commands::Generator::Serializer do - subject { described_class.new('artist', {}, StringIO.new) } + subject { described_class.new("artist", {}, StringIO.new) } around do |example| Dir.chdir(Dir.mktmpdir, &example) end - describe '#create' do - it 'creates a serializer file' do + describe "#create" do + it "creates a serializer file" do subject.create - assert File.exist?('lib/serializers/artist.rb') + assert File.exist?("lib/serializers/artist.rb") end end - describe '#create_test' do - it 'creates a serializer test file' do + describe "#create_test" do + it "creates a serializer test file" do subject.create_test - assert File.exist?('spec/serializers/artist_spec.rb') + assert File.exist?("spec/serializers/artist_spec.rb") end end end diff --git a/spec/commands/generator_spec.rb b/spec/commands/generator_spec.rb index fffeb398..0e2803df 100644 --- a/spec/commands/generator_spec.rb +++ b/spec/commands/generator_spec.rb @@ -1,7 +1,9 @@ -require 'pliny/commands/creator' -require 'pliny/commands/generator' -require 'pliny/commands/generator/base' -require 'spec_helper' +# frozen_string_literal: true + +require "pliny/commands/creator" +require "pliny/commands/generator" +require "pliny/commands/generator/base" +require "spec_helper" describe Pliny::Commands::Generator do subject { Pliny::Commands::Generator.new } @@ -25,139 +27,139 @@ Timecop.return end - describe '#endpoint' do + describe "#endpoint" do before do - subject.endpoint('artists') + subject.endpoint("artists") end - it 'creates a new endpoint module' do - assert File.exist?('lib/endpoints/artists.rb') + it "creates a new endpoint module" do + assert File.exist?("lib/endpoints/artists.rb") end - it 'creates an endpoint test' do - assert File.exist?('spec/endpoints/artists_spec.rb') + it "creates an endpoint test" do + assert File.exist?("spec/endpoints/artists_spec.rb") end - it 'creates an endpoint acceptance test' do - assert File.exist?('spec/acceptance/artists_spec.rb') + it "creates an endpoint acceptance test" do + assert File.exist?("spec/acceptance/artists_spec.rb") end end - describe '#mediator' do + describe "#mediator" do before do - subject.mediator('artists/creator') + subject.mediator("artists/creator") end - it 'creates a new mediator module' do - assert File.exist?('lib/mediators/artists/creator.rb') + it "creates a new mediator module" do + assert File.exist?("lib/mediators/artists/creator.rb") end - it 'creates a test' do - assert File.exist?('spec/mediators/artists/creator_spec.rb') + it "creates a test" do + assert File.exist?("spec/mediators/artists/creator_spec.rb") end end - describe '#model' do - describe 'simple model' do + describe "#model" do + describe "simple model" do before do - subject.model('artist') + subject.model("artist") end - it 'creates a migration' do + it "creates a migration" do assert File.exist?("db/migrate/#{@t.to_i}_create_artists.rb") end - it 'creates the actual model' do - assert File.exist?('lib/models/artist.rb') + it "creates the actual model" do + assert File.exist?("lib/models/artist.rb") end - it 'creates a test' do - assert File.exist?('spec/models/artist_spec.rb') + it "creates a test" do + assert File.exist?("spec/models/artist_spec.rb") end end - describe 'model in nested class' do + describe "model in nested class" do before do - subject.model('administration/user') + subject.model("administration/user") end - it 'creates a migration' do + it "creates a migration" do assert File.exist?("db/migrate/#{@t.to_i}_create_administration_users.rb") end - it 'creates the actual model' do - assert File.exist?('lib/models/administration/user.rb') + it "creates the actual model" do + assert File.exist?("lib/models/administration/user.rb") end - it 'creates a test' do - assert File.exist?('spec/models/administration/user_spec.rb') + it "creates a test" do + assert File.exist?("spec/models/administration/user_spec.rb") end end end - describe '#scaffold' do + describe "#scaffold" do before do - subject.scaffold('artist') + subject.scaffold("artist") end - it 'creates a new endpoint module' do - assert File.exist?('lib/endpoints/artists.rb') + it "creates a new endpoint module" do + assert File.exist?("lib/endpoints/artists.rb") end - it 'creates an endpoint test' do - assert File.exist?('spec/endpoints/artists_spec.rb') + it "creates an endpoint test" do + assert File.exist?("spec/endpoints/artists_spec.rb") end - it 'creates an endpoint acceptance test' do - assert File.exist?('spec/acceptance/artists_spec.rb') + it "creates an endpoint acceptance test" do + assert File.exist?("spec/acceptance/artists_spec.rb") end - it 'creates a migration' do + it "creates a migration" do assert File.exist?("db/migrate/#{@t.to_i}_create_artists.rb") end - it 'creates the actual model' do - assert File.exist?('lib/models/artist.rb') + it "creates the actual model" do + assert File.exist?("lib/models/artist.rb") end - it 'creates a test' do - assert File.exist?('spec/models/artist_spec.rb') + it "creates a test" do + assert File.exist?("spec/models/artist_spec.rb") end - it 'creates a schema' do - assert File.exist?('schema/schemata/artist.yaml') + it "creates a schema" do + assert File.exist?("schema/schemata/artist.yaml") end - it 'creates a new serializer module' do - assert File.exist?('lib/serializers/artist.rb') + it "creates a new serializer module" do + assert File.exist?("lib/serializers/artist.rb") end - it 'creates a test' do - assert File.exist?('spec/serializers/artist_spec.rb') + it "creates a test" do + assert File.exist?("spec/serializers/artist_spec.rb") end end - describe '#schema' do + describe "#schema" do before do - subject.schema('artist') + subject.schema("artist") end - it 'creates a schema' do - assert File.exist?('schema/schemata/artist.yaml') + it "creates a schema" do + assert File.exist?("schema/schemata/artist.yaml") end end - describe '#serializer' do + describe "#serializer" do before do - subject.serializer('artist') + subject.serializer("artist") end - it 'creates a new serializer module' do - assert File.exist?('lib/serializers/artist.rb') + it "creates a new serializer module" do + assert File.exist?("lib/serializers/artist.rb") end - it 'creates a test' do - assert File.exist?('spec/serializers/artist_spec.rb') + it "creates a test" do + assert File.exist?("spec/serializers/artist_spec.rb") end end end diff --git a/spec/commands/updater_spec.rb b/spec/commands/updater_spec.rb index 8ad79857..57b5b67c 100644 --- a/spec/commands/updater_spec.rb +++ b/spec/commands/updater_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "pliny/commands/updater" require "spec_helper" diff --git a/spec/config_helpers_spec.rb b/spec/config_helpers_spec.rb index a61032c0..9ad59f85 100644 --- a/spec/config_helpers_spec.rb +++ b/spec/config_helpers_spec.rb @@ -1,13 +1,14 @@ +# frozen_string_literal: true + require "spec_helper" require "pliny/config_helpers" describe Pliny::CastingConfigHelpers do - describe "#rack_env" do it "is development if app_env is development" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'development', string + override :app_env, "development", string end assert_equal "development", config.rack_env @@ -16,7 +17,7 @@ it "is development if app_env is test" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'test', string + override :app_env, "test", string end assert_equal "development", config.rack_env @@ -25,7 +26,7 @@ it "is deployment if app_env is production" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'production', string + override :app_env, "production", string end assert_equal "deployment", config.rack_env @@ -34,7 +35,7 @@ it "is deployment if app_env is nil" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, '', string + override :app_env, "", string end assert_equal "deployment", config.rack_env @@ -43,7 +44,7 @@ it "is deployment if app_env is another value" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'staging', string + override :app_env, "staging", string end assert_equal "deployment", config.rack_env @@ -51,18 +52,18 @@ context "when legacy PLINY_ENV is still defined" do before do - ENV['ORIGINAL_PLINY_ENV'] = ENV['PLINY_ENV'] - ENV['PLINY_ENV'] = 'staging' + ENV["ORIGINAL_PLINY_ENV"] = ENV["PLINY_ENV"] + ENV["PLINY_ENV"] = "staging" end after do - ENV['PLINY_ENV'] = ENV.delete('ORIGINAL_PLINY_ENV') + ENV["PLINY_ENV"] = ENV.delete("ORIGINAL_PLINY_ENV") end it "uses PLINY_ENV value instead of APP_ENV" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'development', string + override :app_env, "development", string end assert_equal "deployment", config.rack_env @@ -71,7 +72,7 @@ it "displays deprecation warning" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'development', string + override :app_env, "development", string end io = StringIO.new @@ -88,7 +89,7 @@ it "displays deprecation warning if pliny_env is used" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'development', string + override :app_env, "development", string end io = StringIO.new @@ -102,7 +103,7 @@ it "returns app_env value" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'foo', string + override :app_env, "foo", string end assert_equal "foo", config.pliny_env @@ -110,18 +111,18 @@ context "when legacy PLINY_ENV is still defined" do before do - ENV['ORIGINAL_PLINY_ENV'] = ENV['PLINY_ENV'] - ENV['PLINY_ENV'] = 'staging' + ENV["ORIGINAL_PLINY_ENV"] = ENV["PLINY_ENV"] + ENV["PLINY_ENV"] = "staging" end after do - ENV['PLINY_ENV'] = ENV.delete('ORIGINAL_PLINY_ENV') + ENV["PLINY_ENV"] = ENV.delete("ORIGINAL_PLINY_ENV") end it "returns PLINY_ENV value" do config = Class.new do extend Pliny::CastingConfigHelpers - override :app_env, 'development', string + override :app_env, "development", string end assert_equal "staging", config.pliny_env diff --git a/spec/db_support_spec.rb b/spec/db_support_spec.rb index 6744fc23..0a3a0809 100644 --- a/spec/db_support_spec.rb +++ b/spec/db_support_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" require "pliny/db_support" @@ -176,8 +178,8 @@ end end - describe 'MigrationStatusPresenter' do - let(:filename) { '1630551344_latest_change.rb' } + describe "MigrationStatusPresenter" do + let(:filename) { "1630551344_latest_change.rb" } let(:up_migration) { described_class::MigrationStatus.new(filename: "00#{filename}") } let(:down_migration) { described_class::MigrationStatus.new(filename: "0#{filename}") } let(:file_missing_migration) { described_class::MigrationStatus.new(filename: "000#{filename}") } @@ -193,79 +195,79 @@ file_missing_migration.present_on_disk = false end - describe '#barrier_row' do - it 'pads to the longest_migration name' do - expectation = '+--------------+--------------------------------+' + describe "#barrier_row" do + it "pads to the longest_migration name" do + expectation = "+--------------+--------------------------------+" assert_equal expectation, presenter.barrier_row end end - describe '#header_row' do - it 'pads to the longest migration name' do - expectation = '| STATUS | MIGRATION |' + describe "#header_row" do + it "pads to the longest migration name" do + expectation = "| STATUS | MIGRATION |" assert_equal expectation, presenter.header_row end end - describe '#header' do - let(:barrier) { '+--------------+--------------------------------+' } - let(:header) { '| STATUS | MIGRATION |' } + describe "#header" do + let(:barrier) { "+--------------+--------------------------------+" } + let(:header) { "| STATUS | MIGRATION |" } - it 'wraps the title in barriers' do + it "wraps the title in barriers" do assert_equal [barrier, header, barrier], presenter.header end end - describe '#footer' do - let(:barrier) { '+--------------+--------------------------------+' } + describe "#footer" do + let(:barrier) { "+--------------+--------------------------------+" } - it 'just a barrier' do + it "just a barrier" do assert_equal [barrier], presenter.footer end end - describe '#status_row' do - context 'an up migration' do - it 'shows the correct details' do - expectation = '| UP | 001630551344_latest_change.rb |' + describe "#status_row" do + context "an up migration" do + it "shows the correct details" do + expectation = "| UP | 001630551344_latest_change.rb |" assert_equal expectation, presenter.status_row(up_migration) end end - context 'a down migration' do - it 'shows the correct details' do - expectation = '| DOWN | 01630551344_latest_change.rb |' + context "a down migration" do + it "shows the correct details" do + expectation = "| DOWN | 01630551344_latest_change.rb |" assert_equal expectation, presenter.status_row(down_migration) end end - context 'a file missing migration' do - it 'shows the correct details' do - expectation = '| FILE MISSING | 0001630551344_latest_change.rb |' + context "a file missing migration" do + it "shows the correct details" do + expectation = "| FILE MISSING | 0001630551344_latest_change.rb |" assert_equal expectation, presenter.status_row(file_missing_migration) end end end - describe '#statuses' do - let(:up_expectation) { '| UP | 001630551344_latest_change.rb |' } - let(:down_expectation) { '| DOWN | 01630551344_latest_change.rb |' } - let(:file_missing_expectation) { '| FILE MISSING | 0001630551344_latest_change.rb |' } + describe "#statuses" do + let(:up_expectation) { "| UP | 001630551344_latest_change.rb |" } + let(:down_expectation) { "| DOWN | 01630551344_latest_change.rb |" } + let(:file_missing_expectation) { "| FILE MISSING | 0001630551344_latest_change.rb |" } - it 'returns strings' do + it "returns strings" do assert_equal [up_expectation, down_expectation, file_missing_expectation], presenter.statuses end end - describe '#rows' do - let(:barrier) { '+--------------+--------------------------------+' } - let(:header) { '| STATUS | MIGRATION |' } - let(:up_expectation) { '| UP | 001630551344_latest_change.rb |' } - let(:down_expectation) { '| DOWN | 01630551344_latest_change.rb |' } - let(:file_missing_expectation) { '| FILE MISSING | 0001630551344_latest_change.rb |' } - let(:footer) { '+--------------+--------------------------------+' } + describe "#rows" do + let(:barrier) { "+--------------+--------------------------------+" } + let(:header) { "| STATUS | MIGRATION |" } + let(:up_expectation) { "| UP | 001630551344_latest_change.rb |" } + let(:down_expectation) { "| DOWN | 01630551344_latest_change.rb |" } + let(:file_missing_expectation) { "| FILE MISSING | 0001630551344_latest_change.rb |" } + let(:footer) { "+--------------+--------------------------------+" } - it 'is the table as an array' do + it "is the table as an array" do expectation = [ barrier, header, @@ -273,15 +275,15 @@ up_expectation, down_expectation, file_missing_expectation, - footer + footer, ] assert_equal expectation, presenter.rows end end - describe '#to_s' do - it 'is the table as a string' do + describe "#to_s" do + it "is the table as a string" do expectation = <<~OUTPUT.chomp +--------------+--------------------------------+ | STATUS | MIGRATION | @@ -297,8 +299,8 @@ end end - describe '#status' do - let(:filename) { '1630551344_latest_change.rb' } + describe "#status" do + let(:filename) { "1630551344_latest_change.rb" } let(:up_migration) { "00#{filename}" } let(:down_migration) { "0#{filename}" } let(:file_missing_migration) { "000#{filename}" } @@ -339,7 +341,7 @@ end end - it 'returns a table string' do + it "returns a table string" do expectation = <<~OUTPUT.chomp +--------------+--------------------------------+ | STATUS | MIGRATION | diff --git a/spec/error_reporters/rollbar_spec.rb b/spec/error_reporters/rollbar_spec.rb index 808f88cf..98043a8f 100644 --- a/spec/error_reporters/rollbar_spec.rb +++ b/spec/error_reporters/rollbar_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" require "rollbar" require "pliny/error_reporters/rollbar" @@ -7,8 +9,8 @@ describe "#notify" do let(:exception) { StandardError.new("Something went wrong") } - let(:context) { { step: :foo } } - let(:rack_env) { { "rack.input" => StringIO.new } } + let(:context) { { step: :foo } } + let(:rack_env) { { "rack.input" => StringIO.new } } subject(:notify) do reporter.notify(exception, context: context, rack_env: rack_env) @@ -29,7 +31,7 @@ notify expect(::Rollbar).to have_received(:scoped).once.with(hash_including( request: instance_of(Proc), - custom: { step: :foo } + custom: { step: :foo }, )) end @@ -38,8 +40,8 @@ { "rollbar.person_data" => { id: SecureRandom.uuid, email: "foo@bar.com", - username: "foo" - }} + username: "foo", + } } end it "adds person to the rollbar notification" do @@ -66,7 +68,7 @@ it "reports to Rollbar without request data in the scope" do notify - expect(Rollbar).to have_received(:scoped).once.with({ custom: {step: :foo} }) + expect(Rollbar).to have_received(:scoped).once.with({ custom: { step: :foo } }) end it "delegates to #report_exception_to_rollbar" do diff --git a/spec/error_reporters_spec.rb b/spec/error_reporters_spec.rb index 5ac9e4e8..64d38d3b 100644 --- a/spec/error_reporters_spec.rb +++ b/spec/error_reporters_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::ErrorReporters do @@ -7,8 +9,8 @@ describe ".notify" do let(:exception) { RuntimeError.new } - let(:context) { { context: "foo" } } - let(:rack_env) { { rack_env: "bar" } } + let(:context) { { context: "foo" } } + let(:rack_env) { { rack_env: "bar" } } subject(:notify_reporter) do reporter.notify(exception, context: context, rack_env: rack_env) diff --git a/spec/errors_spec.rb b/spec/errors_spec.rb index 2c115aa2..7f0d8da0 100644 --- a/spec/errors_spec.rb +++ b/spec/errors_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Errors do @@ -9,7 +11,8 @@ it "includes an HTTP error that will take generic parameters" do e = Pliny::Errors::HTTPStatusError.new( - "Custom HTTP error.", :custom_http_error, 499) + "Custom HTTP error.", :custom_http_error, 499, + ) assert_equal "Custom HTTP error.", e.message assert_equal :custom_http_error, e.id assert_equal 499, e.status diff --git a/spec/helpers/encode_spec.rb b/spec/helpers/encode_spec.rb index 8f077756..c69e111b 100644 --- a/spec/helpers/encode_spec.rb +++ b/spec/helpers/encode_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Helpers::Encode do diff --git a/spec/helpers/params_spec.rb b/spec/helpers/params_spec.rb index b6f66e8e..763fb025 100644 --- a/spec/helpers/params_spec.rb +++ b/spec/helpers/params_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Helpers::Params do @@ -11,35 +13,35 @@ def app end it "loads json params" do - post "/", {hello: "world"}.to_json, {"CONTENT_TYPE" => "application/json"} + post "/", { hello: "world" }.to_json, { "CONTENT_TYPE" => "application/json" } assert_equal "{\"hello\":\"world\"}", last_response.body end it "loads json array of params" do - post "/", [{hello: "world"}, {goodbye: "moon"}].to_json, {"CONTENT_TYPE" => "application/json"} + post "/", [{ hello: "world" }, { goodbye: "moon" }].to_json, { "CONTENT_TYPE" => "application/json" } assert_equal "[{\"hello\":\"world\"},{\"goodbye\":\"moon\"}]", last_response.body end it "loads json array of arrays of params" do - post "/", [[{hello: "world"}], [{goodbye: "moon"}]].to_json, {"CONTENT_TYPE" => "application/json"} + post "/", [[{ hello: "world" }], [{ goodbye: "moon" }]].to_json, { "CONTENT_TYPE" => "application/json" } assert_equal "[[{\"hello\":\"world\"}],[{\"goodbye\":\"moon\"}]]", last_response.body end it "loads form data params" do - post "/", {hello: "world"} + post "/", { hello: "world" } assert_equal "{\"hello\":\"world\"}", last_response.body end it "loads from an unknown content type" do - post "/", "world", {"CONTENT_TYPE" => "application/xml"} + post "/", "world", { "CONTENT_TYPE" => "application/xml" } assert_equal "{}", last_response.body end it "should throw bad request when receiving invalid json via post" do err = assert_raises(Pliny::Errors::BadRequest) do - post "/", "{\"foo\"}", {"CONTENT_TYPE" => "application/json"} + post "/", "{\"foo\"}", { "CONTENT_TYPE" => "application/json" } end - assert_match /expected ':' after object key at line 1 column 7/, err.message + assert_match(/expected ':' after object key at line 1 column 7/, err.message) end end diff --git a/spec/helpers/serialize_spec.rb b/spec/helpers/serialize_spec.rb index c56eaabc..f3dcf08b 100644 --- a/spec/helpers/serialize_spec.rb +++ b/spec/helpers/serialize_spec.rb @@ -1,5 +1,16 @@ +# frozen_string_literal: true + require "spec_helper" +class Serializer + def initialize(opts) + end + + def serialize(data) + data + end +end + describe Pliny::Helpers::Serialize do context "without a serializer" do def app @@ -20,13 +31,6 @@ def app end context "with a serializer" do - class Serializer - def initialize(opts); end - def serialize(data) - data - end - end - def app Sinatra.new do register Pliny::Helpers::Serialize diff --git a/spec/helpers/zulu_time_spec.rb b/spec/helpers/zulu_time_spec.rb index d4ca9a01..d35ade68 100644 --- a/spec/helpers/zulu_time_spec.rb +++ b/spec/helpers/zulu_time_spec.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require "spec_helper" +class ZuluTimeTest + extend Pliny::Helpers::ZuluTime +end + describe Pliny::Helpers::ZuluTime do context "zulu_time" do - class ZuluTimeTest - extend Pliny::Helpers::ZuluTime - end - it "it formats Time instances" do formatted = ZuluTimeTest.zulu_time(Time.parse("2017-11-28T21:49:52.123+00:00")) assert_equal "2017-11-28T21:49:52Z", formatted diff --git a/spec/integration_spec.rb b/spec/integration_spec.rb index f1997676..bec98721 100644 --- a/spec/integration_spec.rb +++ b/spec/integration_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" require "open3" @@ -79,41 +81,41 @@ it "returns a migration in the DOWN state when not migrated" do bash "pliny-generate model artist" - migration_file = Dir.glob('db/migrate/*').first + migration_file = Dir.glob("db/migrate/*").first - stdout, stderr = bash_with_output("rake db:migrate:status") + stdout, _ = bash_with_output("rake db:migrate:status") - statuses = Hash[stdout.to_s.split(/\+[-]+\+[-]+\+/)[2..-1].map { |s| s.tr("\n", "") }.select(&:present?).map { |s| s.split("|").map { |s| s.tr(" ", "") }.select(&:present?).reverse }] + statuses = stdout.to_s.split(/\+-+\+-+\+/)[2..].map { |s| s.tr("\n", "") }.select(&:present?).map { |s| s.split("|").map { |s| s.tr(" ", "") }.select(&:present?).reverse }.to_h assert statuses[migration_file.split("/").last] == "DOWN" end it "returns a migration in the UP state when not migrated" do bash "pliny-generate model artist" - migration_file = Dir.glob('db/migrate/*').first + migration_file = Dir.glob("db/migrate/*").first bash "rake db:migrate" - stdout, stderr = bash_with_output("rake db:migrate:status") + stdout, _ = bash_with_output("rake db:migrate:status") - statuses = Hash[stdout.to_s.split(/\+[-]+\+[-]+\+/)[2..-1].map { |s| s.tr("\n", "") }.select(&:present?).map { |s| s.split("|").map { |s| s.tr(" ", "") }.select(&:present?).reverse }] + statuses = stdout.to_s.split(/\+-+\+-+\+/)[2..].map { |s| s.tr("\n", "") }.select(&:present?).map { |s| s.split("|").map { |s| s.tr(" ", "") }.select(&:present?).reverse }.to_h assert statuses[migration_file.split("/").last] == "UP" end it "returns a migration in the FILE MISSING state when the file is missing" do bash "pliny-generate model artist" - migration_file = Dir.glob('db/migrate/*').first + migration_file = Dir.glob("db/migrate/*").first bash "rake db:migrate" FileUtils.rm_f(migration_file) - stdout, stderr = bash_with_output("rake db:migrate:status") + stdout, _ = bash_with_output("rake db:migrate:status") - statuses = Hash[stdout.to_s.split(/\+[-]+\+[-]+\+/)[2..-1].map { |s| s.tr("\n", "") }.select(&:present?).map { |s| s.split("|").map { |s| s.gsub(/(^[ ]+|[ ]+$)/, "") }.select(&:present?).reverse }] + statuses = stdout.to_s.split(/\+-+\+-+\+/)[2..].map { |s| s.tr("\n", "") }.select(&:present?).map { |s| s.split("|").map { |s| s.gsub(/(^ +| +$)/, "") }.select(&:present?).reverse }.to_h assert statuses[migration_file.split("/").last] == "FILE MISSING" end end def bash_with_output(cmd) - bin = File.expand_path('../bin', File.dirname(__FILE__)) + bin = File.expand_path("../bin", File.dirname(__FILE__)) path = "#{bin}:#{ENV["PATH"]}" env = { "PATH" => path } stdout, stderr, status = Open3.capture3(env, cmd) @@ -122,11 +124,11 @@ def bash_with_output(cmd) raise "Failed to run #{cmd}, error was #{stderr}" end - return stdout, stderr + [stdout, stderr] end def bash(cmd) - bin = File.expand_path('../bin', File.dirname(__FILE__)) + bin = File.expand_path("../bin", File.dirname(__FILE__)) path = "#{bin}:#{ENV["PATH"]}" env = { "PATH" => path } unless system(env, "#{cmd} > /dev/null") diff --git a/spec/log_spec.rb b/spec/log_spec.rb index bace7e22..1c705be8 100644 --- a/spec/log_spec.rb +++ b/spec/log_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Log do @@ -66,7 +68,7 @@ it "local context does not overwrite default context" do Pliny.default_context = { app: "pliny" } expect(@io).to receive(:print).with("app=not_pliny foo=bar\n") - Pliny.log(app: 'not_pliny', foo: "bar") + Pliny.log(app: "not_pliny", foo: "bar") assert Pliny.default_context[:app] == "pliny" end @@ -95,20 +97,20 @@ end describe "scrubbing" do - it "allows a Proc to be assigned as a log scrubber" do - Pliny.log_scrubber = -> (hash) { hash } + Pliny.log_scrubber = ->(hash) { hash } begin Pliny.log_scrubber = Object.new fail - rescue ArgumentError; end + rescue ArgumentError + end end describe "when a scrubber is present" do before do - Pliny.log_scrubber = -> (hash) { - Hash.new.tap do |h| + Pliny.log_scrubber = ->(hash) { + {}.tap do |h| hash.keys.each do |k| h[k] = "*SCRUBBED*" end diff --git a/spec/metrics/backends/logger_spec.rb b/spec/metrics/backends/logger_spec.rb index caf91467..c898cabc 100644 --- a/spec/metrics/backends/logger_spec.rb +++ b/spec/metrics/backends/logger_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Metrics::Backends::Logger do @@ -18,27 +20,29 @@ context "#count" do it "logs a single key with a value" do - backend.report_counts('app.foo' => 1) + backend.report_counts("app.foo" => 1) expect(io).to have_received(:print).with("count#app.foo=1\n") end it "logs multiple keys with values" do - backend.report_counts('app.foo' => 1, 'app.bar' => 2) + backend.report_counts("app.foo" => 1, "app.bar" => 2) expect(io).to have_received(:print).with( - "count#app.foo=1 count#app.bar=2\n") + "count#app.foo=1 count#app.bar=2\n", + ) end end context "#measure" do it "logs a single key with a value" do - backend.report_measures('pliny.foo' => 0.001) + backend.report_measures("pliny.foo" => 0.001) expect(io).to have_received(:print).with("measure#pliny.foo=0.001\n") end it "logs multiple keys with values" do - backend.report_measures('pliny.foo' => 0.3, 'pliny.bar' => 0.5) + backend.report_measures("pliny.foo" => 0.3, "pliny.bar" => 0.5) expect(io).to have_received(:print).with( - "measure#pliny.foo=0.300 measure#pliny.bar=0.500\n") + "measure#pliny.foo=0.300 measure#pliny.bar=0.500\n", + ) end end end diff --git a/spec/metrics_spec.rb b/spec/metrics_spec.rb index 4735437d..3d4c617e 100644 --- a/spec/metrics_spec.rb +++ b/spec/metrics_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Metrics do @@ -8,7 +10,7 @@ end before do - allow(Config).to receive(:app_name).and_return('pliny') + allow(Config).to receive(:app_name).and_return("pliny") end around do |example| @@ -41,7 +43,7 @@ metrics.count(:foo, :bar) expect(test_backend).to have_received(:report_counts).once.with( "pliny.foo" => 1, - "pliny.bar" => 1 + "pliny.bar" => 1, ) end end @@ -57,9 +59,9 @@ end it "measures a block's execution time with a single key" do - metrics.measure(:foo) { } + metrics.measure(:foo) {} expect(test_backend).to have_received(:report_measures).once.with( - "pliny.foo" => 0 + "pliny.foo" => 0, ) end @@ -69,37 +71,37 @@ end expect(test_backend).to have_received(:report_measures) do |opts| - assert(60 <= opts['pliny.foo'] && opts['pliny.foo'] <= 61) + assert(opts["pliny.foo"].between?(60, 61)) end end it "measures a block's execution time with multiple keys" do - metrics.measure(:foo, :bar) { } + metrics.measure(:foo, :bar) {} expect(test_backend).to have_received(:report_measures).once.with( "pliny.foo" => 0, - "pliny.bar" => 0 + "pliny.bar" => 0, ) end it "measures a given value for a single key without a block" do metrics.measure(:baz, value: 3.14) expect(test_backend).to have_received(:report_measures).once.with( - "pliny.baz" => 3.14 + "pliny.baz" => 3.14, ) end it "measures a given value for multiple keys with a block" do - metrics.measure(:qux, :corge, value: 42) { } + metrics.measure(:qux, :corge, value: 42) {} expect(test_backend).to have_received(:report_measures).once.with( "pliny.qux" => 42, - "pliny.corge" => 42 + "pliny.corge" => 42, ) end it "measures a value of 0 when no key or block is provided" do metrics.measure(:waldo) expect(test_backend).to have_received(:report_measures).once.with( - "pliny.waldo" => 0 + "pliny.waldo" => 0, ) end @@ -107,7 +109,7 @@ metrics.measure("metric.name", "another.name", value: 3.14, foo: :bar) expect(test_backend).to have_received(:report_measures).once.with( "pliny.metric.name" => 3.14, - "pliny.another.name" => 3.14 + "pliny.another.name" => 3.14, ) end @@ -115,7 +117,7 @@ metrics.measure("metric.name", "another.name", { value: 3.14, foo: :bar }) expect(test_backend).to have_received(:report_measures).once.with( "pliny.metric.name" => 3.14, - "pliny.another.name" => 3.14 + "pliny.another.name" => 3.14, ) end end diff --git a/spec/middleware/canonical_log_line_spec.rb b/spec/middleware/canonical_log_line_spec.rb index 51888d9e..f4f8735f 100644 --- a/spec/middleware/canonical_log_line_spec.rb +++ b/spec/middleware/canonical_log_line_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::CanonicalLogLine do @@ -7,7 +9,7 @@ def app use Pliny::Middleware::RequestID use Pliny::Middleware::CanonicalLogLine, - emitter: -> (data) { Pliny.log_without_context(data) } + emitter: ->(data) { Pliny.log_without_context(data) } use Pliny::Middleware::RescueErrors, raise: false @@ -48,7 +50,8 @@ def app it "never fails a request on failure" do expect(Pliny).to receive(:log).with( - message: "Failed to emit canonical log line") + message: "Failed to emit canonical log line", + ) expect(Pliny).to receive(:log_without_context) { |d| raise "bang!" } get "/apps/123" diff --git a/spec/middleware/cors_spec.rb b/spec/middleware/cors_spec.rb index 3dcd246b..7bad0b8e 100644 --- a/spec/middleware/cors_spec.rb +++ b/spec/middleware/cors_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::CORS do diff --git a/spec/middleware/instruments_spec.rb b/spec/middleware/instruments_spec.rb index 8a3626d9..b0499b78 100644 --- a/spec/middleware/instruments_spec.rb +++ b/spec/middleware/instruments_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::Instruments do @@ -25,17 +27,17 @@ def app it "performs logging" do expect(Pliny).to receive(:log).with(hash_including( instrumentation: true, - at: "start", - method: "GET", - path: "/apps/123", + at: "start", + method: "GET", + path: "/apps/123", )) expect(Pliny).to receive(:log).with(hash_including( instrumentation: true, - at: "finish", - method: "GET", - path: "/apps/123", + at: "finish", + method: "GET", + path: "/apps/123", route_signature: "/apps/:id", - status: 201 + status: 201, )) get "/apps/123" end @@ -43,7 +45,7 @@ def app it "respects Pliny error status codes" do expect(Pliny).to receive(:log) expect(Pliny).to receive(:log).with(hash_including( - status: 404 + status: 404, )) get "/error" end diff --git a/spec/middleware/metrics_spec.rb b/spec/middleware/metrics_spec.rb index 71150555..e142a73b 100644 --- a/spec/middleware/metrics_spec.rb +++ b/spec/middleware/metrics_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::Instruments do @@ -57,7 +59,7 @@ def app it "measures the request latency" do expect(Pliny::Metrics).to receive(:measure) do |key, opts| assert_equal(key, "requests.latency") - assert(4 < opts[:value] && opts[:value] < 6) + assert_in_delta(5, opts[:value], 1) end get "/hello" diff --git a/spec/middleware/request_id_spec.rb b/spec/middleware/request_id_spec.rb index ca254a95..faf3bdf7 100644 --- a/spec/middleware/request_id_spec.rb +++ b/spec/middleware/request_id_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::RequestID do diff --git a/spec/middleware/request_store/clear_spec.rb b/spec/middleware/request_store/clear_spec.rb index ec7a19f0..7a6f7f14 100644 --- a/spec/middleware/request_store/clear_spec.rb +++ b/spec/middleware/request_store/clear_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::RequestStore::Clear do diff --git a/spec/middleware/request_store/seed_spec.rb b/spec/middleware/request_store/seed_spec.rb index 8f0c709e..8006a2bf 100644 --- a/spec/middleware/request_store/seed_spec.rb +++ b/spec/middleware/request_store/seed_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::RequestStore::Seed do diff --git a/spec/middleware/rescue_errors_spec.rb b/spec/middleware/rescue_errors_spec.rb index 14cb1ccf..c0906c1f 100644 --- a/spec/middleware/rescue_errors_spec.rb +++ b/spec/middleware/rescue_errors_spec.rb @@ -1,21 +1,21 @@ -require "spec_helper" +# frozen_string_literal: true -describe Pliny::Middleware::RescueErrors do - include Rack::Test::Methods +require "spec_helper" - class BadMiddleware - def call(env) - if env["PATH_INFO"] == "/api-error" - raise Pliny::Errors::ServiceUnavailable - else - raise "Omg!" - end +class BadMiddleware + def call(env) + if env["PATH_INFO"] == "/api-error" + raise Pliny::Errors::ServiceUnavailable + else + raise "Omg!" end end +end - def app - @app - end +describe Pliny::Middleware::RescueErrors do + include Rack::Test::Methods + + attr_reader :app it "intercepts Pliny errors and renders" do @app = new_rack_app diff --git a/spec/middleware/versioning_spec.rb b/spec/middleware/versioning_spec.rb index 8f5b776f..26db30f3 100644 --- a/spec/middleware/versioning_spec.rb +++ b/spec/middleware/versioning_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Middleware::Versioning do @@ -10,7 +12,7 @@ def app Rack::Builder.new do use Rack::Lint - use Pliny::Middleware::Versioning, default: '2', app_name: 'pliny' + use Pliny::Middleware::Versioning, default: "2", app_name: "pliny" run Sinatra.new { get "/" do JSON.generate env @@ -20,48 +22,48 @@ def app end it "produces default version on application/json" do - get '/', {}, {'HTTP_ACCEPT' => 'application/json'} + get "/", {}, { "HTTP_ACCEPT" => "application/json" } json = JSON.parse(last_response.body) - assert_equal 'application/json', json['HTTP_ACCEPT'] - assert_equal '2', json['HTTP_X_API_VERSION'] + assert_equal "application/json", json["HTTP_ACCEPT"] + assert_equal "2", json["HTTP_X_API_VERSION"] end it "errors without a version specified on application/vnd.pliny+json" do - get '/', {}, {'HTTP_ACCEPT' => 'application/vnd.pliny+json'} - error = { id: :bad_version, message: <<-eos } -Please specify a version along with the MIME type. For example, `Accept: application/vnd.pliny+json; version=1`. - eos + get "/", {}, { "HTTP_ACCEPT" => "application/vnd.pliny+json" } + error = { id: :bad_version, message: <<~EOS } + Please specify a version along with the MIME type. For example, `Accept: application/vnd.pliny+json; version=1`. + EOS assert_equal 400, last_response.status assert_equal JSON.generate(error), last_response.body end it "ignores a wrong app name" do - get '/', {}, {'HTTP_ACCEPT' => 'application/vnd.chuck_norris+json'} + get "/", {}, { "HTTP_ACCEPT" => "application/vnd.chuck_norris+json" } json = JSON.parse(last_response.body) - assert_equal 'application/vnd.chuck_norris+json', json['HTTP_ACCEPT'] - assert_equal '2', json['HTTP_X_API_VERSION'] + assert_equal "application/vnd.chuck_norris+json", json["HTTP_ACCEPT"] + assert_equal "2", json["HTTP_X_API_VERSION"] end it "produces a version on application/vnd.pliny+json; version=3" do - get '/', {}, {'HTTP_ACCEPT' => 'application/vnd.pliny+json; version=3'} + get "/", {}, { "HTTP_ACCEPT" => "application/vnd.pliny+json; version=3" } json = JSON.parse(last_response.body) - assert_equal 'application/json', json['HTTP_ACCEPT'] - assert_equal '3', json['HTTP_X_API_VERSION'] + assert_equal "application/json", json["HTTP_ACCEPT"] + assert_equal "3", json["HTTP_X_API_VERSION"] end # this behavior is pretty sketchy, but a pretty extreme edge case it "handles multiple MIME types" do - get '/', {}, {'HTTP_ACCEPT' => 'application/vnd.pliny+json; version=3; q=0.5, text/xml'} + get "/", {}, { "HTTP_ACCEPT" => "application/vnd.pliny+json; version=3; q=0.5, text/xml" } json = JSON.parse(last_response.body) - assert_equal 'text/xml, application/json; q=0.5', json['HTTP_ACCEPT'] - assert_equal '3', json['HTTP_X_API_VERSION'] + assert_equal "text/xml, application/json; q=0.5", json["HTTP_ACCEPT"] + assert_equal "3", json["HTTP_X_API_VERSION"] end it "produces the priority version on multiple types" do - get '/', {}, {'HTTP_ACCEPT' => 'application/vnd.pliny+json; version=4; q=0.5, application/vnd.pliny+json; version=3'} + get "/", {}, { "HTTP_ACCEPT" => "application/vnd.pliny+json; version=4; q=0.5, application/vnd.pliny+json; version=3" } json = JSON.parse(last_response.body) - assert_equal 'application/json, application/json; q=0.5', json['HTTP_ACCEPT'] - assert_equal '3', json['HTTP_X_API_VERSION'] + assert_equal "application/json, application/json; q=0.5", json["HTTP_ACCEPT"] + assert_equal "3", json["HTTP_X_API_VERSION"] end end diff --git a/spec/request_store_spec.rb b/spec/request_store_spec.rb index 76f4769c..64769412 100644 --- a/spec/request_store_spec.rb +++ b/spec/request_store_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::RequestStore do before do @env = { - "REQUEST_IDS" => ["abc", "def"] + "REQUEST_IDS" => ["abc", "def"], } end diff --git a/spec/rollbar_logger_spec.rb b/spec/rollbar_logger_spec.rb index 340b5251..0094f612 100644 --- a/spec/rollbar_logger_spec.rb +++ b/spec/rollbar_logger_spec.rb @@ -1,41 +1,43 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::RollbarLogger do subject(:logger) { Pliny::RollbarLogger.new } - let(:message) { 'hello world' } + let(:message) { "hello world" } let(:log_context) { { rollbar: true, level: level, message: message } } before do expect(Pliny).to receive(:log).with(log_context) end - context '#debug' do - let(:level) { 'debug' } + context "#debug" do + let(:level) { "debug" } it "proxies the debug log level" do logger.debug(message) end end - context '#info' do - let(:level) { 'info' } + context "#info" do + let(:level) { "info" } it "proxies the info log level" do logger.info(message) end end - context '#warn' do - let(:level) { 'warn' } + context "#warn" do + let(:level) { "warn" } it "proxies the warn log level" do logger.warn(message) end end - context '#error' do - let(:level) { 'error' } + context "#error" do + let(:level) { "error" } it "proxies the error log level" do logger.error(message) diff --git a/spec/router_spec.rb b/spec/router_spec.rb index 7a0fc950..8030cf45 100644 --- a/spec/router_spec.rb +++ b/spec/router_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" describe Pliny::Router do @@ -5,12 +7,12 @@ def app Rack::Builder.new do use Rack::Lint - use Pliny::Middleware::Versioning, default: '2', app_name: 'pliny' + use Pliny::Middleware::Versioning, default: "2", app_name: "pliny" use Pliny::Router do - version '3' do + version "3" do mount Sinatra.new { - get '/' do + get "/" do "API V3" end } @@ -26,13 +28,13 @@ def app end it "should not run on any api" do - get '/' - assert_equal 'No API', last_response.body + get "/" + assert_equal "No API", last_response.body end it "should run on API V3" do - get '/', {}, {'HTTP_ACCEPT' => 'application/vnd.pliny+json; version=3'} - assert_equal 'API V3', last_response.body + get "/", {}, { "HTTP_ACCEPT" => "application/vnd.pliny+json; version=3" } + assert_equal "API V3", last_response.body end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ec51dfed..b2595c09 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # make sure this is set before Sinatra is required ENV["RACK_ENV"] = "test" @@ -35,7 +37,7 @@ # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 - config.order = 'random' + config.order = "random" # the rack app to be tested with rack-test: def app diff --git a/spec/support/config.rb b/spec/support/config.rb index 86e48f94..bd2a7672 100644 --- a/spec/support/config.rb +++ b/spec/support/config.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "pliny/config_helpers" # Supress the "use RbConfig instead" warning. diff --git a/spec/support/endpoints.rb b/spec/support/endpoints.rb index d679afb8..2e87e78d 100644 --- a/spec/support/endpoints.rb +++ b/spec/support/endpoints.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # create Endpoints::Base so we can test subclasses generated by Pliny: module Endpoints class Base < Sinatra::Base