Browse Source

lint: fix rubocop-rails errors

develop
Bèr Kessels 1 year ago
parent
commit
500a809457
43 changed files with 308 additions and 201 deletions
  1. 14
    0
      .rubocop.yml
  2. 9
    5
      Gemfile
  3. 4
    1
      Gemfile.lock
  4. 2
    1
      Rakefile
  5. 2
    0
      app/controllers/application_controller.rb
  6. 2
    0
      app/controllers/professionals_controller.rb
  7. 2
    0
      app/helpers/application_helper.rb
  8. 10
    5
      app/helpers/public_helper.rb
  9. 2
    1
      app/jobs/application_job.rb
  10. 2
    0
      app/mailers/application_mailer.rb
  11. 1
    0
      app/models/application_record.rb
  12. 5
    3
      app/models/profile.rb
  13. 17
    19
      app/models/profile/contact_detail.rb
  14. 12
    8
      app/view_models/profile/contact_detail_view_model.rb
  15. 1
    1
      bin/bundle
  16. 4
    1
      config/application.rb
  17. 5
    3
      config/environments/development.rb
  18. 21
    11
      config/environments/production.rb
  19. 2
    1
      config/environments/test.rb
  20. 5
    3
      config/initializers/backtrace_silencers.rb
  21. 6
    3
      config/initializers/content_security_policy.rb
  22. 14
    11
      config/initializers/friendly_id.rb
  23. 38
    22
      config/initializers/pagy.rb
  24. 2
    1
      config/initializers/wrap_parameters.rb
  25. 2
    1
      config/puma.rb
  26. 3
    1
      config/routes.rb
  27. 2
    0
      db/migrate/20200410153131_enable_pgcrypto_extension.rb
  28. 2
    0
      db/migrate/20200410160000_create_profiles.rb
  29. 1
    0
      db/migrate/20200412131932_create_active_storage_tables.active_storage.rb
  30. 2
    0
      db/migrate/20200413130444_add_last_activity_at_to_profiles.rb
  31. 2
    0
      db/migrate/20200416094746_add_contact_details_to_profiles.rb
  32. 2
    0
      db/migrate/20200430111245_add_slug_to_profiles.rb
  33. 3
    8
      db/migrate/20200430111256_create_friendly_id_slugs.rb
  34. 6
    4
      db/schema.rb
  35. 18
    20
      db/seeds.rb
  36. 10
    8
      test/channels/application_cable/connection_test.rb
  37. 3
    1
      test/helpers/public_helper_test.rb
  38. 42
    40
      test/models/profile/contact_detail_test.rb
  39. 15
    9
      test/models/profile_test.rb
  40. 1
    1
      test/support/workflows/profile_creator.rb
  41. 1
    1
      test/support/workflows/profile_importer.rb
  42. 1
    1
      test/system/list_professionals_test.rb
  43. 10
    6
      test/test_helper.rb

+ 14
- 0
.rubocop.yml View File

