Add rubocop and lint all files

This commit is contained in:
h8rry 2022-09-06 15:44:27 +08:00
parent 5368ee2a79
commit c64217d15f
37 changed files with 206 additions and 176 deletions

27
.rubocop.yml Normal file
View File

@ -0,0 +1,27 @@
Style/FrozenStringLiteralComment:
Enabled: false
Style/EmptyMethod:
Enabled: false
Style/Documentation:
Enabled: false
Style/NumericLiterals:
Exclude:
- db/schema.rb
Style/BlockDelimiters:
Exclude:
- spec/**/*
Style/SymbolProc:
Exclude:
- db/migrate/**/*
Metrics/BlockLength:
Enabled: false
Style/MixinUsage:
Enabled: false
Metrics/MethodLength:
Enabled: false
Layout/LineLength:
Enabled: false
Style/HashSyntax:
Enabled: false
Metrics/AbcSize:
Enabled: false

View File

@ -1,6 +1,6 @@
# 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_relative "config/application"
require_relative 'config/application'
Rails.application.load_tasks

View File

@ -3,7 +3,7 @@ module Api
def create
@user = User.find_by(username: params[:user][:username])
if @user and BCrypt::Password.new(@user.password) == params[:user][:password]
if @user && (BCrypt::Password.new(@user.password) == params[:user][:password])
session = @user.sessions.create
cookies.permanent.signed[:twitter_session_token] = {
value: session.token,
@ -36,7 +36,7 @@ module Api
token = cookies.signed[:twitter_session_token]
session = Session.find_by(token: token)
if session and session.destroy
if session&.destroy
render json: {
success: true
}

View File

@ -26,7 +26,7 @@ module Api
user = session.user
tweet = Tweet.find_by(id: params[:id])
if tweet and tweet.user == user and tweet.destroy
if tweet && (tweet.user == user) && tweet.destroy
render json: {
success: true
}
@ -48,8 +48,8 @@ module Api
private
def tweet_params
params.require(:tweet).permit(:message, :image)
end
def tweet_params
params.require(:tweet).permit(:message, :image)
end
end
end

View File

@ -14,8 +14,8 @@ module Api
private
def user_params
params.require(:user).permit(:email, :password, :username)
end
def user_params
params.require(:user).permit(:email, :password, :username)
end
end
end

View File

@ -7,7 +7,7 @@ class Session < ApplicationRecord
private
def generate_session_token
self.token = SecureRandom.urlsafe_base64
end
def generate_session_token
self.token = SecureRandom.urlsafe_base64
end
end

View File

@ -13,7 +13,7 @@ class User < ApplicationRecord
private
def hash_password
self.password = BCrypt::Password.create(self.password)
end
def hash_password
self.password = BCrypt::Password.create(password)
end
end

View File

@ -8,46 +8,46 @@
# this file is here to facilitate running it.
#
require "rubygems"
require 'rubygems'
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
ENV["BUNDLER_VERSION"]
ENV['BUNDLER_VERSION']
end
def cli_arg_version
return unless invoked_as_script? # don't want to hijack other binstubs
return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
return unless 'update'.start_with?(ARGV.first || ' ') # must be running `bundle update`
bundler_version = nil
update_index = nil
ARGV.each_with_index do |a, i|
if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
bundler_version = a
end
bundler_version = a if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
bundler_version = $1
bundler_version = Regexp.last_match(1)
update_index = i
end
bundler_version
end
def gemfile
gemfile = ENV["BUNDLE_GEMFILE"]
gemfile = ENV['BUNDLE_GEMFILE']
return gemfile if gemfile && !gemfile.empty?
File.expand_path("../../Gemfile", __FILE__)
File.expand_path('../Gemfile', __dir__)
end
def lockfile
lockfile =
case File.basename(gemfile)
when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
when 'gems.rb' then gemfile.sub(/\.rb$/, gemfile)
else "#{gemfile}.lock"
end
File.expand_path(lockfile)
@ -55,15 +55,17 @@ m = Module.new do
def lockfile_version
return unless File.file?(lockfile)
lockfile_contents = File.read(lockfile)
return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
Regexp.last_match(1)
end
def bundler_requirement
@bundler_requirement ||=
env_var_version || cli_arg_version ||
bundler_requirement_for(lockfile_version)
bundler_requirement_for(lockfile_version)
end
def bundler_requirement_for(version)
@ -73,28 +75,30 @@ m = Module.new do
requirement = bundler_gem_version.approximate_recommendation
return requirement unless Gem.rubygems_version < Gem::Version.new("2.7.0")
return requirement unless Gem.rubygems_version < Gem::Version.new('2.7.0')
requirement += ".a" if bundler_gem_version.prerelease?
requirement += '.a' if bundler_gem_version.prerelease?
requirement
end
def load_bundler!
ENV["BUNDLE_GEMFILE"] ||= gemfile
ENV['BUNDLE_GEMFILE'] ||= gemfile
activate_bundler
end
def activate_bundler
gem_error = activation_error_handling do
gem "bundler", bundler_requirement
gem 'bundler', bundler_requirement
end
return if gem_error.nil?
require_error = activation_error_handling do
require "bundler/version"
require 'bundler/version'
end
return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION))
warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`"
exit 42
end
@ -109,6 +113,4 @@ end
m.load_bundler!
if m.invoked_as_script?
load Gem.bin_path("bundler", "bundle")
end
load Gem.bin_path('bundler', 'bundle') if m.invoked_as_script?

View File

@ -1,5 +1,5 @@
#!/usr/bin/env ruby
load File.expand_path("spring", __dir__)
load File.expand_path('spring', __dir__)
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative "../config/boot"
require "rails/commands"
require_relative '../config/boot'
require 'rails/commands'

View File

@ -1,5 +1,5 @@
#!/usr/bin/env ruby
load File.expand_path("spring", __dir__)
require_relative "../config/boot"
require "rake"
load File.expand_path('spring', __dir__)
require_relative '../config/boot'
require 'rake'
Rake.application.run

View File

@ -1,5 +1,5 @@
#!/usr/bin/env ruby
require "fileutils"
require 'fileutils'
# path to your application root.
APP_ROOT = File.expand_path('..', __dir__)

View File

@ -1,13 +1,13 @@
#!/usr/bin/env ruby
if !defined?(Spring) && [nil, "development", "test"].include?(ENV["RAILS_ENV"])
gem "bundler"
require "bundler"
if !defined?(Spring) && [nil, 'development', 'test'].include?(ENV['RAILS_ENV'])
gem 'bundler'
require 'bundler'
# Load Spring without loading other gems in the Gemfile, for speed.
Bundler.locked_gems&.specs&.find { |spec| spec.name == "spring" }&.tap do |spring|
Bundler.locked_gems&.specs&.find { |spec| spec.name == 'spring' }&.tap do |spring|
Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
gem "spring", spring.version
require "spring/binstub"
gem 'spring', spring.version
require 'spring/binstub'
rescue Gem::LoadError
# Ignore when Spring is not installed.
end

View File

@ -1,18 +1,18 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"] ||= "development"
ENV['RAILS_ENV'] ||= ENV['RACK_ENV'] || 'development'
ENV['NODE_ENV'] ||= 'development'
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
require 'pathname'
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile',
Pathname.new(__FILE__).realpath)
require "bundler/setup"
require 'bundler/setup'
require "webpacker"
require "webpacker/webpack_runner"
require 'webpacker'
require 'webpacker/webpack_runner'
APP_ROOT = File.expand_path("..", __dir__)
APP_ROOT = File.expand_path('..', __dir__)
Dir.chdir(APP_ROOT) do
Webpacker::WebpackRunner.run(ARGV)
end

View File

@ -1,18 +1,18 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"] ||= "development"
ENV['RAILS_ENV'] ||= ENV['RACK_ENV'] || 'development'
ENV['NODE_ENV'] ||= 'development'
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
require 'pathname'
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile',
Pathname.new(__FILE__).realpath)
require "bundler/setup"
require 'bundler/setup'
require "webpacker"
require "webpacker/dev_server_runner"
require 'webpacker'
require 'webpacker/dev_server_runner'
APP_ROOT = File.expand_path("..", __dir__)
APP_ROOT = File.expand_path('..', __dir__)
Dir.chdir(APP_ROOT) do
Webpacker::DevServerRunner.run(ARGV)
end

View File

@ -1,17 +1,17 @@
#!/usr/bin/env ruby
APP_ROOT = File.expand_path('..', __dir__)
Dir.chdir(APP_ROOT) do
yarn = ENV["PATH"].split(File::PATH_SEPARATOR).
select { |dir| File.expand_path(dir) != __dir__ }.
product(["yarn", "yarn.cmd", "yarn.ps1"]).
map { |dir, file| File.expand_path(file, dir) }.
find { |file| File.executable?(file) }
yarn = ENV['PATH'].split(File::PATH_SEPARATOR)
.reject { |dir| File.expand_path(dir) == __dir__ }
.product(['yarn', 'yarn.cmd', 'yarn.ps1'])
.map { |dir, file| File.expand_path(file, dir) }
.find { |file| File.executable?(file) }
if yarn
exec yarn, *ARGV
else
$stderr.puts "Yarn executable was not detected in the system."
$stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install"
warn 'Yarn executable was not detected in the system.'
warn 'Download Yarn at https://yarnpkg.com/en/docs/install'
exit 1
end
end

View File

@ -1,6 +1,6 @@
# This file is used by Rack-based servers to start the application.
require_relative "config/environment"
require_relative 'config/environment'
run Rails.application
Rails.application.load_server

View File

@ -1,6 +1,6 @@
require_relative "boot"
require_relative 'boot'
require "rails/all"
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.

View File

@ -1,4 +1,4 @@
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require "bundler/setup" # Set up gems listed in the Gemfile.
require "bootsnap/setup" # Speed up boot time by caching expensive operations.
require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' # Speed up boot time by caching expensive operations.

View File

@ -1,5 +1,5 @@
# Load the Rails application.
require_relative "application"
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!

View File

@ -1,4 +1,4 @@
require "active_support/core_ext/integer/time"
require 'active_support/core_ext/integer/time'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.

View File

@ -1,4 +1,4 @@
require "active_support/core_ext/integer/time"
require 'active_support/core_ext/integer/time'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
@ -53,7 +53,7 @@ Rails.application.configure do
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
@ -88,8 +88,8 @@ Rails.application.configure do
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end

View File

@ -1,4 +1,4 @@
require "active_support/core_ext/integer/time"
require 'active_support/core_ext/integer/time'
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that

View File

@ -5,4 +5,4 @@
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code
# by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'".
Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
Rails.backtrace_cleaner.remove_silencers! if ENV['BACKTRACE']

View File

@ -1,6 +1,6 @@
# Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [
:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
Rails.application.config.filter_parameters += %i[
passw secret token _key crypt salt certificate otp ssn
]

View File

@ -4,25 +4,25 @@
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
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 `worker_timeout` threshold that Puma will use to wait before
# terminating a worker in development environments.
#
worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development"
worker_timeout 3600 if ENV.fetch('RAILS_ENV', 'development') == 'development'
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
port ENV.fetch('PORT', 3000)
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
environment ENV.fetch('RAILS_ENV') { 'development' }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together

View File

@ -1,6 +1,6 @@
Spring.watch(
".ruby-version",
".rbenv-vars",
"tmp/restart.txt",
"tmp/caching-dev.txt"
'.ruby-version',
'.rbenv-vars',
'tmp/restart.txt',
'tmp/caching-dev.txt'
)

View File

@ -11,7 +11,7 @@ class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
t.string :checksum, null: false
t.datetime :created_at, null: false
t.index [ :key ], unique: true
t.index [:key], unique: true
end
create_table :active_storage_attachments do |t|
@ -21,7 +21,7 @@ class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
t.datetime :created_at, null: false
t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true
t.index %i[record_type record_id name blob_id], name: 'index_active_storage_attachments_uniqueness', unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
@ -29,7 +29,7 @@ class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
t.belongs_to :blob, null: false, index: false
t.string :variation_digest, null: false
t.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: true
t.index %i[blob_id variation_digest], name: 'index_active_storage_variant_records_uniqueness', unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end

93
db/schema.rb generated
View File

@ -11,63 +11,62 @@
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2022_03_28_042533) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.integer "record_id", null: false
t.integer "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
create_table 'active_storage_attachments', force: :cascade do |t|
t.string 'name', null: false
t.string 'record_type', null: false
t.integer 'record_id', null: false
t.integer 'blob_id', null: false
t.datetime 'created_at', null: false
t.index ['blob_id'], name: 'index_active_storage_attachments_on_blob_id'
t.index %w[record_type record_id name blob_id], name: 'index_active_storage_attachments_uniqueness', unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.string "service_name", null: false
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
create_table 'active_storage_blobs', force: :cascade do |t|
t.string 'key', null: false
t.string 'filename', null: false
t.string 'content_type'
t.text 'metadata'
t.string 'service_name', null: false
t.bigint 'byte_size', null: false
t.string 'checksum', null: false
t.datetime 'created_at', null: false
t.index ['key'], name: 'index_active_storage_blobs_on_key', unique: true
end
create_table "active_storage_variant_records", force: :cascade do |t|
t.integer "blob_id", null: false
t.string "variation_digest", null: false
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
create_table 'active_storage_variant_records', force: :cascade do |t|
t.integer 'blob_id', null: false
t.string 'variation_digest', null: false
t.index %w[blob_id variation_digest], name: 'index_active_storage_variant_records_uniqueness', unique: true
end
create_table "sessions", force: :cascade do |t|
t.string "token"
t.integer "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["user_id"], name: "index_sessions_on_user_id"
create_table 'sessions', force: :cascade do |t|
t.string 'token'
t.integer 'user_id'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
t.index ['user_id'], name: 'index_sessions_on_user_id'
end
create_table "tweets", force: :cascade do |t|
t.string "message"
t.integer "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["user_id"], name: "index_tweets_on_user_id"
create_table 'tweets', force: :cascade do |t|
t.string 'message'
t.integer 'user_id'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
t.index ['user_id'], name: 'index_tweets_on_user_id'
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.string "password"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
create_table 'users', force: :cascade do |t|
t.string 'username'
t.string 'email'
t.string 'password'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
t.index ['email'], name: 'index_users_on_email', unique: true
t.index ['username'], name: 'index_users_on_username', unique: true
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
add_foreign_key "sessions", "users"
add_foreign_key "tweets", "users"
add_foreign_key 'active_storage_attachments', 'active_storage_blobs', column: 'blob_id'
add_foreign_key 'active_storage_variant_records', 'active_storage_blobs', column: 'blob_id'
add_foreign_key 'sessions', 'users'
add_foreign_key 'tweets', 'users'
end

View File

@ -1,5 +1,4 @@
FactoryBot.define do
factory :session do
end
end

View File

@ -1,5 +1,5 @@
FactoryBot.define do
factory :tweet do
message {'Test Message'}
message { 'Test Message' }
end
end

View File

@ -1,7 +1,7 @@
FactoryBot.define do
factory :user do
email {'test@test.com'}
username {'testtest'}
password {'testtest'}
email { 'test@test.com' }
username { 'testtest' }
password { 'testtest' }
end
end

View File

@ -1,3 +1,2 @@
RSpec.describe "Sessions", type: :request do
RSpec.describe 'Sessions', type: :request do
end

View File

@ -1,2 +1,2 @@
RSpec.describe "Tweets", type: :request do
RSpec.describe 'Tweets', type: :request do
end

View File

@ -1,2 +1,2 @@
RSpec.describe "Users", type: :request do
RSpec.describe 'Users', type: :request do
end

View File

@ -1,4 +1,4 @@
require "test_helper"
require 'test_helper'
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :chrome, screen_size: [1400, 1400]

View File

@ -1,11 +1,13 @@
require "test_helper"
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

View File

@ -1,13 +1,15 @@
ENV['RAILS_ENV'] ||= 'test'
require_relative "../config/environment"
require "rails/test_help"
require_relative '../config/environment'
require 'rails/test_help'
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)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
# Add more helper methods to be used by all tests here...
end
end