From 184d2c7a51d22d8536a5c297fd34d3aaeccb3666 Mon Sep 17 00:00:00 2001 From: Anna Royer Date: Mon, 28 May 2018 15:18:25 -0600 Subject: [PATCH] Rubocop offenses may references #99 (#161) * regenerate rubocop_todo file to account for updates in inspected code * Handle several rubocop syntax offenses and delete from rubocop_todo * rebased with master and fix rubocop issue * update each_key and each_value to single params * fix conditional so it will not evaluate to nil --- .rubocop_todo.yml | 279 +++++------------- .ruby-version | 1 - Gemfile | 8 +- Rakefile | 8 +- app/controllers/absences_controller.rb | 7 +- app/controllers/application_controller.rb | 13 +- app/controllers/assignments_controller.rb | 1 - app/controllers/locations_controller.rb | 2 +- app/controllers/logs_controller.rb | 19 +- app/controllers/schedule_chains_controller.rb | 7 +- app/controllers/transport_types_controller.rb | 1 - app/controllers/volunteers_controller.rb | 25 +- app/helpers/application_helper.rb | 25 +- app/helpers/devise_helper.rb | 2 - app/helpers/locations_helper.rb | 6 +- app/helpers/regions_helper.rb | 2 - app/mailers/notifier.rb | 2 +- app/models/assignment.rb | 1 - app/models/location.rb | 27 +- app/models/log.rb | 18 +- app/models/log_recipient.rb | 2 - app/models/region.rb | 2 +- app/models/schedule_volunteer.rb | 2 - app/models/volunteer.rb | 6 +- app/presenters/volunteer_stats_presenter.rb | 6 +- .../pickup_stats_presenter.rb | 6 +- bin/support/bootstrap-database.rb | 6 +- bin/support/create-dot-env.rb | 2 + config/application.rb | 3 +- config/boot.rb | 2 +- config/environment.rb | 2 +- config/environments/development.rb | 2 +- config/environments/production.rb | 6 +- config/environments/test.rb | 2 +- config/initializers/devise.rb | 13 +- config/initializers/food_rescue_robot.rb | 2 +- config/routes.rb | 6 +- ...20120625205247_add_devise_to_volunteers.rb | 3 +- ...131226160442_create_schedule_volunteers.rb | 2 - .../20140408172606_create_log_volunteers.rb | 1 - .../20140418163926_create_schedule_chains.rb | 3 +- db/schema.rb | 101 ++++--- db/seeds.rb | 6 +- lib/food_robot.rb | 8 +- lib/food_robot/log_generator/existing_logs.rb | 8 +- lib/food_robot/log_generator/log_builder.rb | 12 +- .../log_generator/schedule_chain_decorator.rb | 20 +- .../region_data/schedule_chain_data.rb | 6 +- lib/tasks/foodrobot.rake | 2 - script/rails | 6 +- spec/factories/assignments.rb | 4 +- spec/factories/food_types.rb | 2 +- spec/factories/locations.rb | 4 +- spec/factories/log_parts.rb | 3 +- spec/factories/logs.rb | 15 +- spec/factories/scale_types.rb | 2 +- spec/factories/schedules.rb | 6 +- spec/features/api_spec.rb | 54 ++-- spec/features/region_admin/donors_spec.rb | 1 - spec/models/volunteer_spec.rb | 12 +- spec/rails_helper.rb | 2 +- 61 files changed, 309 insertions(+), 498 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 1365e99e..0c231f5c 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,133 +1,17 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2018-03-28 19:38:09 -0600 using RuboCop version 0.51.0. +# on 2018-05-19 15:29:33 -0600 using RuboCop version 0.51.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: Include, TreatCommentsAsGroupSeparators. -# Include: **/Gemfile, **/gems.rb -AllCops: - Exclude: - - 'lib/tasks/data_lookups.rake' - - 'vendor/**/*' - - 'bin/**/*' - - 'script/**/*' - -Bundler/OrderedGems: - Exclude: - - 'Gemfile' - -# Offense count: 2 -# Cop supports --auto-correct. -Layout/ClosingParenthesisIndentation: - Exclude: - - 'app/models/location.rb' - -# Offense count: 43 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: leading, trailing -Layout/DotPosition: - Exclude: - - 'Rakefile' - - 'app/controllers/logs_controller.rb' - - 'app/controllers/volunteers_controller.rb' - - 'app/models/log.rb' - - 'app/models/volunteer.rb' - - 'app/presenters/volunteer_stats_presenter.rb' - - 'app/presenters/volunteer_stats_presenter/pickup_stats_presenter.rb' - - 'lib/food_robot/log_generator/existing_logs.rb' - - 'lib/food_robot/log_generator/log_builder.rb' - - 'lib/food_robot/log_generator/schedule_chain_decorator.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Layout/ElseAlignment: - Exclude: - - 'app/controllers/schedule_chains_controller.rb' - # Offense count: 1 # Cop supports --auto-correct. Layout/EmptyLineAfterMagicComment: Exclude: - 'db/schema.rb' -# Offense count: 4 -# Cop supports --auto-correct. -Layout/EmptyLines: - Exclude: - - 'app/controllers/logs_controller.rb' - - 'config/environments/production.rb' - - 'db/migrate/20120625205247_add_devise_to_volunteers.rb' - - 'db/seeds.rb' - -# Offense count: 15 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: empty_lines, no_empty_lines -Layout/EmptyLinesAroundBlockBody: - Exclude: - - 'Rakefile' - - 'config/environments/production.rb' - - 'config/initializers/devise.rb' - - 'config/routes.rb' - - 'db/schema.rb' - - 'lib/tasks/foodrobot.rake' - - 'spec/factories/log_parts.rb' - - 'spec/factories/logs.rb' - - 'spec/features/api_spec.rb' - - 'spec/features/region_admin/donors_spec.rb' - -# Offense count: 20 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines -Layout/EmptyLinesAroundClassBody: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Layout/EmptyLinesAroundMethodBody: - Exclude: - - 'app/controllers/logs_controller.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines -Layout/EmptyLinesAroundModuleBody: - Exclude: - - 'app/helpers/application_helper.rb' - - 'app/helpers/devise_helper.rb' - - 'app/helpers/locations_helper.rb' - - 'app/helpers/regions_helper.rb' - - 'app/helpers/volunteers_helper.rb' - - 'lib/food_robot.rb' - -# Offense count: 22 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment, ForceEqualSignAlignment. -Layout/ExtraSpacing: - Exclude: - - 'app/models/location.rb' - - 'app/models/region.rb' - - 'config/environments/test.rb' - - 'config/initializers/food_rescue_robot.rb' - - 'db/schema.rb' - - 'script/rails' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth. -# SupportedStyles: consistent, special_for_inner_method_call, special_for_inner_method_call_in_parentheses -Layout/FirstParameterIndentation: - Exclude: - - 'spec/models/volunteer_spec.rb' - # Offense count: 8 # Cop supports --auto-correct. # Configuration parameters: SupportedStyles, IndentationWidth. @@ -135,35 +19,23 @@ Layout/FirstParameterIndentation: Layout/IndentHash: EnforcedStyle: consistent -# Offense count: 1 +# Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. # SupportedStyles: auto_detection, squiggly, active_support, powerpack, unindent Layout/IndentHeredoc: Exclude: + - 'bin/support/bootstrap-database.rb' + - 'bin/support/create-dot-env.rb' - 'lib/de_dup_log_volunteers.rb' -# Offense count: 15 -# Cop supports --auto-correct. -Layout/LeadingCommentSpace: - Exclude: - - 'Gemfile' - - 'app/controllers/schedule_chains_controller.rb' - - 'app/mailers/notifier.rb' - - 'config/environments/development.rb' - - 'config/environments/production.rb' - - 'config/routes.rb' - - 'db/migrate/20120625205247_add_devise_to_volunteers.rb' - - 'db/seeds.rb' - - 'spec/factories/logs.rb' - # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. # SupportedStyles: symmetrical, new_line, same_line Layout/MultilineArrayBraceLayout: Exclude: - - 'app/models/log.rb' + # - 'app/models/log.rb' # Offense count: 2 # Cop supports --auto-correct. @@ -173,14 +45,13 @@ Layout/MultilineMethodCallBraceLayout: Exclude: - 'app/models/location.rb' -# Offense count: 36 +# Offense count: 28 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth. # SupportedStyles: aligned, indented, indented_relative_to_receiver Layout/MultilineMethodCallIndentation: Exclude: - 'Rakefile' - - 'app/controllers/logs_controller.rb' - 'app/controllers/volunteers_controller.rb' - 'app/models/log.rb' - 'app/presenters/volunteer_stats_presenter.rb' @@ -209,13 +80,13 @@ Layout/SpaceAroundEqualsInParameterDefault: - 'app/models/log.rb' - 'lib/food_robot.rb' -# Offense count: 168 +# Offense count: 157 # Cop supports --auto-correct. # Configuration parameters: AllowForAlignment. Layout/SpaceAroundOperators: Enabled: false -# Offense count: 148 +# Offense count: 136 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, SupportedStylesForEmptyBraces. # SupportedStyles: space, no_space @@ -253,14 +124,7 @@ Layout/SpaceInsideBlockBraces: Exclude: - 'spec/features/take_one_time_shift.rb' -# Offense count: 6 -# Cop supports --auto-correct. -Layout/SpaceInsideBrackets: - Exclude: - - 'app/models/location.rb' - - 'config/initializers/devise.rb' - -# Offense count: 36 +# Offense count: 23 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SupportedStylesForEmptyBraces. # SupportedStyles: space, no_space, compact @@ -284,27 +148,32 @@ Layout/SpaceInsideParens: - 'app/models/location.rb' - 'app/models/volunteer.rb' -# Offense count: 2 +# Offense count: 4 # Cop supports --auto-correct. Layout/SpaceInsidePercentLiteralDelimiters: Exclude: - 'config/environments/production.rb' + - 'db/seeds.rb' -# Offense count: 6 +# Offense count: 1 Lint/AmbiguousBlockAssociation: Exclude: - - 'spec/interactors/region_admin/create_food_type_spec.rb' - - 'spec/lib/de_dup_log_volunteers_spec.rb' - - 'spec/lib/food_robot_spec.rb' + - 'db/seeds.rb' + +# Offense count: 2 +Lint/UselessAssignment: + Exclude: + - 'bin/support/bootstrap-database.rb' + - 'db/seeds.rb' # Offense count: 76 Metrics/AbcSize: Max: 146 -# Offense count: 71 +# Offense count: 9 # Configuration parameters: CountComments, ExcludedMethods. Metrics/BlockLength: - Max: 361 + Max: 235 # Offense count: 4 # Configuration parameters: CountBlocks. @@ -314,19 +183,19 @@ Metrics/BlockNesting: # Offense count: 8 # Configuration parameters: CountComments. Metrics/ClassLength: - Max: 378 + Max: 374 # Offense count: 15 Metrics/CyclomaticComplexity: Max: 29 -# Offense count: 483 +# Offense count: 490 # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https Metrics/LineLength: Max: 349 -# Offense count: 80 +# Offense count: 83 # Configuration parameters: CountComments. Metrics/MethodLength: Max: 93 @@ -351,10 +220,12 @@ Naming/AccessorMethodName: - 'app/controllers/application_controller.rb' # Offense count: 2 -Naming/ConstantName: +# Configuration parameters: ExpectMatchingDefinition, Regex, IgnoreExecutableScripts, AllowedAcronyms. +# AllowedAcronyms: CLI, DSL, ACL, API, ASCII, CPU, CSS, DNS, EOF, GUID, HTML, HTTP, HTTPS, ID, IP, JSON, LHS, QPS, RAM, RHS, RPC, SLA, SMTP, SQL, SSH, TCP, TLS, TTL, UDP, UI, UID, UUID, URI, URL, UTF8, VM, XML, XMPP, XSRF, XSS +Naming/FileName: Exclude: - - 'app/mailers/notifier.rb' - - 'app/models/log.rb' + - 'bin/support/bootstrap-database.rb' + - 'bin/support/create-dot-env.rb' # Offense count: 1 # Configuration parameters: Blacklist. @@ -363,22 +234,6 @@ Naming/HeredocDelimiterNaming: Exclude: - 'lib/tasks/sample_data.rake' -# Offense count: 14 -# Configuration parameters: NamePrefix, NamePrefixBlacklist, NameWhitelist, MethodDefinitionMacros. -# NamePrefix: is_, has_, have_ -# NamePrefixBlacklist: is_, has_, have_ -# NameWhitelist: is_a? -# MethodDefinitionMacros: define_method, define_singleton_method -Naming/PredicateName: - Exclude: - - 'spec/**/*' - - 'app/models/location.rb' - - 'app/models/log.rb' - - 'app/models/region.rb' - - 'app/models/schedule.rb' - - 'app/models/schedule_chain.rb' - - 'app/models/volunteer.rb' - # Offense count: 5 # Configuration parameters: EnforcedStyle, SupportedStyles. # SupportedStyles: snake_case, camelCase @@ -388,14 +243,6 @@ Naming/VariableName: - 'db/migrate/20140408172606_create_log_volunteers.rb' - 'lib/food_robot.rb' -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: AutoCorrect. -Performance/HashEachMethods: - Exclude: - - 'app/controllers/logs_controller.rb' - - 'spec/features/api_spec.rb' - # Offense count: 2 # Cop supports --auto-correct. Performance/StringReplacement: @@ -410,7 +257,7 @@ Style/Alias: Exclude: - 'app/controllers/application_controller.rb' -# Offense count: 38 +# Offense count: 37 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. # SupportedStyles: always, conditionals @@ -431,7 +278,7 @@ Style/AndOr: - 'db/migrate/20140207200738_create_scale_types.rb' - 'lib/food_robot.rb' -# Offense count: 76 +# Offense count: 70 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods. # SupportedStyles: line_count_based, semantic, braces_for_chaining @@ -456,21 +303,13 @@ Style/ClassVars: Exclude: - 'lib/food_robot.rb' -# Offense count: 9 +# Offense count: 4 # Cop supports --auto-correct. Style/ColonMethodCall: Exclude: - 'app/controllers/absences_controller.rb' - 'lib/tasks/foodrobot.rake' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles, SingleLineConditionsOnly, IncludeTernaryExpressions. -# SupportedStyles: assign_to_condition, assign_inside_condition -Style/ConditionalAssignment: - Exclude: - - 'app/controllers/volunteers_controller.rb' - # Offense count: 4 Style/DateTime: Exclude: @@ -501,18 +340,17 @@ Style/FormatString: Exclude: - 'app/models/volunteer.rb' -# Offense count: 6 +# Offense count: 5 # Configuration parameters: MinBodyLength. Style/GuardClause: Exclude: - 'app/controllers/application_controller.rb' - 'app/controllers/volunteers_controller.rb' - - 'app/models/log.rb' - 'app/models/volunteer.rb' - 'db/migrate/20131226160442_create_schedule_volunteers.rb' - 'db/migrate/20140408172606_create_log_volunteers.rb' -# Offense count: 222 +# Offense count: 217 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. # SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys @@ -546,7 +384,7 @@ Style/InverseMethods: - 'app/controllers/schedule_chains_controller.rb' - 'lib/food_robot.rb' -# Offense count: 10 +# Offense count: 9 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. # SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline @@ -555,7 +393,6 @@ Style/MethodDefParentheses: - 'app/helpers/application_helper.rb' - 'app/helpers/locations_helper.rb' - 'app/models/assignment.rb' - - 'app/models/log.rb' # Offense count: 1 # Cop supports --auto-correct. @@ -592,20 +429,21 @@ Style/NestedTernaryOperator: - 'app/controllers/logs_controller.rb' - 'app/controllers/schedule_chains_controller.rb' -# Offense count: 7 +# Offense count: 8 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles. # SupportedStyles: skip_modifier_ifs, always Style/Next: Exclude: - 'app/controllers/logs_controller.rb' + - 'app/controllers/schedule_chains_controller.rb' - 'app/models/location.rb' - 'db/migrate/20131226160442_create_schedule_volunteers.rb' - 'db/migrate/20140207200738_create_scale_types.rb' - 'db/migrate/20140408172606_create_log_volunteers.rb' - 'lib/food_robot.rb' -# Offense count: 8 +# Offense count: 7 # Cop supports --auto-correct. Style/Not: Exclude: @@ -628,7 +466,7 @@ Style/NumericLiteralPrefix: Style/NumericLiterals: MinDigits: 15 -# Offense count: 19 +# Offense count: 20 # Cop supports --auto-correct. # Configuration parameters: AutoCorrect, EnforcedStyle, SupportedStyles. # SupportedStyles: predicate, comparison @@ -637,17 +475,17 @@ Style/NumericPredicate: - 'spec/**/*' - 'Rakefile' - 'app/controllers/absences_controller.rb' - - 'app/controllers/assignments_controller.rb' + - 'app/controllers/locations_controller.rb' - 'app/controllers/logs_controller.rb' - 'app/controllers/schedule_chains_controller.rb' - - 'app/controllers/volunteers_controller.rb' - - 'app/mailers/notifier.rb' - 'app/models/assignment.rb' - 'app/models/log.rb' + - 'app/models/schedule_chain.rb' - 'config/initializers/constant.rb' - 'config/initializers/food_rescue_robot.rb' + - 'lib/food_robot.rb' -# Offense count: 12 +# Offense count: 13 # Cop supports --auto-correct. # Configuration parameters: PreferredDelimiters. Style/PercentLiteralDelimiters: @@ -660,6 +498,7 @@ Style/PercentLiteralDelimiters: - 'config/environments/production.rb' - 'config/initializers/assets.rb' - 'db/migrate/20120709010156_init_food_types_and_transport_types.rb' + - 'db/seeds.rb' - 'lib/sample_data/region_data/schedule_chain_data.rb' # Offense count: 1 @@ -674,10 +513,11 @@ Style/Proc: Exclude: - 'app/models/log.rb' -# Offense count: 4 +# Offense count: 6 # Cop supports --auto-correct. Style/RedundantParentheses: Exclude: + - 'app/controllers/schedule_chains_controller.rb' - 'app/mailers/notifier.rb' - 'config/initializers/constant.rb' @@ -691,7 +531,7 @@ Style/RedundantReturn: - 'app/models/log.rb' - 'lib/food_robot.rb' -# Offense count: 44 +# Offense count: 43 # Cop supports --auto-correct. Style/RedundantSelf: Exclude: @@ -710,6 +550,27 @@ Style/RegexpLiteral: - 'app/controllers/logs_controller.rb' - 'app/models/location.rb' +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: ConvertCodeThatCanStartToReturnNil. +Style/SafeNavigation: + Exclude: + - 'app/controllers/logs_controller.rb' + - 'app/controllers/schedule_chains_controller.rb' + - 'app/controllers/volunteers_controller.rb' + - 'app/helpers/locations_helper.rb' + - 'lib/food_robot.rb' + +# Offense count: 12 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, ConsistentQuotesInMultiline. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiterals: + Exclude: + - 'bin/support/bootstrap-database.rb' + - 'bin/support/create-dot-env.rb' + - 'db/seeds.rb' + # Offense count: 8 # Cop supports --auto-correct. # Configuration parameters: MinSize, SupportedStyles. @@ -717,7 +578,7 @@ Style/RegexpLiteral: Style/SymbolArray: EnforcedStyle: brackets -# Offense count: 36 +# Offense count: 30 # Cop supports --auto-correct. # Configuration parameters: IgnoredMethods. # IgnoredMethods: respond_to, define_method @@ -753,7 +614,7 @@ Style/TrailingUnderscoreVariable: Exclude: - 'spec/lib/food_robot_spec.rb' -# Offense count: 13 +# Offense count: 11 # Cop supports --auto-correct. Style/UnlessElse: Exclude: diff --git a/.ruby-version b/.ruby-version index 06016962..00355e29 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1,2 +1 @@ 2.3.7 - diff --git a/Gemfile b/Gemfile index 0aabcf89..24424b91 100755 --- a/Gemfile +++ b/Gemfile @@ -27,10 +27,10 @@ group :development do gem 'better_errors' gem 'binding_of_caller' gem 'faker', '~> 1.7.3' + gem 'guard-rspec', require: false gem 'rails-erd' - gem 'rubocop', require: false gem 'rb-fsevent', '~> 0.9.0', require: false # latest 0.10.x seems to be incompatible with listen gem - gem 'guard-rspec', require: false + gem 'rubocop', require: false end group :development, :test do @@ -89,10 +89,10 @@ gem 'jquery-datatables-rails', git: 'https://github.com/rweng/jquery-datatables- gem 'cocoon' # set timezone to browser timezone -gem 'browser-timezone-rails'#, '~> 0.0.9' +gem 'browser-timezone-rails' # '~> 0.0.9' gem 'ranked-model' -#Send email when exception occurs. +# Send email when exception occurs. gem 'exception_notification', '~> 3.0.1' gem 'exception_notification-rake', '~> 0.0.6' diff --git a/Rakefile b/Rakefile index 0e57e1b1..16f7012f 100755 --- a/Rakefile +++ b/Rakefile @@ -4,12 +4,11 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('../config/application', __FILE__) +require File.expand_path('config/application', __dir__) Webapp::Application.load_tasks task(:export_log_data => :environment) do - CSV.open('orgs.csv', 'wb') do |csv| csv << %w(id name lat lng type) Location.where('region_id = ?', 1).each{ |l| @@ -24,8 +23,8 @@ task(:export_log_data => :environment) do schedule_id) ntotal = Log.where('region_id = ? AND complete', 1).count Log.where('region_id = ? AND complete', 1).each{ |l| - lp = LogPart.select('log_parts.id,food_types.name,weight,count').where('log_id = ?', l.id). - joins('LEFT JOIN food_types ON log_parts.food_type_id=food_types.id') + lp = LogPart.select('log_parts.id,food_types.name,weight,count').where('log_id = ?', l.id) + .joins('LEFT JOIN food_types ON log_parts.food_type_id=food_types.id') tt = l.transport_type.nil? ? '' : l.transport_type.name st = l.scale_type.nil? ? '' : l.scale_type.name csv << [l.id, l.when, l.volunteers.collect{ |v| v.id }.join(':'), l.donor_id, l.recipients.collect{ |r| r.id }.join(':'), @@ -38,5 +37,4 @@ task(:export_log_data => :environment) do end } end - end diff --git a/app/controllers/absences_controller.rb b/app/controllers/absences_controller.rb index 659acb04..4c32e60e 100755 --- a/app/controllers/absences_controller.rb +++ b/app/controllers/absences_controller.rb @@ -11,9 +11,9 @@ def all index(absences, 'All Absences') end - def index(a=nil, header='Absences') - @absences = a.nil? ? Absence.where('stop_date >= ? AND volunteer_id=?', Date.today, current_volunteer.id) : a - @header = header.nil? ? 'Absences' : header + def index(absence=nil, header='Absences') + @absences = absence || Absence.where('stop_date >= ? AND volunteer_id=?', Date.today, current_volunteer.id) + @header = header || 'Absences' respond_to do |format| format.html { render :index } # index.html.erb end @@ -110,5 +110,4 @@ def create def admin_only redirect_to(root_path) unless current_volunteer.any_admin? end - end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index b3b1d3a5..845cfae6 100755 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -3,7 +3,6 @@ require 'food_robot' class ApplicationController < ActionController::Base - protect_from_forgery with: :null_session after_filter :setup_headers before_filter :authenticate_user_from_token! @@ -69,13 +68,11 @@ def set_vars_for_form(region) # https://gist.github.com/josevalim/fb706b1e933ef01e4fb6 def authenticate_user_from_token! user_email = params['volunteer_email'] - return if user_email.nil? - - user = Volunteer.find_by_email(user_email) token = params['volunteer_token'] - return if token.nil? - if user and Devise.secure_compare(user.authentication_token, token) - sign_in user, store: false - end + return unless user_email && token + + user = Volunteer.find_by_email(params['volunteer_email']) + clearance = Devise.secure_compare(user.authentication_token, token) if user + sign_in user, store: false if clearance end end diff --git a/app/controllers/assignments_controller.rb b/app/controllers/assignments_controller.rb index 29c2d4b5..5a7a4361 100755 --- a/app/controllers/assignments_controller.rb +++ b/app/controllers/assignments_controller.rb @@ -31,5 +31,4 @@ def knight def admin_only redirect_to(root_path) unless current_volunteer.any_admin? end - end diff --git a/app/controllers/locations_controller.rb b/app/controllers/locations_controller.rb index 118092cb..8d84f9bc 100755 --- a/app/controllers/locations_controller.rb +++ b/app/controllers/locations_controller.rb @@ -5,7 +5,7 @@ class LocationsController < ApplicationController def hud @location = Location.find(params[:id]) - if params[:key] == @location.receipt_key || (!current_volunteer.nil? && (current_volunteer.region_admin?(@location.region) || current_volunteer.super_admin?)) + if params[:key] == @location.receipt_key || (current_volunteer && (current_volunteer.region_admin?(@location.region) || current_volunteer.super_admin?)) @schedules = ScheduleChain.for_location(@location) @logs = if @location.donor? Log.at(@location).last(500) diff --git a/app/controllers/logs_controller.rb b/app/controllers/logs_controller.rb index 43618502..85f2fcd7 100755 --- a/app/controllers/logs_controller.rb +++ b/app/controllers/logs_controller.rb @@ -96,7 +96,7 @@ def stats @transport_years << log.year unless @transport_years.include?(log.year) @transport_per_year[log.name] = [] if @transport_per_year[log.name].nil? end - @transport_per_year.keys.each do |key| + @transport_per_year.each_key do |key| @transport_per_year[key] = @transport_years.collect{ |_y| 0 } end @transport_data.each do |log| @@ -132,14 +132,8 @@ def stats_service when 'transport' rq = '' wq = '' - unless params[:region_id].nil? - rq = "AND region_id=#{params[:region_id].to_i}" - end - unless params[:timespan].nil? - if params[:timespan] == 'month' - wq = "AND \"when\" > NOW() - interval '1 month'" - end - end + rq = "AND region_id=#{params[:region_id].to_i}" if params[:region_id] + wq = "AND \"when\" > NOW() - interval '1 month'" if params[:timespan] == 'month' noncar = Log.where("complete AND transport_type_id IN (SELECT id FROM transport_types WHERE name != 'Car') #{rq} #{wq}").count.to_f car = Log.where("complete AND transport_type_id IN (SELECT id FROM transport_types WHERE name = 'Car') #{rq} #{wq}").count.to_f render :text => "#{100.0*noncar/(noncar+car)} #{100.0*car/(noncar+car)}" @@ -176,9 +170,7 @@ def create render :new and return end - if @scale_types.any? && @log.scale_type_id.nil? - @log.scale_type_id = @region.scale_types.first.id - end + @log.scale_type_id ||= @region.scale_types.first.id if @scale_types.any? authorize! :create, @log parse_and_create_log_parts(params, @log) @@ -283,7 +275,6 @@ def take format.json { render json: { error: 0, message: flash[:notice] } } format.html { request.env['HTTP_REFERER'].present? ? redirect_to(:back) : redirect_to(open_logs_path) } end - end # can be given a single id or a list of ids @@ -401,7 +392,7 @@ def export def parse_and_create_log_parts(params, log) ret = [] - params['log_parts']&.each{ |_dc, lpdata| + params['log_parts'].each_value{ |lpdata| lpdata['weight'] = nil if lpdata['weight'].strip == '' lpdata['count'] = nil if lpdata['count'].strip == '' next if lpdata['id'].nil? and lpdata['weight'].nil? and lpdata['count'].nil? diff --git a/app/controllers/schedule_chains_controller.rb b/app/controllers/schedule_chains_controller.rb index 4db92606..92482156 100755 --- a/app/controllers/schedule_chains_controller.rb +++ b/app/controllers/schedule_chains_controller.rb @@ -220,13 +220,13 @@ def take notice += if index == (schedule.recipient_stops.length-1) ('and ' + stop.location.name + '.') else - (stop.location.name + ', ') #oxford comma + (stop.location.name + ', ') # oxford comma end end end flash[:notice] = notice - else - flash[:error] = "Hrmph. That didn't work..." + else + flash[:error] = "Hrmph. That didn't work..." end end else @@ -245,5 +245,4 @@ def take def admin_only redirect_to(root_path) unless current_volunteer.any_admin? end - end diff --git a/app/controllers/transport_types_controller.rb b/app/controllers/transport_types_controller.rb index 9590ee09..128961c5 100755 --- a/app/controllers/transport_types_controller.rb +++ b/app/controllers/transport_types_controller.rb @@ -8,5 +8,4 @@ def index format.json { render json: TransportType.all.to_json } end end - end diff --git a/app/controllers/volunteers_controller.rb b/app/controllers/volunteers_controller.rb index 0280c3d5..afd947bd 100755 --- a/app/controllers/volunteers_controller.rb +++ b/app/controllers/volunteers_controller.rb @@ -187,21 +187,20 @@ def stats @regions = current_volunteer.admin_regions region_ids = @regions.collect{ |region| region.id }.join(',') @logs_per_volunteer_year = - Log.joins(:log_parts, :volunteers). - select('volunteers.id, volunteers.name, sum(weight), count(DISTINCT logs.id)'). - where("complete AND region_id IN (#{region_ids}) and logs.when > ?", Date.today-12.months). - group('volunteers.id, volunteers.name').order('sum DESC') + Log.joins(:log_parts, :volunteers) + .select('volunteers.id, volunteers.name, sum(weight), count(DISTINCT logs.id)') + .where("complete AND region_id IN (#{region_ids}) and logs.when > ?", Date.today-12.months) + .group('volunteers.id, volunteers.name').order('sum DESC') @logs_per_volunteer_month = - Log.joins(:log_parts, :volunteers). - select('volunteers.id, volunteers.name, sum(weight), count(DISTINCT logs.id)'). - where("complete AND region_id IN (#{region_ids}) and logs.when > ?", Date.today-1.month). - group('volunteers.id, volunteers.name').order('sum DESC') - + Log.joins(:log_parts, :volunteers) + .select('volunteers.id, volunteers.name, sum(weight), count(DISTINCT logs.id)') + .where("complete AND region_id IN (#{region_ids}) and logs.when > ?", Date.today-1.month) + .group('volunteers.id, volunteers.name').order('sum DESC') @lazy_volunteers = - Volunteer.select('volunteers.id, name, email, count(*) as count, max("when") as last_date'). - joins(:logs, :log_volunteers). - where("volunteers.id=log_volunteers.volunteer_id and logs.region_id IN (#{current_volunteer.admin_region_ids.join(',')})"). - group('volunteers.id, name, email') + Volunteer.select('volunteers.id, name, email, count(*) as count, max("when") as last_date') + .joins(:logs, :log_volunteers) + .where("volunteers.id=log_volunteers.volunteer_id and logs.region_id IN (#{current_volunteer.admin_region_ids.join(',')})") + .group('volunteers.id, name, email') end def shift_stats diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 495e38e9..ff784164 100755 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true module ApplicationHelper - def all_admin_region_volunteer_tuples(whom) admin_rids = whom.assignments.collect{ |a| a.admin ? a.region.id : nil }.compact Volunteer.all.collect{ |v| @@ -10,20 +9,17 @@ def all_admin_region_volunteer_tuples(whom) }.compact end + def days_ago(shift_date) + return 'today' if shift_date.today? + distance = distance_of_time_in_words(Time.zone.today, shift_date) + return "#{distance} ago" if shift_date.past? + return "#{distance} from now" if shift_date.future? + end + def readable_time_until shift - ret = shift.when.strftime('%a %b %e') + ' (' - if shift.when == Time.zone.today - ret += 'today' - elsif shift.when < Time.zone.today - ret += (Time.zone.today - shift.when).to_i.to_s + ' days ago' - elsif shift.when > Time.zone.today - ret += (shift.when - Time.zone.today).to_i.to_s + ' days from now' - end - ret += ')' - unless shift.schedule_chain.nil? - ret += "
between #{readable_start_time(shift.schedule_chain)} and #{readable_stop_time(shift.schedule_chain)}" - end - ret.html_safe + time = "#{shift.when.strftime('%a %b %e')} (#{days_ago(shift.when)})}" + time += "\n#{readable_start_time(shift.schedule_chain)} and #{readable_stop_time(shift.schedule_chain)}" if shift.schedule_chain + time end def readable_start_time schedule @@ -53,5 +49,4 @@ def readable_pickup_timespan schedule str+= readable_stop_time schedule str end - end diff --git a/app/helpers/devise_helper.rb b/app/helpers/devise_helper.rb index 349d3fe3..8ee4a0d2 100755 --- a/app/helpers/devise_helper.rb +++ b/app/helpers/devise_helper.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true module DeviseHelper - def devise_error_messages! flash_alerts = [] error_key = 'errors.messages.not_saved' @@ -35,5 +34,4 @@ def devise_error_messages! html.html_safe end - end diff --git a/app/helpers/locations_helper.rb b/app/helpers/locations_helper.rb index b849d7d1..5f492ff2 100755 --- a/app/helpers/locations_helper.rb +++ b/app/helpers/locations_helper.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true module LocationsHelper - def readable_hours location readable_detailed_hours location end @@ -23,8 +22,7 @@ def readable_detailed_hours location str.html_safe end - def format_time t - t.to_s(:clean_time) + def format_time time + time.to_s(:clean_time) end - end diff --git a/app/helpers/regions_helper.rb b/app/helpers/regions_helper.rb index fc0ab064..04279ef1 100755 --- a/app/helpers/regions_helper.rb +++ b/app/helpers/regions_helper.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true module RegionsHelper - def region_logo_column(record) return '' if record.logo_file_name.nil? image_tag(record.logo(:thumb)) @@ -11,5 +10,4 @@ def region_time_zone_form_column(record, options) time_zone_select( 'record', 'time_zone', ActiveSupport::TimeZone.us_zones, {:default => record.time_zone}, options) end - end diff --git a/app/mailers/notifier.rb b/app/mailers/notifier.rb index e7cc6868..eacb4cff 100755 --- a/app/mailers/notifier.rb +++ b/app/mailers/notifier.rb @@ -3,7 +3,7 @@ class Notifier < ActionMailer::Base add_template_helper(ApplicationHelper) default from: 'robot@boulderfoodrescue.org' - #ForceTo = "cphillips@smallwhitecube.com" + # ForceTo = "cphillips@smallwhitecube.com" FORCE_TO = nil def admin_emails_for_region(region) diff --git a/app/models/assignment.rb b/app/models/assignment.rb index cf0b37f4..b1875bd5 100755 --- a/app/models/assignment.rb +++ b/app/models/assignment.rb @@ -30,5 +30,4 @@ def self.add_volunteer_to_region volunteer, region volunteer.save return true end - end diff --git a/app/models/location.rb b/app/models/location.rb index 462e4fe6..89262ec8 100755 --- a/app/models/location.rb +++ b/app/models/location.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true class Location < ActiveRecord::Base - # MOVE TO ENUM LOCATION_TYPES = { 0 => 'Recipient', @@ -17,7 +16,7 @@ class Location < ActiveRecord::Base belongs_to :region has_many :log_recipients - geocoded_by :address, latitude: :lat, longitude: :lng # can also be an IP address + geocoded_by :address, latitude: :lat, longitude: :lng # can also be an IP address acts_as_gmappable process_geocoding: false, lat: 'lat', lng: 'lng', address: 'address' after_initialize :init_detailed_hours @@ -67,7 +66,7 @@ def gmaps4rails_infowindow def gmaps4rails_marker_picture { 'picture' => self.donor? ? 'http://maps.gstatic.com/intl/en_ALL/mapfiles/dd-start.png' : - 'http://maps.gstatic.com/intl/en_ALL/mapfiles/dd-end.png' # string, mandatory + 'http://maps.gstatic.com/intl/en_ALL/mapfiles/dd-end.png' # string, mandatory } end @@ -82,7 +81,7 @@ def open?(time = nil) end def hours_on_day(index) - [ read_day_info('day'+index.to_s+'_start') , read_day_info('day'+index.to_s+'_end') ] + [read_day_info("day#{index}_start"), read_day_info("day#{index}_end")] end def open_on_day?(index) @@ -95,10 +94,10 @@ def populate_detailed_hours_from_form(params) write_day_info(prefix+'_status', params[prefix]['status'].to_i) write_day_info(prefix+'_start', Time.find_zone(self.time_zone).parse( params[prefix]['start']['hour']+':'+params[prefix]['start']['minute'] ) - ) + ) write_day_info(prefix+'_end', Time.find_zone(self.time_zone).parse( params[prefix]['end']['hour']+':'+params[prefix]['end']['minute'] ) - ) + ) end populate_detailed_hours_json_before_save end @@ -136,14 +135,18 @@ def mappable_address private + def day_length + hours_on_day(index).reduce(:-) + end + + def wrong_day_order?(index) + open_on_day?(index) && day_length(index).negative? + end + def detailed_hours_cannot_end_before_start (0..6).each do |index| - if open_on_day? index - prefix = 'day'+index.to_s - if read_day_info(prefix + '_start') > read_day_info(prefix + '_end') - errors.add(prefix+'_status', 'must have an end time AFTER the start time') - end - end + message = 'must have an end time AFTER the start time' + errors.add("day#{index}_status", message) if wrong_day_order?(index) end end diff --git a/app/models/log.rb b/app/models/log.rb index 602d5a3d..a127a0eb 100755 --- a/app/models/log.rb +++ b/app/models/log.rb @@ -76,9 +76,9 @@ def covering_volunteers end def covered? - num_vols = self.num_volunteers - num_vols = self.schedule_chain.num_volunteers if num_vols.nil? && !self.schedule_chain.nil? - num_vols.nil? ? self.volunteers? : self.volunteers.length >= num_vols + num_vols = num_volunteers || schedule_chain&.num_volunteers + return volunteers.count >= num_vols if num_vols + volunteers? end def volunteer?(volunteer) @@ -113,10 +113,10 @@ def self.pickup_count(region_id) end def self.picked_up_by(volunteer_id, complete=true, limit=nil) - logs = joins(:log_volunteers). - where('log_volunteers.volunteer_id = ? AND logs.complete=? AND log_volunteers.active', volunteer_id, complete). - order('"logs"."when" DESC'). - uniq + logs = joins(:log_volunteers) + .where('log_volunteers.volunteer_id = ? AND logs.complete=? AND log_volunteers.active', volunteer_id, complete) + .order('"logs"."when" DESC') + .uniq if limit.present? logs.limit(limit.to_i) @@ -208,10 +208,8 @@ def self.to_csv lps.collect{ |lp| lp.description.nil? ? 'None' : lp.description }.join(':'), log.summed_weight, log.donor.nil? ? 'Unknown' : log.donor.name, log.recipients.collect{ |r| r.nil? ? 'Unknown' : r.name }.join(':'), log.volunteers.collect{ |r| r.nil? ? 'Unknown' : r.name }.join(':'), log.scale_type.nil? ? 'Uknown' : log.scale_type.name, - log.transport_type.nil? ? 'Unknown' : log.transport_type.name, log.hours_spent, log.num_reminders, log.notes - ] + log.transport_type.nil? ? 'Unknown' : log.transport_type.name, log.hours_spent, log.num_reminders, log.notes] end end end - end diff --git a/app/models/log_recipient.rb b/app/models/log_recipient.rb index d5aa2507..e0041170 100755 --- a/app/models/log_recipient.rb +++ b/app/models/log_recipient.rb @@ -1,12 +1,10 @@ # frozen_string_literal: true class LogRecipient < ActiveRecord::Base - belongs_to :log belongs_to :recipient, :class_name => 'Location', :foreign_key => 'recipient_id' attr_accessible :log_id, :recipient_id, :active, :log, :recipient accepts_nested_attributes_for :recipient - end diff --git a/app/models/region.rb b/app/models/region.rb index 7490ec90..6b7cea15 100755 --- a/app/models/region.rb +++ b/app/models/region.rb @@ -11,7 +11,7 @@ class Region < ActiveRecord::Base scope :all_admin, ->(volunteer) { where(id: volunteer.admin_region_ids) } - geocoded_by :address, latitude: :lat, longitude: :lng # can also be an IP address + geocoded_by :address, latitude: :lat, longitude: :lng # can also be an IP address after_validation :geocode attr_accessible :address, :lat, :lng, :name, :notes, :website, :handbook_url, :welcome_email_text, diff --git a/app/models/schedule_volunteer.rb b/app/models/schedule_volunteer.rb index e2aff84b..907fc9b7 100755 --- a/app/models/schedule_volunteer.rb +++ b/app/models/schedule_volunteer.rb @@ -1,12 +1,10 @@ # frozen_string_literal: true class ScheduleVolunteer < ActiveRecord::Base - belongs_to :schedule_chain belongs_to :volunteer attr_accessible :schedule_chain_id, :volunteer_id, :active accepts_nested_attributes_for :volunteer - end diff --git a/app/models/volunteer.rb b/app/models/volunteer.rb index 128e5b2c..bcc355cb 100755 --- a/app/models/volunteer.rb +++ b/app/models/volunteer.rb @@ -214,9 +214,9 @@ def self.inactive(region_ids = nil) end def self.all_for_region(region_id) - includes(:regions). - where(regions: { id: region_id }). - compact + includes(:regions) + .where(regions: { id: region_id }) + .compact end def self.active_but_shiftless(region_ids) diff --git a/app/presenters/volunteer_stats_presenter.rb b/app/presenters/volunteer_stats_presenter.rb index c29a42b5..5a98f370 100644 --- a/app/presenters/volunteer_stats_presenter.rb +++ b/app/presenters/volunteer_stats_presenter.rb @@ -32,9 +32,9 @@ def lbs_by_month_graph :time def logs - @logs ||= Log.picked_up_by(volunteer.id). - where('"logs"."when" < ?', time). - includes(:log_parts) + @logs ||= Log.picked_up_by(volunteer.id) + .where('"logs"."when" < ?', time) + .includes(:log_parts) end def today diff --git a/app/presenters/volunteer_stats_presenter/pickup_stats_presenter.rb b/app/presenters/volunteer_stats_presenter/pickup_stats_presenter.rb index 0800ba68..19745443 100644 --- a/app/presenters/volunteer_stats_presenter/pickup_stats_presenter.rb +++ b/app/presenters/volunteer_stats_presenter/pickup_stats_presenter.rb @@ -40,9 +40,9 @@ def percent_human_powered_pickups :time def human_powered_pickups - @human_powered_logs ||= logs. - joins('LEFT OUTER JOIN "transport_types" ON "transport_types"."id" = "logs"."transport_type_id"'). - where("transport_types.name IS NULL OR NOT transport_types.name ILIKE '%car%'") + @human_powered_pickups ||= logs + .joins('LEFT OUTER JOIN "transport_types" ON "transport_types"."id" = "logs"."transport_type_id"') + .where("transport_types.name IS NULL OR NOT transport_types.name ILIKE '%car%'") end def weeks_since_first diff --git a/bin/support/bootstrap-database.rb b/bin/support/bootstrap-database.rb index 101bab4b..abc5aa3a 100644 --- a/bin/support/bootstrap-database.rb +++ b/bin/support/bootstrap-database.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + def run_command(*args) command = args.join(" ") puts command @@ -8,7 +10,7 @@ def locate_psql_command bin_location = `command -v psql`.strip if bin_location.empty? - puts <<-WARNING + puts <<~WARNING ==> Error: database connection could not be established and "psql" command could not be found. Do you have Postgres installed? WARNING @@ -19,7 +21,7 @@ def locate_psql_command end def each_sql_statement - ActiveRecord::Base.configurations.each do |_environment, settings| + ActiveRecord::Base.configurations.each_value do |settings| database = settings.fetch('database') username = settings.fetch('username') password = settings['password'] diff --git a/bin/support/create-dot-env.rb b/bin/support/create-dot-env.rb index 16a29de2..0c820342 100644 --- a/bin/support/create-dot-env.rb +++ b/bin/support/create-dot-env.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'erb' require 'pathname' diff --git a/config/application.rb b/config/application.rb index b57d8f8d..1003c6d6 100755 --- a/config/application.rb +++ b/config/application.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require File.expand_path('../boot', __FILE__) +require File.expand_path('boot', __dir__) require 'rails/all' @@ -13,7 +13,6 @@ module Webapp class Application < Rails::Application - # Generator settings config.generators do |g| g.assets = false diff --git a/config/boot.rb b/config/boot.rb index d1a6770c..faa3f886 100755 --- a/config/boot.rb +++ b/config/boot.rb @@ -3,6 +3,6 @@ require 'rubygems' # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) diff --git a/config/environment.rb b/config/environment.rb index 6a8a8347..f3c19b3b 100755 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Load the rails application -require File.expand_path('../application', __FILE__) +require File.expand_path('application', __dir__) # Initialize the rails application Webapp::Application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb index 12563099..257a573b 100755 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -59,6 +59,6 @@ # Raises helpful error messages. config.assets.raise_runtime_errors = true - #Show it all! + # Show it all! config.log_level = :debug end diff --git a/config/environments/production.rb b/config/environments/production.rb index 52d3ec64..f862ea50 100755 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -4,7 +4,7 @@ # Settings specified here will take precedence over those in config/application.rb config.time_zone = 'Mountain Time (US & Canada)' - #Asset Mailer Host! + # Asset Mailer Host! config.action_mailer.asset_host = 'https://boulder-food-rescue-robot.herokuapp.com' config.action_mailer.smtp_settings = { @@ -17,13 +17,12 @@ password: ENV['SENDGRID_PASSWORD'] } # ActionMailer Config - #config.action_mailer.default_url_options = { :host => 'robot.boulderfoodrescue.org' } + # config.action_mailer.default_url_options = { :host => 'robot.boulderfoodrescue.org' } config.action_mailer.default_url_options = { host: "#{ENV['DOMAIN_NAME']}" } config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true - # Code is not reloaded between requests config.cache_classes = true @@ -105,5 +104,4 @@ url: ':s3_domain_url', path: '/:class/:attachment/:id_partition/:style/:filename' } - end diff --git a/config/environments/test.rb b/config/environments/test.rb index d3ceb0a8..bb5d9e42 100755 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -24,7 +24,7 @@ config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment - config.action_controller.allow_forgery_protection = false + config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 3bc179fd..41dd1374 100755 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -3,7 +3,6 @@ # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| - # For devise 3.1 config.secret_key = '3cd770ec4e21f12a592de139fb8f40ba9eefb8fb6769b28223ab2dd8d543c3b5c34ae7cae346052d6c866fd17267786418d86a77eb2a57edddd102be9559673a9' @@ -29,7 +28,7 @@ # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. - # config.authentication_keys = [ :email ] + # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the @@ -41,12 +40,12 @@ # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. - config.case_insensitive_keys = [ :email ] + config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. - config.strip_whitespace_keys = [ :email ] + config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the @@ -105,7 +104,7 @@ config.reconfirmable = true # Defines which key will be used when confirming an account - # config.confirmation_keys = [ :email ] + # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. @@ -142,7 +141,7 @@ # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account - # config.unlock_keys = [ :email ] + # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email @@ -161,7 +160,7 @@ # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account - # config.reset_password_keys = [ :email ] + # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to diff --git a/config/initializers/food_rescue_robot.rb b/config/initializers/food_rescue_robot.rb index f03943de..da80d451 100755 --- a/config/initializers/food_rescue_robot.rb +++ b/config/initializers/food_rescue_robot.rb @@ -2,5 +2,5 @@ Time::DATE_FORMATS[:clean_time] = lambda { |t| format = (t.min==0) ? '%-I%p' : '%-I:%M%p' - I18n.l t, format: format, locale: :en + I18n.l t, format: format, locale: :en } diff --git a/config/routes.rb b/config/routes.rb index 12dddccf..3872c648 100755 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true Webapp::Application.routes.draw do - resources :assignments, only: [] do collection do get :knight @@ -66,9 +65,9 @@ get :create get :destroy end - #member do + # member do # get :show - #end + # end end resources :locations do @@ -135,5 +134,4 @@ root to: 'sessions#new', as: :unauthenticated_root end end - end diff --git a/db/migrate/20120625205247_add_devise_to_volunteers.rb b/db/migrate/20120625205247_add_devise_to_volunteers.rb index 97aa497f..a0e8a8d2 100755 --- a/db/migrate/20120625205247_add_devise_to_volunteers.rb +++ b/db/migrate/20120625205247_add_devise_to_volunteers.rb @@ -4,7 +4,7 @@ class AddDeviseToVolunteers < ActiveRecord::Migration def self.up change_table(:volunteers) do |t| ## Database authenticatable - #t.string :email, :null => false, :default => "" + # t.string :email, :null => false, :default => "" t.string :encrypted_password, :null => false, :default => '' ## Recoverable @@ -35,7 +35,6 @@ def self.up ## Token authenticatable # t.string :authentication_token - # Uncomment below if timestamps were not included in your original model. # t.timestamps end diff --git a/db/migrate/20131226160442_create_schedule_volunteers.rb b/db/migrate/20131226160442_create_schedule_volunteers.rb index 68f6fbef..2deda565 100755 --- a/db/migrate/20131226160442_create_schedule_volunteers.rb +++ b/db/migrate/20131226160442_create_schedule_volunteers.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true class CreateScheduleVolunteers < ActiveRecord::Migration - def up # make the new one-to-many table create_table :schedule_volunteers do |t| @@ -46,5 +45,4 @@ def down add_column(:schedules, :volunteer_id, :integer) add_column(:schedules, :prior_volunteer_id, :integer) end - end diff --git a/db/migrate/20140408172606_create_log_volunteers.rb b/db/migrate/20140408172606_create_log_volunteers.rb index e90674bb..0313c2b7 100755 --- a/db/migrate/20140408172606_create_log_volunteers.rb +++ b/db/migrate/20140408172606_create_log_volunteers.rb @@ -46,5 +46,4 @@ def down add_column(:logs, :volunteer_id, :integer) add_column(:logs, :orig_volunteer_id, :integer) end - end diff --git a/db/migrate/20140418163926_create_schedule_chains.rb b/db/migrate/20140418163926_create_schedule_chains.rb index 8a639780..8749b248 100755 --- a/db/migrate/20140418163926_create_schedule_chains.rb +++ b/db/migrate/20140418163926_create_schedule_chains.rb @@ -41,7 +41,7 @@ def change old_schedules.each{ |sid| original = Schedule.find(sid) puts "Converting #{sid}: #{n}/#{old_schedules.length}" - sc = ScheduleChain.create(irregular: original.irregular, backup: original.backup, frequency: original.frequency, + sc = ScheduleChain.create(irregular: original.irregular, backup: original.backup, frequency: original.frequency, detailed_start_time: original.detailed_start_time, detailed_stop_time: original.detailed_stop_time, detailed_date: original.detailed_date, hilliness: original.hilliness, difficulty_rating: original.difficulty_rating, @@ -98,5 +98,4 @@ def change l.remove :recipient_id end end - end diff --git a/db/schema.rb b/db/schema.rb index baafef9e..68aabf7b 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -13,12 +13,11 @@ # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20150623180213) do - create_table 'absences', :force => true do |t| t.integer 'volunteer_id' t.date 'start_date' t.date 'stop_date' - t.boolean 'active', :default => true + t.boolean 'active', :default => true t.text 'comments' end @@ -31,8 +30,8 @@ t.integer 'volunteer_id' t.integer 'region_id' t.boolean 'admin' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false end add_index 'assignments', ['region_id'], :name => 'index_assignments_on_region_id' @@ -45,10 +44,10 @@ create_table 'food_types', :force => true do |t| t.string 'name' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.integer 'region_id' - t.boolean 'active', :default => true, :null => false + t.boolean 'active', :default => true, :null => false end create_table 'locations', :force => true do |t| @@ -63,8 +62,8 @@ t.text 'admin_notes' t.text 'public_notes' t.text 'hours' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.integer 'region_id' t.string 'twitter_handle' t.string 'receipt_key' @@ -76,8 +75,8 @@ t.text 'entry_info' t.text 'exit_info' t.text 'onsite_contact_info' - t.boolean 'active', :default => true, :null => false - t.integer 'location_type', :default => 0 + t.boolean 'active', :default => true, :null => false + t.integer 'location_type', :default => 0 end create_table 'log_parts', :force => true do |t| @@ -85,8 +84,9 @@ t.integer 'food_type_id' t.boolean 'required' t.decimal 'weight' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + + t.datetime 'updated_at', :null => false t.integer 'count' t.text 'description' end @@ -102,9 +102,9 @@ create_table 'log_volunteers', :force => true do |t| t.integer 'log_id' t.integer 'volunteer_id' - t.boolean 'active', :default => true - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.boolean 'active', :default => true + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.boolean 'covering' end @@ -116,12 +116,12 @@ t.text 'notes' t.integer 'num_reminders' t.boolean 'flag_for_admin' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.integer 'donor_id' t.integer 'transport_type_id' t.integer 'region_id' - t.boolean 'complete', :default => false + t.boolean 'complete', :default => false t.integer 'scale_type_id' t.string 'weight_unit' t.integer 'schedule_chain_id' @@ -137,8 +137,8 @@ t.string 'website' t.text 'address' t.text 'notes' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.string 'handbook_url' t.integer 'prior_lbs_rescued' t.integer 'prior_num_pickups' @@ -158,20 +158,20 @@ t.string 'tax_id' t.text 'welcome_email_text' t.text 'splash_html' - t.string 'weight_unit', :default => 'pound', :null => false + t.string 'weight_unit', :default => 'pound', :null => false t.text 'time_zone' t.string 'volunteer_coordinator_email' - t.boolean 'post_pickup_emails', :default => false - t.boolean 'unschedule_self', :default => false + t.boolean 'post_pickup_emails', :default => false + t.boolean 'unschedule_self', :default => false end create_table 'scale_types', :force => true do |t| t.string 'name' t.string 'weight_unit' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.integer 'region_id' - t.boolean 'active', :default => true, :null => false + t.boolean 'active', :default => true, :null => false end create_table 'schedule_chains', :force => true do |t| @@ -191,16 +191,16 @@ t.integer 'expected_weight' t.text 'public_notes' t.text 'admin_notes' - t.integer 'num_volunteers', :default => 1, :null => false - t.boolean 'active', :default => true, :null => false + t.integer 'num_volunteers', :default => 1, :null => false + t.boolean 'active', :default => true, :null => false end create_table 'schedule_parts', :force => true do |t| t.integer 'schedule_id' t.integer 'food_type_id' t.boolean 'required' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false end add_index 'schedule_parts', ['food_type_id'], :name => 'index_schedule_parts_on_food_type_id' @@ -208,17 +208,17 @@ create_table 'schedule_volunteers', :force => true do |t| t.integer 'volunteer_id' - t.boolean 'active', :default => true - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.boolean 'active', :default => true + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.integer 'schedule_chain_id' end add_index 'schedule_volunteers', ['volunteer_id'], :name => 'index_schedule_volunteers_on_volunteer_id' create_table 'schedules', :force => true do |t| - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false t.integer 'schedule_chain_id' t.integer 'location_id' t.integer 'position' @@ -226,9 +226,9 @@ create_table 'transport_types', :force => true do |t| t.string 'name' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false - t.boolean 'active', :default => true, :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false + t.boolean 'active', :default => true, :null => false end create_table 'volunteers', :force => true do |t| @@ -241,36 +241,35 @@ t.text 'pickup_prefs' t.boolean 'is_disabled' t.boolean 'on_email_list' - t.datetime 'created_at', :null => false - t.datetime 'updated_at', :null => false - t.string 'encrypted_password', :default => '', :null => false + t.datetime 'created_at', :null => false + t.datetime 'updated_at', :null => false + t.string 'encrypted_password', :default => '', :null => false t.string 'reset_password_token' t.datetime 'reset_password_sent_at' t.datetime 'remember_created_at' - t.integer 'sign_in_count', :default => 0 + t.integer 'sign_in_count', :default => 0 t.datetime 'current_sign_in_at' t.datetime 'last_sign_in_at' t.string 'current_sign_in_ip' t.string 'last_sign_in_ip' - t.boolean 'admin', :default => false + t.boolean 'admin', :default => false t.integer 'transport_type_id' t.integer 'cell_carrier_id' - t.boolean 'sms_too', :default => false - t.boolean 'pre_reminders_too', :default => false + t.boolean 'sms_too', :default => false + t.boolean 'pre_reminders_too', :default => false t.string 'photo_file_name' t.string 'photo_content_type' t.integer 'photo_file_size' t.datetime 'photo_updated_at' - t.boolean 'get_sncs_email', :default => false, :null => false - t.boolean 'waiver_signed', :default => false, :null => false + t.boolean 'get_sncs_email', :default => false, :null => false + t.boolean 'waiver_signed', :default => false, :null => false t.datetime 'waiver_signed_at' - t.boolean 'assigned', :default => false, :null => false + t.boolean 'assigned', :default => false, :null => false t.integer 'requested_region_id' t.string 'authentication_token' - t.boolean 'active', :default => true, :null => false + t.boolean 'active', :default => true, :null => false end add_index 'volunteers', ['email'], :name => 'index_volunteers_on_email', :unique => true add_index 'volunteers', ['reset_password_token'], :name => 'index_volunteers_on_reset_password_token', :unique => true - end diff --git a/db/seeds.rb b/db/seeds.rb index cf06674d..d090c3e9 100755 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -29,7 +29,7 @@ CellCarrier.create(attrs) end -#region.attributes.slice('lat', 'lng', 'name', 'website', 'address', 'notes', 'handbook_url', 'prior_lbs_rescued', 'prior_num_pickups', 'title', 'tagline', 'phone', 'tax_id', 'welcome_email_text', 'splash_html', 'weight_unit', 'time_zone', 'volunteer_coordinator_email', 'post_pickup_emails', 'unschedule_self' ) +# region.attributes.slice('lat', 'lng', 'name', 'website', 'address', 'notes', 'handbook_url', 'prior_lbs_rescued', 'prior_num_pickups', 'title', 'tagline', 'phone', 'tax_id', 'welcome_email_text', 'splash_html', 'weight_unit', 'time_zone', 'volunteer_coordinator_email', 'post_pickup_emails', 'unschedule_self' ) region = Region.create({ 'lat'=> 41.5409097, 'lng'=> -72.9990631, @@ -53,8 +53,8 @@ log << "Created region #{region.name.inspect}" -#volunteer.attributes.slice('email', 'name', 'phone', 'preferred_contact', 'has_car', 'admin_notes', 'pickup_prefs', 'is_disabled', 'on_email_list', 'admin', 'transport_type_id', 'cell_carrier_id', 'sms_too', 'pre_reminders_too', 'get_sncs_email', 'waiver_signed', 'waiver_signed_at', 'assigned', 'requested_region_id', 'active') -#assignment.attributes.slice('volunteer_id', 'region_id', 'admin') +# volunteer.attributes.slice('email', 'name', 'phone', 'preferred_contact', 'has_car', 'admin_notes', 'pickup_prefs', 'is_disabled', 'on_email_list', 'admin', 'transport_type_id', 'cell_carrier_id', 'sms_too', 'pre_reminders_too', 'get_sncs_email', 'waiver_signed', 'waiver_signed_at', 'assigned', 'requested_region_id', 'active') +# assignment.attributes.slice('volunteer_id', 'region_id', 'admin') volunteer = Volunteer.create({ 'email'=>'volunteer.bfr@gmail.com', diff --git a/lib/food_robot.rb b/lib/food_robot.rb index d4148138..d3c60963 100755 --- a/lib/food_robot.rb +++ b/lib/food_robot.rb @@ -6,7 +6,6 @@ require 'food_robot/log_generator' module FoodRobot - # Set to true to disable emailing and just print the emails to STDOUT @@DontDeliverEmails = false @@ -26,7 +25,7 @@ def self.generate_log_entries(date = Time.zone.today, absence = nil) # Sends an email to any volunteer who has a outstanding log entry # from n or more days ago. Also sends an email to the admin summarizing # all logs that have seen at least r reminders. - def self.send_reminder_emails(n=2, r=3) + def self.send_reminder_emails(max_days_past=2, reminder_level=3) naughty_list = {} reminder_list = {} short_term_cover_list = {} @@ -51,7 +50,7 @@ def self.send_reminder_emails(n=2, r=3) # PAST reminders... next if log.volunteers.empty? days_past = (Time.zone.today - log.when).to_i - next unless days_past >= n + next unless days_past >= max_days_past log.num_reminders = 0 if log.num_reminders.nil? log.num_reminders += 1 @@ -61,7 +60,7 @@ def self.send_reminder_emails(n=2, r=3) reminder_list[vol] = [] if reminder_list[vol].nil? reminder_list[vol].push(log) - if log.num_reminders >= r + if log.num_reminders >= reminder_level naughty_list[log.region] = [] if naughty_list[log.region].nil? naughty_list[log.region].push(log) end @@ -167,5 +166,4 @@ def self.send_weekly_pickup_summary end end end - end diff --git a/lib/food_robot/log_generator/existing_logs.rb b/lib/food_robot/log_generator/existing_logs.rb index 4a3a554c..4602c2de 100644 --- a/lib/food_robot/log_generator/existing_logs.rb +++ b/lib/food_robot/log_generator/existing_logs.rb @@ -16,10 +16,10 @@ def log_for_donor(donor) attr_reader :date def logs - @logs ||= Log. - where(when: date). - map { |l| ["#{l.schedule_chain_id}:#{l.donor_id}", l] }. - to_h + @logs ||= Log + .where(when: date) + .map { |l| ["#{l.schedule_chain_id}:#{l.donor_id}", l] } + .to_h end end end diff --git a/lib/food_robot/log_generator/log_builder.rb b/lib/food_robot/log_generator/log_builder.rb index 993f5e38..b3a5e00a 100644 --- a/lib/food_robot/log_generator/log_builder.rb +++ b/lib/food_robot/log_generator/log_builder.rb @@ -54,12 +54,12 @@ def volunteers end def recipients - schedule_chain.schedules. - eager_load(:location). - where('position > ?', donor.position). - select{ |s| s.location.present? }. - select(&:drop_stop?). - map(&:location) + schedule_chain.schedules + .eager_load(:location) + .where('position > ?', donor.position) + .select{ |s| s.location.present? } + .select(&:drop_stop?) + .map(&:location) end def log_parts diff --git a/lib/food_robot/log_generator/schedule_chain_decorator.rb b/lib/food_robot/log_generator/schedule_chain_decorator.rb index 34e57130..d38acf57 100644 --- a/lib/food_robot/log_generator/schedule_chain_decorator.rb +++ b/lib/food_robot/log_generator/schedule_chain_decorator.rb @@ -9,10 +9,10 @@ def initialize(schedule_chain) def donors @donors ||= begin - donors = schedules. - where('location_id IS NOT NULL'). - includes(:location). - select(&:pickup_stop?) + donors = schedules + .where('location_id IS NOT NULL') + .includes(:location) + .select(&:pickup_stop?) donors.pop if donors.last.location.hub? @@ -21,12 +21,12 @@ def donors end def summary - @summary ||= schedules. - includes(:location). - select { |s| s.location.present? }. - map { |s| "#{s.pickup_stop? ? 'D' : 'R'}#{s.location_id}" }. - compact. - join(' -> ') + @summary ||= schedules + .includes(:location) + .select { |s| s.location.present? } + .map { |s| "#{s.pickup_stop? ? 'D' : 'R'}#{s.location_id}" } + .compact + .join(' -> ') end private diff --git a/lib/sample_data/region_data/schedule_chain_data.rb b/lib/sample_data/region_data/schedule_chain_data.rb index c59909fb..892caa65 100644 --- a/lib/sample_data/region_data/schedule_chain_data.rb +++ b/lib/sample_data/region_data/schedule_chain_data.rb @@ -27,7 +27,7 @@ def schedule_chains detailed_start_time: times[:start], detailed_stop_time: times[:stop], detailed_date: 100.days.from_now - rand(600).days, - difficulty_rating: [true, false].sample ? 1 + rand(3) : nil, + difficulty_rating: [true, false].sample ? rand(1..3) : nil, hilliness: [true, false].sample ? rand(5) : nil, frequency: frequency, day_of_week: frequency == 'weekly' ? rand(7) : nil, @@ -45,11 +45,11 @@ def schedule_chains end def random_start_stop_times - start = 9 + rand(10) + start = rand(9...20) { start: "#{start}:00:00", - stop: "#{start + 1 + rand(3)}:00:00" + stop: "#{start + rand(1...4)}:00:00" } end diff --git a/lib/tasks/foodrobot.rake b/lib/tasks/foodrobot.rake index d3cc113c..3fbf8521 100755 --- a/lib/tasks/foodrobot.rake +++ b/lib/tasks/foodrobot.rake @@ -3,7 +3,6 @@ require 'food_robot' namespace :foodrobot do - task(:generate_logs => :environment) do Rails.logger = Logger.new(STDOUT) # RB 4-28-2018: Generate entries for the next 14 days (these shouldn't create duplicates) @@ -21,5 +20,4 @@ namespace :foodrobot do FoodRobot::send_weekly_pickup_summary # email pickup summary on sunday end end - end diff --git a/script/rails b/script/rails index f138a34a..a056d914 100755 --- a/script/rails +++ b/script/rails @@ -1,6 +1,8 @@ #!/usr/bin/env ruby1.8 +# frozen_string_literal: true + # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. -APP_PATH = File.expand_path('../../config/application', __FILE__) -require File.expand_path('../../config/boot', __FILE__) +APP_PATH = File.expand_path('../config/application', __dir__) +require File.expand_path('../config/boot', __dir__) require 'rails/commands' diff --git a/spec/factories/assignments.rb b/spec/factories/assignments.rb index 1988f5fd..c50ec048 100755 --- a/spec/factories/assignments.rb +++ b/spec/factories/assignments.rb @@ -2,8 +2,8 @@ FactoryGirl.define do factory :assignment do - volunteer { (Volunteer.all.count >= 5 ? Volunteer.all.sort_by{ rand }.first : create(:volunteer)) } - region { (Region.all.count >= 3 ? Region.all.sort_by{ rand }.first : create(:region)) } + volunteer { (Volunteer.all.count >= 5 ? Volunteer.all.sample : create(:volunteer)) } + region { (Region.all.count >= 3 ? Region.all.sample : create(:region)) } trait :admin do admin true diff --git a/spec/factories/food_types.rb b/spec/factories/food_types.rb index 5f66d90f..4ce25b1d 100755 --- a/spec/factories/food_types.rb +++ b/spec/factories/food_types.rb @@ -3,6 +3,6 @@ FactoryGirl.define do factory :food_type do name 'Some food!' - region { (Region.all.count >= 5 ? Region.all.sort_by{ rand }.first : create(:region)) } + region { (Region.all.count >= 5 ? Region.all.sample : create(:region)) } end end diff --git a/spec/factories/locations.rb b/spec/factories/locations.rb index 367acc78..056389e8 100755 --- a/spec/factories/locations.rb +++ b/spec/factories/locations.rb @@ -3,13 +3,13 @@ FactoryGirl.define do factory :location do address { '710 31st St., Boulder, CO, 80303' } - name 'Some place' + sequence(:name) { |n| "Some place #{n}" } contact 'Some dude' website 'http://foobar.com' admin_notes 'Some admin notes' public_notes 'Some public notes' hours 'Some hours' - region { (Region.all.count >= 5 ? Region.all.sort_by{ rand }.first : create(:region)) } + region { (Region.all.count >= 5 ? Region.all.sample : create(:region)) } sequence(:email) { |n| "location#{n}@gmail.com" } phone '555-555-5555' equipment_storage_info 'Or something' diff --git a/spec/factories/log_parts.rb b/spec/factories/log_parts.rb index 42726b62..d2b19e42 100755 --- a/spec/factories/log_parts.rb +++ b/spec/factories/log_parts.rb @@ -3,7 +3,7 @@ FactoryGirl.define do factory :log_part do required false - food_type { (FoodType.all.count >= 5 ? FoodType.all.sort_by{ rand }.first : create(:food_type)) } + food_type { (FoodType.all.count >= 5 ? FoodType.all.sample : create(:food_type)) } factory :complete_log_part do weight 42.0 @@ -14,6 +14,5 @@ factory :required_log_part do required true end - end end diff --git a/spec/factories/logs.rb b/spec/factories/logs.rb index 6f211879..919af4df 100755 --- a/spec/factories/logs.rb +++ b/spec/factories/logs.rb @@ -4,27 +4,26 @@ factory :log do notes 'Log Notes Testing123' weight_unit 'lb' - region { (Region.all.count >= 5 ? Region.all.sort_by{ rand }.first : create(:region)) } + region { (Region.all.count >= 5 ? Region.all.sample : create(:region)) } self.when { Date.today + (rand > 0.5 ? -1 : 1)*rand(10) } # have to do self. since when is a reserved word in ruby - donor { Location.donors.count >= 5 ? Location.donors.sort_by{ rand }.first : create(:donor) } + donor { Location.donors.count >= 5 ? Location.donors.sample : create(:donor) } after(:create) do |d| rand(1..3).times{ - d.recipients << (Location.recipients.count >= 5 ? Location.recipients.sort_by{ rand }.first : create(:recipient)) + d.recipients << (Location.recipients.count >= 5 ? Location.recipients.sample : create(:recipient)) } rand(1..3).times{ d.log_parts << create(:log_part) } - d.scale_type = (ScaleType.all.count >= 5 ? ScaleType.all.sort_by{ rand }.first : create(:scale_type, region: d.region)) - d.transport_type = (TransportType.all.count >= 5 ? TransportType.all.sort_by{ rand }.first : create(:transport_type)) + d.scale_type = (ScaleType.all.count >= 5 ? ScaleType.all.sample : create(:scale_type, region: d.region)) + d.transport_type = (TransportType.all.count >= 5 ? TransportType.all.sample : create(:transport_type)) d.save end - #factory :log_from_chain do + # factory :log_from_chain do # after(:create) do |d| # schedule_chain { (ScheduleChain.all.count >= 5 ? ScheduleChain.all.sort_by{ rand }.first : create(:schedule_chain,region:d.region)) } # end - #end - + # end end end diff --git a/spec/factories/scale_types.rb b/spec/factories/scale_types.rb index dfc473ea..45fb5310 100755 --- a/spec/factories/scale_types.rb +++ b/spec/factories/scale_types.rb @@ -4,6 +4,6 @@ factory :scale_type do name 'Some scale' weight_unit 'lb' - region { (Region.all.count >= 5 ? Region.all.sort_by{ rand }.first : create(:region)) } + region { (Region.all.count >= 5 ? Region.all.sample : create(:region)) } end end diff --git a/spec/factories/schedules.rb b/spec/factories/schedules.rb index f148b026..9148916e 100755 --- a/spec/factories/schedules.rb +++ b/spec/factories/schedules.rb @@ -3,14 +3,14 @@ FactoryGirl.define do factory :schedule do position 3 - location { Location.all.count >= 5 ? Location.all.sort_by{ rand }.first : create(:location) } + location { Location.all.count >= 5 ? Location.all.sample : create(:location) } factory :donation_schedule do - location { Location.donors.count >= 5 ? Location.donors.sort_by{ rand }.first : create(:donor) } + location { Location.donors.count >= 5 ? Location.donors.sample : create(:donor) } end factory :recipient_schedule do - location { Location.recipients.count >= 5 ? Location.recipients.sort_by{ rand }.first : create(:recipient) } + location { Location.recipients.count >= 5 ? Location.recipients.sample : create(:recipient) } end end end diff --git a/spec/features/api_spec.rb b/spec/features/api_spec.rb index d4b3e5cf..6e03f2a7 100755 --- a/spec/features/api_spec.rb +++ b/spec/features/api_spec.rb @@ -4,30 +4,29 @@ require 'pp' xdescribe 'api' do - - def get_auth_params(u) - data = {email: u.email, password: u.password} + def get_auth_params(user) + data = {email: user.email, password: user.password} post '/volunteers/sign_in.json', data expect(last_response.status).to eq(201) json = JSON.parse(last_response.body) - {'volunteer_token' => json['authentication_token'], 'volunteer_email' => u.email } + {'volunteer_token' => json['authentication_token'], 'volunteer_email' => user.email } end it 'can sign in' do - v = create(:volunteer_with_assignment) - auth_params = get_auth_params(v) + volunteer = create(:volunteer_with_assignment) + auth_params = get_auth_params(volunteer) auth_params['volunteer_token'].should_not be_nil end it 'can sign out' do - v = create(:volunteer_with_assignment) - auth_params = get_auth_params(v) + volunteer = create(:volunteer_with_assignment) + auth_params = get_auth_params(volunteer) auth_params['volunteer_token'].should_not be_nil delete '/volunteers/sign_out.json', auth_params last_response.status.should eq(204) - auth_params2 = get_auth_params(v) + auth_params2 = get_auth_params(volunteer) auth_params2['volunteer_token'].should_not be_nil auth_params2['volunteer_token'].should_not eq(auth_params['volunteer_token']) end @@ -35,8 +34,8 @@ def get_auth_params(u) # GET /logs.json it 'can get a list of logs' do create(:log) - v = create(:volunteer_with_assignment) - auth_params = get_auth_params(v) + volunteer = create(:volunteer_with_assignment) + auth_params = get_auth_params(volunteer) get '/logs.json', auth_params expect(last_response.status).to eq(200) json = JSON.parse(last_response.body) @@ -46,11 +45,11 @@ def get_auth_params(u) # GET /logs/:id.json it 'can look up a log' do - v = create(:volunteer_with_assignment) - r = v.assignments.first.region - l = create(:log, region: r) - auth_params = get_auth_params(v) - get "/logs/#{l.id}.json", auth_params + volunteer = create(:volunteer_with_assignment) + region = volunteer.assignments.first.region + log = create(:log, region: region) + auth_params = get_auth_params(volunteer) + get "/logs/#{log.id}.json", auth_params expect(last_response.status).to eq(200) json = JSON.parse(last_response.body) json.should be_an(Hash) @@ -59,14 +58,14 @@ def get_auth_params(u) # GET /logs/:id/take.json it 'can cover a shift' do - v = create(:volunteer_with_assignment) - r = v.assignments.first.region - l = create(:log, region: r) - auth_params = get_auth_params(v) - get "/logs/#{l.id}/take.json", auth_params + volunteer = create(:volunteer_with_assignment) + region = volunteer.assignments.first.region + log = create(:log, region: region) + auth_params = get_auth_params(volunteer) + get "/logs/#{log.id}/take.json", auth_params expect(last_response.status).to eq(200) - l2 = Log.find(l.id) - expect(l2.volunteers.include?(v)).to eq(true) + l2 = Log.find(log.id) + expect(l2.volunteers.include?(volunteer)).to eq(true) end # GET /schedule_chains/:id/take.json @@ -89,14 +88,14 @@ def get_auth_params(u) l.volunteers << v l.save - auth_params = get_a uth_params(v) + auth_params = get_auth_params(v) get "/logs/#{l.id}.json", auth_params expect(last_response.status).to eq(200) json = JSON.parse(last_response.body) pp json - json['log_parts'].each{ |i, _lp| - json['log_parts'][i][:weight] = 42.0 - json['log_parts'][i][:count] = 5 + json['log_parts'].each_key{ |key| + json['log_parts'][key][:weight] = 42.0 + json['log_parts'][key][:count] = 5 } put "/logs/#{l.id}.json", auth_params.merge(json) pp last_response.body @@ -126,5 +125,4 @@ def get_auth_params(u) get '/logs.json' expect(last_response.status).to eq(401) end - end diff --git a/spec/features/region_admin/donors_spec.rb b/spec/features/region_admin/donors_spec.rb index ab468b19..a536f06c 100644 --- a/spec/features/region_admin/donors_spec.rb +++ b/spec/features/region_admin/donors_spec.rb @@ -3,7 +3,6 @@ require 'rails_helper' RSpec.describe 'Region Admin Donors' do - feature 'Viewing the list of donors' do let(:boulder) { create(:region) } let(:denver) { create(:region) } diff --git a/spec/models/volunteer_spec.rb b/spec/models/volunteer_spec.rb index c0a4ab09..c3c4f958 100644 --- a/spec/models/volunteer_spec.rb +++ b/spec/models/volunteer_spec.rb @@ -170,17 +170,17 @@ expect(volunteers.length).to eq(3) - expect(volunteers.include?( + expect(volunteers).to include( ["#{volunteer_with_shifts.name} ['#{boulder.name}']", volunteer_with_shifts.id] - )).to eq(true) + ) - expect(volunteers.include?( + expect(volunteers).to include( ["#{shiftless_volunteer_denver.name} ['#{denver.name}']", shiftless_volunteer_denver.id] - )).to eq(true) + ) - expect(volunteers.include?( + expect(volunteers).to include( ["#{shiftless_volunteer.name} ['#{boulder.name}']", shiftless_volunteer.id] - )).to eq(true) + ) end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 0cce6fb4..c41aa1a3 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -2,7 +2,7 @@ # This file is copied to spec/ when you run 'rails generate rspec:install' ENV['RAILS_ENV'] ||= 'test' -require File.expand_path('../../config/environment', __FILE__) +require File.expand_path('../config/environment', __dir__) # Prevent database truncation if the environment is production abort('The Rails environment is running in production mode!') if Rails.env.production?