@@ -0,0 +1,14 @@
require: rubocop-rails
Layout/LineLength:
Exclude:
- db/schema.rb
- db/migrate/*
Metrics/BlockLength:
Exclude:
- db/schema.rb
Metrics/AbcSize:
Exclude:
- db/migrate/*
Metrics/MethodLength:
Exclude:
- db/migrate/*

+ 9
- 5
Gemfile View File

@@ -17,7 +17,8 @@ gem 'puma', '~> 4.1'
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
# Turbolinks makes navigating your web application faster. Read more:
# https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
@@ -45,7 +46,8 @@ end
group :development, :test do
gem 'awesome_print'

# Call 'byebug' anywhere in the code to stop execution and get a debugger console
# Call 'byebug' anywhere in the code to stop execution and get a debugger
# console
gem 'byebug', platforms: %i[mri mingw x64_mingw]

# On development and test, load env from disk
@@ -53,15 +55,17 @@ group :development, :test do
end

group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
# Access an interactive console on exception pages or by calling 'console'
# anywhere in the code.
gem 'listen', '>= 3.0.5', '< 3.2'
gem 'web-console', '>= 3.3.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
# Spring speeds up development by keeping your application running in the
# background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'

# Linting with rubocop
gem 'rubocop'
gem 'rubocop-rails'
end

group :test do

+ 4
- 1
Gemfile.lock View File

@@ -169,6 +169,9 @@ GEM
rainbow (>= 2.2.2, < 4.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 1.7)
rubocop-rails (2.4.2)
rack (>= 1.1)
rubocop (>= 0.72.0)
ruby-progressbar (1.10.1)
ruby-vips (2.0.17)
ffi (~> 1.9)
@@ -246,7 +249,7 @@ DEPENDENCIES
puma (~> 4.1)
rails (~> 6.0.2, >= 6.0.2.2)
rails-assets-bootstrap!
rubocop
rubocop-rails
sass-rails (>= 6)
selenium-webdriver
spring

+ 2
- 1
Rakefile View File

@@ -1,7 +1,8 @@
# frozen_string_literal: true

# 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.
# for example lib/tasks/capistrano.rake, and they will automatically be
# available to Rake.

require_relative 'config/application'


+ 2
- 0
app/controllers/application_controller.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Bas Controller for all controllers
class ApplicationController < ActionController::Base
include Pagy::Backend


+ 2
- 0
app/controllers/professionals_controller.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Controller for public profesionals
class ProfessionalsController < ApplicationController
layout 'public'


+ 2
- 0
app/helpers/application_helper.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Base helper
module ApplicationHelper
include Pagy::Frontend
end

+ 10
- 5
app/helpers/public_helper.rb View File

@@ -17,11 +17,16 @@ module PublicHelper

def formatted_contact_detail_value(contact_detail)
case contact_detail.type
when :email then mail_to(contact_detail.value)
when :phone then link_to(contact_detail.value, "tel:#{contact_detail.value}")
when :twitter then link_to("@#{contact_detail.value}", "https://twitter.com/#{contact_detail.value}")
when :facebook then link_to(contact_detail.value, "https://www.facebook.com/#{contact_detail.value}")
when :linkedin then link_to(contact_detail.value, "https://linkedin.com/#{contact_detail.value}")
when :email
mail_to(contact_detail.value)
when :phone
link_to(contact_detail.value, "tel:#{contact_detail.value}")
when :twitter
link_to("@#{contact_detail.value}", "https://twitter.com/#{contact_detail.value}")
when :facebook
link_to(contact_detail.value, "https://www.facebook.com/#{contact_detail.value}")
when :linkedin
link_to(contact_detail.value, "https://linkedin.com/#{contact_detail.value}")
else contact_detail.value
end
end

+ 2
- 1
app/jobs/application_job.rb View File

@@ -4,6 +4,7 @@ class ApplicationJob < ActiveJob::Base
# Automatically retry jobs that encountered a deadlock
# retry_on ActiveRecord::Deadlocked

# Most jobs are safe to ignore if the underlying records are no longer available
# Most jobs are safe to ignore if the underlying records are no longer
# available
# discard_on ActiveJob::DeserializationError
end

+ 2
- 0
app/mailers/application_mailer.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Base Mailer
class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'

+ 1
- 0
app/models/application_record.rb View File

@@ -1,5 +1,6 @@
# frozen_string_literal: true

# Base record
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end

+ 5
- 3
app/models/profile.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# A profile is the displayable version of a user
class Profile < ApplicationRecord
extend FriendlyId

@@ -70,8 +72,8 @@ class Profile < ApplicationRecord
end

def limit_contact_details_entries
if contact_details.length > CD_ENTRIES_MAX
errors.add(:contact_details, :too_many, count: 255)
end
return if contact_details.length <= CD_ENTRIES_MAX
errors.add(:contact_details, :too_many, count: 255)
end
end

+ 17
- 19
app/models/profile/contact_detail.rb View File

@@ -1,27 +1,25 @@
# frozen_string_literal: true

##
# Profile::ContactDetail
#
class Profile::ContactDetail
include ActiveModel::Validations
class Profile
##
# Profile::ContactDetail model used to validate contact details
class ContactDetail
include ActiveModel::Validations

MAX_KEY_LENGTH = 100
MAX_VALUE_LENGTH = 300
ALLOWED_TYPES = %w[address email facebook linkedin phone twitter].freeze
MAX_KEY_LENGTH = 100
MAX_VALUE_LENGTH = 300
ALLOWED_TYPES = %w[address email facebook linkedin phone twitter].freeze

attr_reader :key, :value, :type
attr_reader :key, :value, :type

validates_presence_of :key
validates_presence_of :value
validates_presence_of :type
validates_length_of :key, maximum: MAX_KEY_LENGTH
validates_length_of :value, maximum: MAX_VALUE_LENGTH
validates_inclusion_of :type, in: ALLOWED_TYPES
validates :key, presence: true, length: { maximum: MAX_KEY_LENGTH }
validates :value, presence: true, length: { maximum: MAX_VALUE_LENGTH }
validates :type, presence: true, inclusion: { in: ALLOWED_TYPES }

def initialize(key: '', value: '', type: '')
@key = key
@value = value
@type = type
def initialize(key: '', value: '', type: '')
@key = key
@value = value
@type = type
end
end
end

+ 12
- 8
app/view_models/profile/contact_detail_view_model.rb View File

@@ -1,15 +1,19 @@
# frozen_string_literal: true

class Profile::ContactDetailViewModel
extend Forwardable
class Profile
##
# View model for Profile::ContactDetail
class ContactDetailViewModel
extend Forwardable

def_delegators :@resource, :key, :value
def_delegators :@resource, :key, :value

def initialize(resource)
@resource = resource
end
def initialize(resource)
@resource = resource
end

def type
@resource.type.to_sym
def type
@resource.type.to_sym
end
end
end

+ 1
- 1
bin/bundle View File

@@ -14,7 +14,7 @@ m = Module.new do
module_function

def invoked_as_script?
File.expand_path($0) == File.expand_path(__FILE__)
File.expand_path($PROGRAM_NAME) == File.expand_path(__FILE__)
end

def env_var_version

+ 4
- 1
config/application.rb View File

@@ -9,11 +9,14 @@ require 'rails/all'
Bundler.require(*Rails.groups)

module Mahout
##
# Basic application config
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0

# Settings in config/environments/* take precedence over those specified here.
# Settings in config/environments/* take precedence over those specified
# here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.

+ 5
- 3
config/environments/development.rb View File

@@ -1,7 +1,8 @@
# frozen_string_literal: true

Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Settings specified here will take precedence over those in
# config/application.rb.

# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
@@ -16,7 +17,7 @@ Rails.application.configure do

# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true

@@ -30,7 +31,8 @@ Rails.application.configure do
config.cache_store = :null_store
end

# Store uploaded files on the local file system (see config/storage.yml for options).
# Store uploaded files on the local file system (see config/storage.yml for
# options).
config.active_storage.service = :local

# Don't care if the mailer can't send.

+ 21
- 11
config/environments/production.rb View File

@@ -1,7 +1,8 @@
# frozen_string_literal: true

Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Settings specified here will take precedence over those in
# config/application.rb.

# Code is not reloaded between requests.
config.cache_classes = true
@@ -16,8 +17,9 @@ Rails.application.configure do
config.consider_all_requests_local = false
config.action_controller.perform_caching = true

# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# Ensures that a master key has been made available in either
# ENV["RAILS_MASTER_KEY"] or in config/master.key. This key is used to
# decrypt credentials (and other encrypted files).
# config.require_master_key = true

# Disable serving static files from the `/public` folder by default since
@@ -37,15 +39,18 @@ Rails.application.configure do
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

# Store uploaded files on the local file system (see config/storage.yml for options).
# Store uploaded files on the local file system (see config/storage.yml for
# options).
config.active_storage.service = :local

# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# config.action_cable.allowed_request_origins = [ 'http://example.com',
# /http:\/\/example.*/ ]

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# Force all access to the app over SSL, use Strict-Transport-Security, and
# use secure cookies.
# config.force_ssl = true

# Use the lowest log level to ensure availability of diagnostic information
@@ -58,14 +63,16 @@ Rails.application.configure do
# Use a different cache store in production.
# config.cache_store = :mem_cache_store

# Use a real queuing backend for Active Job (and separate queues per environment).
# Use a real queuing backend for Active Job (and separate queues per
# environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "mahout_production"

config.action_mailer.perform_caching = false

# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# Set this to true and configure the email server for immediate delivery to
# raise delivery errors.
# config.action_mailer.raise_delivery_errors = false

# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
@@ -80,7 +87,8 @@ Rails.application.configure do

# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new
# 'app-name')

if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new(STDOUT)
@@ -109,6 +117,8 @@ Rails.application.configure do
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
# config.active_record.database_resolver =
# ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context =
# ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end

+ 2
- 1
config/environments/test.rb View File

@@ -6,7 +6,8 @@
# and recreated between test runs. Don't rely on the data there!

Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Settings specified here will take precedence over those in
# config/application.rb.

config.cache_classes = false


+ 5
- 3
config/initializers/backtrace_silencers.rb View File

@@ -1,8 +1,10 @@
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.

# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can add backtrace silencers for libraries that you're using but don't
# wish to see in your backtraces. Rails.backtrace_cleaner.add_silencer {
# |line| line =~ /my_noisy_library/ }

# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# You can also remove all the silencers if you're trying to debug a problem
# that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

+ 6
- 3
config/initializers/content_security_policy.rb View File

@@ -13,17 +13,20 @@
# policy.script_src :self, :https
# policy.style_src :self, :https
# # If you are using webpack-dev-server then specify webpack-dev-server host
# policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development?
# policy.connect_src :self, :https, "http://localhost:3035",
# "ws://localhost:3035" if Rails.env.development?

# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end

# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Rails.application.config.content_security_policy_nonce_generator = -> request
# { SecureRandom.base64(16) }

# Set the nonce only to specific directives
# Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
# Rails.application.config.content_security_policy_nonce_directives =
# %w(script-src)

# Report CSP violations to a specified URI
# For further information see the following documentation:

+ 14
- 11
config/initializers/friendly_id.rb View File

@@ -21,8 +21,9 @@ FriendlyId.defaults do |config|
config.reserved_words = %w[new edit index session login logout users admin
stylesheets assets javascripts images]

# This adds an option to treat reserved words as conflicts rather than exceptions.
# When there is no good candidate, a UUID will be appended, matching the existing
# This adds an option to treat reserved words as conflicts rather than
# exceptions. When there is no good candidate, a UUID will be appended,
# matching the existing
# conflict behavior.

# config.treat_reserved_as_conflict = true
@@ -64,15 +65,16 @@ FriendlyId.defaults do |config|
#
# config.slug_limit = 255
#
# When FriendlyId can not generate a unique ID from your base method, it appends
# a UUID, separated by a single dash. You can configure the character used as the
# separator. If you're upgrading from FriendlyId 4, you may wish to replace this
# with two dashes.
# When FriendlyId can not generate a unique ID from your base method, it
# appends a UUID, separated by a single dash. You can configure the character
# used as the separator. If you're upgrading from FriendlyId 4, you may wish
# to replace this with two dashes.
#
# config.sequence_separator = '-'
#
# Note that you must use the :slugged addon **prior** to the line which
# configures the sequence separator, or else FriendlyId will raise an undefined
# configures the sequence separator, or else FriendlyId will raise an
# undefined
# method error.
#
# ## Tips and Tricks
@@ -84,10 +86,11 @@ FriendlyId.defaults do |config|
# behavior by overriding the `should_generate_new_friendly_id?` method that
# FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave
# more like 4.0.
# Note: Use(include) Slugged module in the config if using the anonymous module.
# If you have `friendly_id :name, use: slugged` in the model, Slugged module
# is included after the anonymous module defined in the initializer, so it
# overrides the `should_generate_new_friendly_id?` method from the anonymous module.
# Note: Use(include) Slugged module in the config if using the anonymous
# module. If you have `friendly_id :name, use: slugged` in the model,
# Slugged module is included after the anonymous module defined in the
# initializer, so it overrides the `should_generate_new_friendly_id?` method
# from the anonymous module.
#
# config.use :slugged
# config.use Module.new {

+ 38
- 22
config/initializers/pagy.rb View File

@@ -1,16 +1,17 @@
# frozen_string_literal: true

# Pagy initializer file (3.7.5)
# Customize only what you really need and notice that Pagy works also without any of the following lines.
# Should you just cherry pick part of this file, please maintain the require-order of the extras
# Pagy initializer file (3.7.5) Customize only what you really need and notice
# that Pagy works also without any of the following lines. Should you just
# cherry pick part of this file, please maintain the require-order of the
# extras

# Extras
# See https://ddnexus.github.io/pagy/extras

# Backend Extras

# Array extra: Paginate arrays efficiently, avoiding expensive array-wrapping and without overriding
# See https://ddnexus.github.io/pagy/extras/array
# Array extra: Paginate arrays efficiently, avoiding expensive array-wrapping
# and without overriding See https://ddnexus.github.io/pagy/extras/array
# require 'pagy/extras/array'

# Countless extra: Paginate without any count, saving one query per rendering
@@ -28,19 +29,23 @@

# Frontend Extras

# Bootstrap extra: Add nav, nav_js and combo_nav_js helpers and templates for Bootstrap pagination
# Bootstrap extra: Add nav, nav_js and combo_nav_js helpers and templates for
# Bootstrap pagination
# See https://ddnexus.github.io/pagy/extras/bootstrap
require 'pagy/extras/bootstrap'

# Bulma extra: Add nav, nav_js and combo_nav_js helpers and templates for Bulma pagination
# Bulma extra: Add nav, nav_js and combo_nav_js helpers and templates for Bulma
# pagination
# See https://ddnexus.github.io/pagy/extras/bulma
# require 'pagy/extras/bulma'

# Foundation extra: Add nav, nav_js and combo_nav_js helpers and templates for Foundation pagination
# Foundation extra: Add nav, nav_js and combo_nav_js helpers and templates for
# Foundation pagination
# See https://ddnexus.github.io/pagy/extras/foundation
# require 'pagy/extras/foundation'

# Materialize extra: Add nav, nav_js and combo_nav_js helpers for Materialize pagination
# Materialize extra: Add nav, nav_js and combo_nav_js helpers for Materialize
# pagination
# See https://ddnexus.github.io/pagy/extras/materialize
# require 'pagy/extras/materialize'

@@ -50,7 +55,8 @@ require 'pagy/extras/bootstrap'
# See https://ddnexus.github.io/pagy/extras/navs
# require 'pagy/extras/navs'

# Semantic extra: Add nav, nav_js and combo_nav_js helpers for Semantic UI pagination
# Semantic extra: Add nav, nav_js and combo_nav_js helpers for Semantic UI
# pagination
# See https://ddnexus.github.io/pagy/extras/semantic
# require 'pagy/extras/semantic'

@@ -60,20 +66,25 @@ require 'pagy/extras/bootstrap'

# Multi size var used by the *_nav_js helpers
# See https://ddnexus.github.io/pagy/extras/navs#steps
# Pagy::VARS[:steps] = { 0 => [2,3,3,2], 540 => [3,5,5,3], 720 => [5,7,7,5] } # example
# Pagy::VARS[:steps] = { 0 => [2,3,3,2], 540 => [3,5,5,3], 720 => [5,7,7,5] }
#

# Feature Extras

# Headers extra: http response headers (and other helpers) useful for API pagination
# Headers extra: http response headers (and other helpers) useful for API
# pagination
# See http://ddnexus.github.io/pagy/extras/headers
# require 'pagy/extras/headers'
# Pagy::VARS[:headers] = { page: 'Current-Page', items: 'Page-Items', count: 'Total-Count', pages: 'Total-Pages' } # default
# Pagy::VARS[:headers] = { page: 'Current-Page', items: 'Page-Items', count:
# 'Total-Count', pages: 'Total-Pages' } # default

# Support extra: Extra support for features like: incremental, infinite, auto-scroll pagination
# Support extra: Extra support for features like: incremental, infinite,
# auto-scroll pagination
# See https://ddnexus.github.io/pagy/extras/support
# require 'pagy/extras/support'

# Items extra: Allow the client to request a custom number of items per page with an optional selector UI
# Items extra: Allow the client to request a custom number of items per page
# with an optional selector UI
# See https://ddnexus.github.io/pagy/extras/items
# require 'pagy/extras/items'
# Pagy::VARS[:items_param] = :items # default
@@ -82,15 +93,18 @@ require 'pagy/extras/bootstrap'
# Overflow extra: Allow for easy handling of overflowing pages
# See https://ddnexus.github.io/pagy/extras/overflow
# require 'pagy/extras/overflow'
# Pagy::VARS[:overflow] = :empty_page # default (other options: :last_page and :exception)
# Pagy::VARS[:overflow] = :empty_page

# Metadata extra: Provides the pagination metadata to Javascript frameworks like Vue.js, react.js, etc.
# Metadata extra: Provides the pagination metadata to Javascript frameworks
# like Vue.js, react.js, etc.
# See https://ddnexus.github.io/pagy/extras/metadata
# you must require the shared internal extra (BEFORE the metadata extra) ONLY if you need also the :sequels
# you must require the shared internal extra (BEFORE the metadata extra) ONLY
# if you need also the :sequels
# require 'pagy/extras/shared'
# require 'pagy/extras/metadata'
# For performance reason, you should explicitly set ONLY the metadata you use in the frontend
# Pagy::VARS[:metadata] = [:scaffold_url, :count, :page, :prev, :next, :last] # example
# For performance reason, you should explicitly set ONLY the metadata you use
# in the frontend Pagy::VARS[:metadata] = [:scaffold_url, :count, :page, :prev,
# :next, :last] # example

# Trim extra: Remove the page=1 param from links
# See https://ddnexus.github.io/pagy/extras/trim
@@ -124,7 +138,8 @@ Pagy::VARS[:items] = 21 # default

# Pagy internal I18n: ~18x faster using ~10x less memory than the i18n gem
# See https://ddnexus.github.io/pagy/api/frontend#i18n
# Notice: No need to configure anything in this section if your app uses only "en"
# Notice: No need to configure anything in this section if your app uses only
# "en"
# or if you use the i18n extra below
#
# Examples:
@@ -149,7 +164,8 @@ Pagy::VARS[:items] = 21 # default
# filepath: 'path/to/pagy-xyz.yml',
# pluralize: lambda{|count| ... } )

# I18n extra: uses the standard i18n gem which is ~18x slower using ~10x more memory
# I18n extra: uses the standard i18n gem which is ~18x slower using ~10x more
# memory
# than the default pagy internal i18n (see above)
# See https://ddnexus.github.io/pagy/extras/i18n
# require 'pagy/extras/i18n'

+ 2
- 1
config/initializers/wrap_parameters.rb View File

@@ -5,7 +5,8 @@
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.

# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
# Enable parameter wrapping for JSON. You can disable this by setting :format
# to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end

+ 2
- 1
config/puma.rb View File

@@ -10,7 +10,8 @@ max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 }
min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count }
threads min_threads_count, max_threads_count

# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
# Specifies the `port` that Puma will listen on to receive requests; default is
# 3000.
#
port ENV.fetch('PORT') { 3000 }


+ 3
- 1
config/routes.rb View File

@@ -3,5 +3,7 @@
Rails.application.routes.draw do
root 'professionals#index'

get 'professionals/:id', as: :professional, controller: :professionals, action: :show
get 'professionals/:id', as: :professional,
controller: :professionals,
action: :show
end

+ 2
- 0
db/migrate/20200410153131_enable_pgcrypto_extension.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Enables the postgres crypto extension used for uuidgen
class EnablePgcryptoExtension < ActiveRecord::Migration[6.0]
def change
enable_extension 'pgcrypto'

+ 2
- 0
db/migrate/20200410160000_create_profiles.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Create basic profiles
class CreateProfiles < ActiveRecord::Migration[6.0]
def change
create_table :profiles, id: :uuid do |t|

+ 1
- 0
db/migrate/20200412131932_create_active_storage_tables.active_storage.rb View File

@@ -1,5 +1,6 @@
# frozen_string_literal: true

##
# This migration comes from active_storage (originally 20170806125915)
class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
def change

+ 2
- 0
db/migrate/20200413130444_add_last_activity_at_to_profiles.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Add a timestamp used for ordering to profiles
class AddLastActivityAtToProfiles < ActiveRecord::Migration[6.0]
class Profile < ApplicationRecord
end

+ 2
- 0
db/migrate/20200416094746_add_contact_details_to_profiles.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Add a json field to hold contact details
class AddContactDetailsToProfiles < ActiveRecord::Migration[6.0]
def change
add_column :profiles, :contact_details, :jsonb

+ 2
- 0
db/migrate/20200430111245_add_slug_to_profiles.rb View File

@@ -1,5 +1,7 @@
# frozen_string_literal: true

##
# Add a slug field to profiles
class AddSlugToProfiles < ActiveRecord::Migration[6.0]
def change
add_column :profiles, :slug, :string

+ 3
- 8
db/migrate/20200430111256_create_friendly_id_slugs.rb View File

@@ -1,13 +1,8 @@
# frozen_string_literal: true

MIGRATION_CLASS =
if ActiveRecord::VERSION::MAJOR >= 5
ActiveRecord::Migration["#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}"]
else
ActiveRecord::Migration
end

class CreateFriendlyIdSlugs < MIGRATION_CLASS
##
# Add friendly_id_slugs table
class CreateFriendlyIdSlugs < ActiveRecord::Migration[6.0]
def change
create_table :friendly_id_slugs do |t|
t.string :slug, null: false

+ 6
- 4
db/schema.rb View File

@@ -2,15 +2,17 @@

# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
# incrementally modify your database, and then regenerate this schema
# definition.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# db:schema:load`. When creating a new database, `rails db:schema:load` tends
# to be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
# It's strongly recommended that you check this file into your version control
# system.

ActiveRecord::Schema.define(version: 20_200_430_111_256) do
# These are extensions that must be enabled in order to support this database

+ 18
- 20
db/seeds.rb View File

@@ -2,24 +2,28 @@

require 'csv'

# 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 rails db:seed command (or created alongside the database with db:setup).
# 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 rails db:seed
# command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# movies = Movie.create(
# [{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]
# )
# Character.create(name: 'Luke', movie: movies.first)

# Profiles
seed_csv = Rails.root.join('db', 'seeds', 'profiles.csv')
seed_csv = Rails.root.join('db/seeds/profiles.csv')

avatar_files = Dir[Rails.root.join('db', 'seeds', 'avatars', '*.jpg')]
header_images = Dir[Rails.root.join('db', 'seeds', 'headers', '*.jpg')]
avatar_files = Dir[Rails.root.join('db/seeds/avatars/*.jpg')]
header_images = Dir[Rails.root.join('db/seeds/headers/*.jpg')]

model_class = Profile
records = []

contact_lines = CSV.read(Rails.root.join('db', 'seeds', 'contact_details.csv'), headers: true).to_enum
csv_file = Rails.root.join('db/seeds/contact_details.csv')
contact_lines = CSV.read(csv_file, headers: true).to_enum

CSV.foreach(seed_csv, headers: true) do |row|
contact_details = []
@@ -27,18 +31,12 @@ CSV.foreach(seed_csv, headers: true) do |row|
next unless key && value

type = case key
when 'Home', 'Work'
:phone
when 'Personal', 'Workemail'
:email
when 'Twitter'
:twitter
when 'Facebook'
:facebook
when 'Linkedin'
:linkedin
when 'Street Address'
:address
when 'Home', 'Work' then :phone
when 'Personal', 'Workemail' then :email
when 'Twitter' then :twitter
when 'Facebook' then :facebook
when 'Linkedin' then :linkedin
when 'Street Address' then :address
end
contact_details << { key: key, value: value, type: type }
end
@@ -60,4 +58,4 @@ CSV.foreach(seed_csv, headers: true) do |row|
record.save!
records << record
end
puts "Imported #{records.count} #{model_class} records"
Rails.logger.info "Imported #{records.count} #{model_class} records"

+ 10
- 8
test/channels/application_cable/connection_test.rb View File

@@ -2,12 +2,14 @@

require 'test_helper'

class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
# test "connects with cookies" do
# cookies.signed[:user_id] = 42
#
# connect
#
# assert_equal connection.user_id, "42"
# end
module ApplicationCable
class ConnectionTest < ActionCable::Connection::TestCase
# test "connects with cookies" do
# cookies.signed[:user_id] = 42
#
# connect
#
# assert_equal connection.user_id, "42"
# end
end
end

+ 3
- 1
test/helpers/public_helper_test.rb View File

@@ -81,6 +81,8 @@ class PublicHelperTest < ActionView::TestCase
private

def contact_detail(key: '', value: '', type: '')
Profile::ContactDetailViewModel.new(OpenStruct.new(key: key, value: value, type: type))
Profile::ContactDetailViewModel.new(
OpenStruct.new(key: key, value: value, type: type)
)
end
end

+ 42
- 40
test/models/profile/contact_detail_test.rb View File

@@ -2,56 +2,58 @@

require 'test_helper'

class Profile::ContactDetailTest < ActiveSupport::TestCase
test '#contact_details with proper object is valid' do
subject(key: 'k', value: 'v', type: 't').valid?
assert_empty subject.errors[:contact_details]
end
class Profile
class ContactDetailTest < ActiveSupport::TestCase
test '#contact_details with proper object is valid' do
subject(key: 'k', value: 'v', type: 't').valid?
assert_empty subject.errors[:contact_details]
end

test '#contact_details must be key, value, type objects each with a string' do
msg = "can't be blank"
refute subject(value: 'v', type: 't').valid?
assert_includes subject.errors[:key], msg
test '#contact_details must have key, value, type with a string' do
msg = "can't be blank"
assert_not subject(value: 'v', type: 't').valid?
assert_includes subject.errors[:key], msg

refute subject(key: 'k', type: 't').valid?
assert_includes subject.errors[:value], msg
assert_not subject(key: 'k', type: 't').valid?
assert_includes subject.errors[:value], msg

refute subject(key: 'k', value: 'v').valid?
assert_includes subject.errors[:type], msg
end
assert_not subject(key: 'k', value: 'v').valid?
assert_includes subject.errors[:type], msg
end

test 'key may never be larger than 100 characters' do
refute subject(key: 'x' * 101).valid?
assert_includes subject.errors[:key],
'is too long (maximum is 100 characters)'
end
test 'key may never be larger than 100 characters' do
assert_not subject(key: 'x' * 101).valid?
assert_includes subject.errors[:key],
'is too long (maximum is 100 characters)'
end

test 'value may never be larger than 300 characters' do
refute subject(value: 'x' * 301).valid?
assert_includes subject.errors[:value],
'is too long (maximum is 300 characters)'
end
test 'value may never be larger than 300 characters' do
assert_not subject(value: 'x' * 301).valid?
assert_includes subject.errors[:value],
'is too long (maximum is 300 characters)'
end

test 'type can only be of whitelist' do
whitelist = %w[email phone twitter facebook linkedin address]
whitelist.each do |valid_type|
subject(type: valid_type).valid?
assert_not_includes subject.errors[:type],
'is not included in the list'
end

test 'type can only be of whitelist' do
whitelist = %w[email phone twitter facebook linkedin address]
whitelist.each do |valid_type|
subject(type: valid_type).valid?
refute_includes subject.errors[:type],
assert_not subject(type: :geocities).valid?
assert_includes subject.errors[:type],
'is not included in the list'
end

refute subject(type: :geocities).valid?
assert_includes subject.errors[:type],
'is not included in the list'
end

private
private

def subject(attributes = nil)
if attributes
@subject = Profile::ContactDetail.new(attributes)
else
@subject
def subject(attributes = nil)
if attributes
@subject = Profile::ContactDetail.new(attributes)
else
@subject
end
end
end
end

+ 15
- 9
test/models/profile_test.rb View File

@@ -6,7 +6,7 @@ require 'minitest/mock'
class ProfileTest < ActiveSupport::TestCase
test '#by_activity sorts last active top' do
Profile.create(name: 'Harry', last_activity_at: 2.days.ago)
Profile.create(name: 'Ron', last_activity_at: 1.days.ago)
Profile.create(name: 'Ron', last_activity_at: 1.day.ago)

assert_equal(%w[Ron Harry], Profile.by_activity.pluck(:name))
end
@@ -22,27 +22,27 @@ class ProfileTest < ActiveSupport::TestCase
end

test '#contact_details is an array of ContactDetail' do
subject = Profile.new(contact_details: [{ key: 'k', value: 'v', type: 'phone' }])
subject = Profile.new(contact_details: [valid_attributes])
assert_kind_of Profile::ContactDetail, subject.contact_details.first
end

test '#contact_details with proper object is valid' do
subject = Profile.new(contact_details: [{ key: 'k', value: 'v', type: 'phone' }])
subject = Profile.new(contact_details: [valid_attributes])
subject.valid?
assert_empty subject.errors[:contact_details]
end

test '#contact_details with ContactDetail is valid' do
subject = Profile.new(contact_details: [
Profile::ContactDetail.new(key: 'k', value: 'v', type: 'phone')
])
subject = Profile.new(
contact_details: [Profile::ContactDetail.new(valid_attributes)]
)
subject.valid?
assert_empty subject.errors[:contact_details]
end

test '#contact_details must be an array' do
subject = Profile.new(contact_details: { foo: 'bar' })
refute subject.valid?
assert_not subject.valid?
assert_includes subject.errors[:contact_details], 'is formatted wrong'
end

@@ -52,7 +52,7 @@ class ProfileTest < ActiveSupport::TestCase
end

subject = Profile.new(contact_details: contact_details)
refute subject.valid?
assert_not subject.valid?
assert_includes subject.errors[:contact_details],
'has too many entries (maximum is 255 entries)'
end
@@ -66,7 +66,13 @@ class ProfileTest < ActiveSupport::TestCase
invalid_detail.expect :as_json, { key: :value }, [Hash]

subject = Profile.new(contact_details: [valid_detail, invalid_detail])
refute subject.valid?
assert_not subject.valid?
assert_includes subject.errors[:contact_details], 'is formatted wrong'
end

private

def valid_attributes
@valid_attributes ||= { key: 'k', value: 'v', type: 'phone' }
end
end

+ 1
- 1
test/support/workflows/profile_creator.rb View File

@@ -29,7 +29,7 @@ module Workflows

def data
Psych.load(
File.read(Rails.root.join('test', 'fixtures', 'profiles.yml')),
File.read(Rails.root.join('test/fixtures/profiles.yml')),
symbolize_names: true
)
end

+ 1
- 1
test/support/workflows/profile_importer.rb View File

@@ -9,7 +9,7 @@ module Workflows
end

def call
seed_csv = Rails.root.join('db', 'seeds', 'profiles.csv')
seed_csv = Rails.root.join('db/seeds/profiles.csv')
model_class = Profile

records = []

+ 1
- 1
test/system/list_professionals_test.rb View File

@@ -51,7 +51,7 @@ class ListProfessionalsTest < ApplicationSystemTestCase
# For now, depend on fixtures.
visit root_url
# Simply assert that Ron Weasly comes first
assert_text /Ron Weasly.*Harry Potter/m
assert_text(/Ron Weasly.*Harry Potter/m)
end

test 'anon visits page 2 of an index with 22 professionals' do

+ 10
- 6
test/test_helper.rb View File

@@ -1,16 +1,20 @@
# frozen_string_literal: true

ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'

require 'support/workflows.rb'
glb = Rails.root.join('test', 'support', '**', '*rb')
Dir[glb].each do |file|
glb = Rails.root.join('test/support/**/*rb')
Dir[glb].sort.each do |file|
require file
end

class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
module ActiveSupport
class TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)

# Add more helper methods to be used by all tests here...
# Add more helper methods to be used by all tests here...
end
end

Loading…
Cancel
Save