diff --git a/.rubocop.yml b/.rubocop.yml
index 4999be032..a57eb1c2f 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -249,6 +249,9 @@ Layout/InitialIndentation:
# Rails
+Rails:
+ Enabled: true
+
Rails/Date:
Description: >-
Checks the correct usage of date aware methods,
diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml
index 04bc6abff..9e89df048 100644
--- a/.rubocop_todo.yml
+++ b/.rubocop_todo.yml
@@ -67,3 +67,27 @@ RSpec/AnyInstance:
# URISchemes: http, https
Metrics/LineLength:
Max: 279
+
+Rails/HasManyOrHasOneDependent:
+ Enabled: false
+
+# Potential security risks
+# Offense count: 16
+Rails/OutputSafety:
+ Exclude:
+ - 'app/controllers/stripe_subscriptions_controller.rb'
+ - 'app/helpers/application_helper.rb'
+ - 'app/helpers/comments_helper.rb'
+ - 'app/labor/markdown_parser.rb'
+ - 'app/liquid_tags/dev_comment_tag.rb'
+ - 'app/liquid_tags/github_tag/github_issue_tag.rb'
+ - 'app/liquid_tags/liquid_tag_base.rb'
+ - 'app/liquid_tags/tweet_tag.rb'
+ - 'app/models/comment.rb'
+ - 'app/models/display_ad.rb'
+ - 'app/models/message.rb'
+ - 'app/views/api/v0/articles/show.json.jbuilder'
+ - 'app/views/articles/feed.rss.builder'
+
+Rails/SkipsModelValidations:
+ Enabled: false
diff --git a/app/black_box/black_box.rb b/app/black_box/black_box.rb
index d142231a2..3e305c002 100644
--- a/app/black_box/black_box.rb
+++ b/app/black_box/black_box.rb
@@ -5,7 +5,7 @@ class BlackBox
usable_date = article.crossposted_at || article.published_at
reaction_points = article.score
- super_super_recent_bonus = usable_date > 1.hours.ago ? 28 : 0
+ super_super_recent_bonus = usable_date > 1.hour.ago ? 28 : 0
super_recent_bonus = usable_date > 8.hours.ago ? 31 : 0
recency_bonus = usable_date > 12.hours.ago ? 80 : 0
today_bonus = usable_date > 26.hours.ago ? 395 : 0
diff --git a/app/black_box/google_analytics.rb b/app/black_box/google_analytics.rb
index 92e243e76..7a6947f65 100644
--- a/app/black_box/google_analytics.rb
+++ b/app/black_box/google_analytics.rb
@@ -16,7 +16,7 @@ class GoogleAnalytics
def get_pageviews
requests = @article_ids.map do |id|
- article = Article.find_by_id(id)
+ article = Article.find_by(id: id)
make_report_request("ga:pagePath=@#{article.slug}", "ga:pageviews")
end
pageviews = fetch_all_results(requests)
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb
index f08ce0395..ef03257c2 100644
--- a/app/controllers/admin/users_controller.rb
+++ b/app/controllers/admin/users_controller.rb
@@ -50,7 +50,7 @@ module Admin
gitlab_url
linkedin_url
]
- accessible << %i[password password_confirmation] unless params[:user][:password].blank?
+ accessible << %i[password password_confirmation] if params[:user][:password].present?
params.require(:user).permit(accessible)
end
end
diff --git a/app/controllers/api/v0/articles_controller.rb b/app/controllers/api/v0/articles_controller.rb
index 37fd2e697..cd1a7a201 100644
--- a/app/controllers/api/v0/articles_controller.rb
+++ b/app/controllers/api/v0/articles_controller.rb
@@ -26,7 +26,7 @@ module Api
def show
@article = if params[:id] == "by_path"
- Article.includes(:user).find_by_path(params[:url])&.decorate
+ Article.includes(:user).find_by(path: params[:url])&.decorate
else
Article.includes(:user).find(params[:id])&.decorate
end
diff --git a/app/controllers/api/v0/podcast_episodes_controller.rb b/app/controllers/api/v0/podcast_episodes_controller.rb
index 3932b93b5..87852380f 100644
--- a/app/controllers/api/v0/podcast_episodes_controller.rb
+++ b/app/controllers/api/v0/podcast_episodes_controller.rb
@@ -18,7 +18,7 @@ module Api
def index
@page = params[:page]
if params[:username]
- @podcast = Podcast.find_by_slug(params[:username]) || not_found
+ @podcast = Podcast.find_by(slug: params[:username]) || not_found
@podcast_episodes = @podcast.
podcast_episodes.order("published_at desc").
page(@page).
diff --git a/app/controllers/api/v0/reactions_controller.rb b/app/controllers/api/v0/reactions_controller.rb
index 294fe0548..8cade8705 100644
--- a/app/controllers/api/v0/reactions_controller.rb
+++ b/app/controllers/api/v0/reactions_controller.rb
@@ -36,7 +36,7 @@ module Api
private
def valid_user
- user = User.find_by_secret(params[:key])
+ user = User.find_by(secret: params[:key])
user = nil unless user.has_role?(:super_admin)
user
end
diff --git a/app/controllers/api/v0/users_controller.rb b/app/controllers/api/v0/users_controller.rb
index a2592509e..1df3b0a65 100644
--- a/app/controllers/api/v0/users_controller.rb
+++ b/app/controllers/api/v0/users_controller.rb
@@ -17,7 +17,7 @@ module Api
def show
@user = if params[:id] == "by_username"
- User.find_by_username(params[:url])
+ User.find_by(username: params[:url])
else
User.find(params[:id])
end
diff --git a/app/controllers/api_secrets_controller.rb b/app/controllers/api_secrets_controller.rb
index f5138d4a8..215a013d1 100644
--- a/app/controllers/api_secrets_controller.rb
+++ b/app/controllers/api_secrets_controller.rb
@@ -27,6 +27,6 @@ class ApiSecretsController < ApplicationController
private
def set_api_secret
- @secret = ApiSecret.find_by_id(params[:id]) || not_found
+ @secret = ApiSecret.find_by(id: params[:id]) || not_found
end
end
diff --git a/app/controllers/articles_controller.rb b/app/controllers/articles_controller.rb
index ddc6f3e73..836e16b6e 100644
--- a/app/controllers/articles_controller.rb
+++ b/app/controllers/articles_controller.rb
@@ -15,9 +15,9 @@ class ArticlesController < ApplicationController
page(params[:page].to_i).per(12)
if params[:username]
- if (@user = User.find_by_username(params[:username]))
+ if (@user = User.find_by(username: params[:username]))
@articles = @articles.where(user_id: @user.id)
- elsif (@user = Organization.find_by_slug(params[:username]))
+ elsif (@user = Organization.find_by(slug: params[:username]))
@articles = @articles.where(organization_id: @user.id).includes(:user)
else
render body: nil
@@ -36,7 +36,7 @@ class ArticlesController < ApplicationController
def new
@user = current_user
@organization = @user&.organization
- @tag = Tag.find_by_name(params[:template])
+ @tag = Tag.find_by(name: params[:template])
@prefill = params[:prefill].to_s.gsub("\\n ", "\n").gsub("\\n", "\n")
@article = if @tag.present? && @user&.editor_version == "v2"
authorize Article
@@ -136,7 +136,7 @@ class ArticlesController < ApplicationController
end
def delete_confirm
- @article = current_user.articles.find_by_slug(params[:slug])
+ @article = current_user.articles.find_by(slug: params[:slug])
authorize @article
end
@@ -182,9 +182,9 @@ class ArticlesController < ApplicationController
end
def set_article
- owner = User.find_by_username(params[:username]) || Organization.find_by_slug(params[:username])
+ owner = User.find_by(username: params[:username]) || Organization.find_by(slug: params[:username])
found_article = if params[:slug]
- owner.articles.includes(:user).find_by_slug(params[:slug])
+ owner.articles.includes(:user).find_by(slug: params[:slug])
else
Article.includes(:user).find(params[:id])
end
@@ -200,7 +200,7 @@ class ArticlesController < ApplicationController
end
def job_opportunity_params
- return nil unless params[:article][:job_opportunity].present?
+ return nil if params[:article][:job_opportunity].blank?
params[:article].require(:job_opportunity).permit(
:remoteness, :location_given, :location_city, :location_postal_code,
@@ -214,7 +214,7 @@ class ArticlesController < ApplicationController
redirect_to @article.current_state_path, notice: "Article was successfully created."
else
if @article.errors.to_h[:body_markdown] == "has already been taken"
- @article = current_user.articles.find_by_body_markdown(@article.body_markdown)
+ @article = current_user.articles.find_by(body_markdown: @article.body_markdown)
redirect_to @article.current_state_path
return
end
diff --git a/app/controllers/badges_controller.rb b/app/controllers/badges_controller.rb
index 5cfe9a000..4f6afb2e6 100644
--- a/app/controllers/badges_controller.rb
+++ b/app/controllers/badges_controller.rb
@@ -3,7 +3,7 @@ class BadgesController < ApplicationController
# No authorization required for entirely public controller
def show
- @badge = Badge.find_by_slug(params[:slug]) || not_found
+ @badge = Badge.find_by(slug: params[:slug]) || not_found
set_surrogate_key_header "badges-show-action"
end
end
diff --git a/app/controllers/chat_channels_controller.rb b/app/controllers/chat_channels_controller.rb
index e0c306826..b2a62ddff 100644
--- a/app/controllers/chat_channels_controller.rb
+++ b/app/controllers/chat_channels_controller.rb
@@ -17,7 +17,7 @@ class ChatChannelsController < ApplicationController
end
def show
- @chat_channel = ChatChannel.find_by_id(params[:id]) || not_found
+ @chat_channel = ChatChannel.find_by(id: params[:id]) || not_found
authorize @chat_channel
add_context(chat_channel_id: @chat_channel.id)
end
@@ -54,7 +54,7 @@ class ChatChannelsController < ApplicationController
authorize @chat_channel
add_context(chat_channel_id: @chat_channel.id)
membership = @chat_channel.chat_channel_memberships.where(user_id: current_user.id).first
- membership.update(last_opened_at: 1.seconds.from_now, has_unopened_messages: false)
+ membership.update(last_opened_at: 1.second.from_now, has_unopened_messages: false)
@chat_channel.index!
render json: { status: "success", channel: params[:id] }, status: 200
end
@@ -66,7 +66,7 @@ class ChatChannelsController < ApplicationController
command = chat_channel_params[:command].split
case command[0]
when "/ban"
- banned_user = User.find_by_username(command[1])
+ banned_user = User.find_by(username: command[1])
if banned_user
banned_user.add_role :banned
banned_user.messages.each(&:destroy!)
@@ -78,7 +78,7 @@ class ChatChannelsController < ApplicationController
render json: { status: "error", message: "username not found" }, status: 400
end
when "/unban"
- banned_user = User.find_by_username(command[1])
+ banned_user = User.find_by(username: command[1])
if banned_user
banned_user.remove_role :banned
render json: { status: "success", message: "unbanned!" }, status: 200
@@ -153,7 +153,7 @@ class ChatChannelsController < ApplicationController
else
params[:slug]
end
- @active_channel = ChatChannel.find_by_slug(slug)
+ @active_channel = ChatChannel.find_by(slug: slug)
@active_channel.current_user = current_user if @active_channel
end
generate_github_token
diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb
index cc1283dbf..3fe4a15b0 100644
--- a/app/controllers/comments_controller.rb
+++ b/app/controllers/comments_controller.rb
@@ -10,19 +10,19 @@ class CommentsController < ApplicationController
skip_authorization
@on_comments_page = true
@comment = Comment.new
- @podcast = Podcast.find_by_slug(params[:username])
+ @podcast = Podcast.find_by(slug: params[:username])
@root_comment = Comment.find(params[:id_code].to_i(26)) if params[:id_code].present?
if @podcast
@user = @podcast
- (@commentable = @user.podcast_episodes.find_by_slug(params[:slug])) || not_found
+ (@commentable = @user.podcast_episodes.find_by(slug: params[:slug])) || not_found
else
- @user = User.find_by_username(params[:username]) ||
- Organization.find_by_slug(params[:username]) ||
+ @user = User.find_by(username: params[:username]) ||
+ Organization.find_by(slug: params[:username]) ||
not_found
@commentable = @root_comment&.commentable ||
- @user.articles.find_by_slug(params[:slug]) ||
+ @user.articles.find_by(slug: params[:slug]) ||
not_found
@article = @commentable
not_found unless @commentable.published
diff --git a/app/controllers/dashboards_controller.rb b/app/controllers/dashboards_controller.rb
index a15e8420a..ff8b4bc19 100644
--- a/app/controllers/dashboards_controller.rb
+++ b/app/controllers/dashboards_controller.rb
@@ -5,7 +5,7 @@ class DashboardsController < ApplicationController
def show
@user = if params[:username] && current_user.any_admin?
- User.find_by_username(params[:username])
+ User.find_by(username: params[:username])
else
current_user
end
@@ -34,7 +34,7 @@ class DashboardsController < ApplicationController
def pro
user_or_org = if params[:org_id]
- org = Organization.find_by_id(params[:org_id])
+ org = Organization.find_by(id: params[:org_id])
authorize org, :pro_org_user?
org
else
diff --git a/app/controllers/giveaways_controller.rb b/app/controllers/giveaways_controller.rb
index cdf424864..4e169f1c5 100644
--- a/app/controllers/giveaways_controller.rb
+++ b/app/controllers/giveaways_controller.rb
@@ -86,19 +86,19 @@ class GiveawaysController < ApplicationController
end
def confirm_presence
- unless user_params[:shipping_name].present?
+ if user_params[:shipping_name].blank?
@errors << "You need a shipping name"
@invalid_form = true
end
- unless user_params[:shipping_address].present?
+ if user_params[:shipping_address].blank?
@errors << "You need a shipping address"
@invalid_form = true
end
- unless user_params[:shipping_city].present?
+ if user_params[:shipping_city].blank?
@errors << "You need a shipping city"
@invalid_form = true
end
- unless user_params[:shipping_country].present?
+ if user_params[:shipping_country].blank?
@errors << "You need a shipping country"
@invalid_form = true
end
diff --git a/app/controllers/internal/users_controller.rb b/app/controllers/internal/users_controller.rb
index 5570ef4d9..b0b0541ae 100644
--- a/app/controllers/internal/users_controller.rb
+++ b/app/controllers/internal/users_controller.rb
@@ -12,7 +12,7 @@ class Internal::UsersController < Internal::ApplicationController
else
User.order("created_at DESC").page(params[:page]).per(50)
end
- return unless params[:search].present?
+ return if params[:search].blank?
@users = @users.where('users.name ILIKE :search OR
users.username ILIKE :search OR
@@ -72,11 +72,11 @@ class Internal::UsersController < Internal::ApplicationController
def make_matches
return if @new_mentee.blank? && @new_mentor.blank?
- if !@new_mentee.blank?
+ if @new_mentee.present?
mentee = User.find(@new_mentee)
MentorRelationship.new(mentee_id: mentee.id, mentor_id: @user.id).save!
end
- return unless !@new_mentor.blank?
+ return if @new_mentor.blank?
mentor = User.find(@new_mentor)
MentorRelationship.new(mentee_id: @user.id, mentor_id: mentor.id).save!
diff --git a/app/controllers/moderations_controller.rb b/app/controllers/moderations_controller.rb
index d6e4e0146..0e154c49d 100644
--- a/app/controllers/moderations_controller.rb
+++ b/app/controllers/moderations_controller.rb
@@ -19,7 +19,7 @@ class ModerationsController < ApplicationController
def article
authorize(User, :moderation_routes?)
- @moderatable = Article.find_by_slug(params[:slug])
+ @moderatable = Article.find_by(slug: params[:slug])
render template: "moderations/mod"
end
diff --git a/app/controllers/notifications_controller.rb b/app/controllers/notifications_controller.rb
index 3b9434cbb..562929473 100644
--- a/app/controllers/notifications_controller.rb
+++ b/app/controllers/notifications_controller.rb
@@ -32,7 +32,7 @@ class NotificationsController < ApplicationController
def user_to_view
if params[:username] && current_user.admin?
- User.find_by_username(params[:username])
+ User.find_by(username: params[:username])
else
current_user
end
diff --git a/app/controllers/organizations_controller.rb b/app/controllers/organizations_controller.rb
index bbd938614..2016c5d89 100644
--- a/app/controllers/organizations_controller.rb
+++ b/app/controllers/organizations_controller.rb
@@ -1,5 +1,4 @@
class OrganizationsController < ApplicationController
- before_action :authenticate_user!, except: [:show]
after_action :verify_authorized
def create
diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rb
index 7a8cf579d..2bb672576 100644
--- a/app/controllers/pages_controller.rb
+++ b/app/controllers/pages_controller.rb
@@ -1,6 +1,6 @@
class PagesController < ApplicationController
# No authorization required for entirely public controller
- before_action :set_cache_control_headers, only: %i[rlyweb now events membership survey badge shecoded]
+ before_action :set_cache_control_headers, only: %i[rlyweb now membership survey badge shecoded]
def now
set_surrogate_key_header "now_page"
@@ -32,7 +32,7 @@ class PagesController < ApplicationController
end
def report_abuse
- reported_url = params[:reported_url] || params[:url] || request.referrer
+ reported_url = params[:reported_url] || params[:url] || request.referer
@feedback_message = FeedbackMessage.new(
reported_url: reported_url&.chomp("?i=i"),
)
@@ -54,7 +54,7 @@ class PagesController < ApplicationController
end
def live
- @active_channel = ChatChannel.find_by_channel_name("Workshop")
+ @active_channel = ChatChannel.find_by(channel_name: "Workshop")
@chat_channels = [@active_channel].to_json(
only: %i[channel_name channel_type last_message_at slug status id],
)
diff --git a/app/controllers/podcast_episodes_controller.rb b/app/controllers/podcast_episodes_controller.rb
index 5623138d6..470ca7321 100644
--- a/app/controllers/podcast_episodes_controller.rb
+++ b/app/controllers/podcast_episodes_controller.rb
@@ -6,7 +6,7 @@ class PodcastEpisodesController < ApplicationController
@podcast_index = true
@podcasts = Podcast.order("title asc")
@podcast_episodes = PodcastEpisode.order("published_at desc").first(20)
- unless params[:q].present?
+ if params[:q].blank?
set_surrogate_key_header("podcast_episodes_all " + params[:q].to_s,
@podcast_episodes.map { |e| e["record_key"] })
end
diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb
index 4f504d017..d572175d3 100644
--- a/app/controllers/stories_controller.rb
+++ b/app/controllers/stories_controller.rb
@@ -1,5 +1,5 @@
class StoriesController < ApplicationController
- before_action :authenticate_user!, except: %i[index search show feed new]
+ before_action :authenticate_user!, except: %i[index search show]
before_action :set_cache_control_headers, only: %i[index search show]
def index
@@ -20,19 +20,19 @@ class StoriesController < ApplicationController
def show
@story_show = true
add_param_context(:username, :slug)
- if (@article = Article.find_by_path("/#{params[:username].downcase}/#{params[:slug]}")&.decorate)
+ if (@article = Article.find_by(path: "/#{params[:username].downcase}/#{params[:slug]}")&.decorate)
handle_article_show
- elsif (@article = Article.find_by_slug(params[:slug])&.decorate)
+ elsif (@article = Article.find_by(slug: params[:slug])&.decorate)
handle_possible_redirect
else
- @podcast = Podcast.find_by_slug(params[:username]) || not_found
- @episode = PodcastEpisode.find_by_slug(params[:slug]) || not_found
+ @podcast = Podcast.find_by(slug: params[:username]) || not_found
+ @episode = PodcastEpisode.find_by(slug: params[:slug]) || not_found
handle_podcast_show
end
end
def warm_comments
- @article = Article.find_by_path("/#{params[:username].downcase}/#{params[:slug]}")&.decorate || not_found
+ @article = Article.find_by(path: "/#{params[:username].downcase}/#{params[:slug]}")&.decorate || not_found
@warm_only = true
assign_article_show_variables
render partial: "articles/full_comment_area"
@@ -66,8 +66,8 @@ class StoriesController < ApplicationController
end
def handle_user_or_organization_or_podcast_index
- @podcast = Podcast.find_by_slug(params[:username].downcase)
- @organization = Organization.find_by_slug(params[:username].downcase)
+ @podcast = Podcast.find_by(slug: params[:username].downcase)
+ @organization = Organization.find_by(slug: params[:username].downcase)
if @podcast
handle_podcast_index
elsif @organization
@@ -80,7 +80,7 @@ class StoriesController < ApplicationController
def handle_tag_index
@tag = params[:tag].downcase
@page = (params[:page] || 1).to_i
- @tag_model = Tag.find_by_name(@tag) || not_found
+ @tag_model = Tag.find_by(name: @tag) || not_found
@moderators = User.with_role(:tag_moderator, @tag_model)
add_param_context(:tag, :page)
if @tag_model.alias_for.present?
@@ -157,7 +157,7 @@ class StoriesController < ApplicationController
end
def handle_user_index
- @user = User.find_by_username(params[:username].tr("@", "").downcase)
+ @user = User.find_by(username: params[:username].tr("@", "").downcase)
unless @user
redirect_to_changed_username_profile
return
@@ -223,7 +223,7 @@ class StoriesController < ApplicationController
end
def assign_second_and_third_user
- return unless @article.second_user_id.present?
+ return if @article.second_user_id.blank?
@second_user = User.find(@article.second_user_id)
@third_user = User.find(@article.third_user_id) if @article.third_user_id.present?
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 09f60db28..a2bee18e5 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -90,7 +90,7 @@ class UsersController < ApplicationController
def join_org
authorize User
- if (@organization = Organization.find_by_secret(params[:org_secret]))
+ if (@organization = Organization.find_by(secret: params[:org_secret]))
current_user.update(organization_id: @organization.id)
redirect_to "/settings/organization",
notice: "You have joined the #{@organization.name} organization."
@@ -156,7 +156,7 @@ class UsersController < ApplicationController
stripe_code = current_user.stripe_id_code
return if stripe_code == "special"
- @customer = Stripe::Customer.retrieve(stripe_code) unless stripe_code.blank?
+ @customer = Stripe::Customer.retrieve(stripe_code) if stripe_code.present?
when "membership"
if current_user.monthly_dues.zero?
redirect_to "/membership"
diff --git a/app/controllers/video_states_controller.rb b/app/controllers/video_states_controller.rb
index c083198ba..4949b4410 100644
--- a/app/controllers/video_states_controller.rb
+++ b/app/controllers/video_states_controller.rb
@@ -17,14 +17,14 @@ class VideoStatesController < ApplicationController
end
request_json = JSON.parse(request.raw_post, symbolize_names: true)
message_json = JSON.parse(request_json[:Message], symbolize_names: true)
- @article = Article.find_by_video_code(message_json[:input][:key])
+ @article = Article.find_by(video_code: message_json[:input][:key])
@article.update(video_state: "COMPLETED") # Only is called on completion
NotifyMailer.video_upload_complete_email(@article).deliver
render json: { message: "Video state updated" }
end
def valid_user
- user = User.find_by_secret(params[:key])
+ user = User.find_by(secret: params[:key])
user = nil unless user.has_role?(:super_admin)
user
end
diff --git a/app/facades/dashboard/pro.rb b/app/facades/dashboard/pro.rb
index 50054a74a..2d693ffe8 100644
--- a/app/facades/dashboard/pro.rb
+++ b/app/facades/dashboard/pro.rb
@@ -28,7 +28,7 @@ module Dashboard
end
def last_month_reactions_count
- Reaction.where(reactable_id: user_or_org_article_ids, reactable_type: "Article").where("created_at > ? AND created_at < ?", 2.months.ago, 1.months.ago).size
+ Reaction.where(reactable_id: user_or_org_article_ids, reactable_type: "Article").where("created_at > ? AND created_at < ?", 2.months.ago, 1.month.ago).size
end
def this_week_comments
@@ -48,7 +48,7 @@ module Dashboard
end
def last_month_comments_count
- Comment.where(commentable_id: user_or_org_article_ids, commentable_type: "Article").where("created_at > ? AND created_at < ?", 2.months.ago, 1.months.ago).size
+ Comment.where(commentable_id: user_or_org_article_ids, commentable_type: "Article").where("created_at > ? AND created_at < ?", 2.months.ago, 1.month.ago).size
end
def this_week_followers_count
@@ -64,7 +64,7 @@ module Dashboard
end
def last_month_followers_count
- Follow.where(followable_id: user_or_org.id, followable_type: user_or_org.class.name).where("created_at > ? AND created_at < ?", 2.months.ago, 1.months.ago).size
+ Follow.where(followable_id: user_or_org.id, followable_type: user_or_org.class.name).where("created_at > ? AND created_at < ?", 2.months.ago, 1.month.ago).size
end
def reactors
diff --git a/app/fields/carrierwave_field.rb b/app/fields/carrierwave_field.rb
index 7e22aa54e..ec459213b 100644
--- a/app/fields/carrierwave_field.rb
+++ b/app/fields/carrierwave_field.rb
@@ -1,9 +1,7 @@
require "administrate/field/base"
class CarrierwaveField < Administrate::Field::Base
- def url
- data.url
- end
+ delegate :url, to: :data
def to_s
data
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 44b9ac979..24f5818e8 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -139,7 +139,7 @@ module ApplicationHelper
def tag_colors(tag)
Rails.cache.fetch("view-helper-#{tag}/tag_colors", expires_in: 5.hours) do
- if (found_tag = Tag.select(%i[bg_color_hex text_color_hex]).find_by_name(tag))
+ if (found_tag = Tag.select(%i[bg_color_hex text_color_hex]).find_by(name: tag))
{ background: found_tag.bg_color_hex, color: found_tag.text_color_hex }
else
{ background: "#d6d9e0", color: "#606570" }
diff --git a/app/labor/badge_rewarder.rb b/app/labor/badge_rewarder.rb
index 8a5f85582..08aefd580 100644
--- a/app/labor/badge_rewarder.rb
+++ b/app/labor/badge_rewarder.rb
@@ -4,8 +4,8 @@ module BadgeRewarder
def self.award_yearly_club_badges
(1..3).each do |i|
message = "Happy DEV birthday! Can you believe it's been #{i} #{'year'.pluralize(i)} already?!"
- badge = Badge.find_by_slug("#{YEARS[i]}-year-club")
- User.where("created_at < ? AND created_at > ?", i.year.ago, i.year.ago - 2.day).find_each do |user|
+ badge = Badge.find_by(slug: "#{YEARS[i]}-year-club")
+ User.where("created_at < ? AND created_at > ?", i.year.ago, i.year.ago - 2.days).find_each do |user|
achievement = BadgeAchievement.create(
user_id: user.id,
badge_id: badge.id,
@@ -21,7 +21,7 @@ module BadgeRewarder
message = "You're DEV famous! [This is the comment](https://dev.to#{comment.path}) for which you are being recognized. 😄"
achievement = BadgeAchievement.create(
user_id: comment.user_id,
- badge_id: Badge.find_by_slug("beloved-comment")&.id || 3,
+ badge_id: Badge.find_by(slug: "beloved-comment")&.id || 3,
rewarding_context_message_markdown: message,
)
comment.user.save if achievement.valid?
@@ -43,7 +43,7 @@ module BadgeRewarder
def self.award_contributor_badges_from_github(since = 1.day.ago, message_markdown = "Thank you so much for your contributions!")
client = Octokit::Client.new
- badge = Badge.find_by_slug("dev-contributor")
+ badge = Badge.find_by(slug: "dev-contributor")
["thepracticaldev/dev.to", "thepracticaldev/DEV-ios"].each do |repo|
commits = client.commits repo, since: since.iso8601
authors_uids = commits.map { |c| c.author.id }
@@ -75,7 +75,7 @@ module BadgeRewarder
User.where(username: usernames).find_each do |user|
BadgeAchievement.create(
user_id: user.id,
- badge_id: Badge.find_by_slug(slug).id,
+ badge_id: Badge.find_by(slug: slug).id,
rewarding_context_message_markdown: message_markdown,
)
user.save
diff --git a/app/labor/emoji_converter.rb b/app/labor/emoji_converter.rb
index 31efe71d9..bf093da3d 100644
--- a/app/labor/emoji_converter.rb
+++ b/app/labor/emoji_converter.rb
@@ -11,7 +11,7 @@ class EmojiConverter
def convert
html.gsub!(/:([\w+-]+):/) do |match|
- emoji = Emoji.find_by_alias(Regexp.last_match(1))
+ emoji = Emoji.find_by_alias(Regexp.last_match(1)) # rubocop:disable Rails/DynamicFindBy
emoji.present? ? emoji.raw : match
end
html
diff --git a/app/labor/flare_tag.rb b/app/labor/flare_tag.rb
index 911f8aaec..32fc43496 100644
--- a/app/labor/flare_tag.rb
+++ b/app/labor/flare_tag.rb
@@ -19,7 +19,7 @@ class FlareTag
def tag
@tag ||= Rails.cache.fetch("article_flare_tag-#{article.id}-#{article.updated_at}", expires_in: 12.hours) do
flare = FLARES.detect { |f| article.cached_tag_list_array.include?(f) }
- flare && flare != except_tag ? Tag.select(%i[name bg_color_hex text_color_hex]).find_by_name(flare) : nil
+ flare && flare != except_tag ? Tag.select(%i[name bg_color_hex text_color_hex]).find_by(name: flare) : nil
end
end
diff --git a/app/labor/markdown_parser.rb b/app/labor/markdown_parser.rb
index aab4e41f8..b112cd2f4 100644
--- a/app/labor/markdown_parser.rb
+++ b/app/labor/markdown_parser.rb
@@ -59,7 +59,7 @@ class MarkdownParser
end
def tags_used
- return [] unless @content.present?
+ return [] if @content.blank?
cleaned_parsed = escape_liquid_tags_in_codeblock(@content)
tags = []
@@ -149,7 +149,7 @@ class MarkdownParser
def user_link_if_exists(mention)
username = mention.delete("@").downcase
- if User.find_by_username(username)
+ if User.find_by(username: username)
<<~HTML
HTML
diff --git a/app/lib/acts_as_taggable_on/tag_parser.rb b/app/lib/acts_as_taggable_on/tag_parser.rb
index 9034c58e5..85cd0881f 100644
--- a/app/lib/acts_as_taggable_on/tag_parser.rb
+++ b/app/lib/acts_as_taggable_on/tag_parser.rb
@@ -31,8 +31,8 @@ module ActsAsTaggableOn
def find_tag_alias(tag)
# "&." is "Safe Navigation"; ensure not called on nil
- alias_for = Tag.find_by_name(tag)&.alias_for
- alias_for if alias_for.present?
+ alias_for = Tag.find_by(name: tag)&.alias_for
+ alias_for.presence
end
end
end
diff --git a/app/liquid_tags/codepen_tag.rb b/app/liquid_tags/codepen_tag.rb
index ed8f73972..f0cedacb2 100644
--- a/app/liquid_tags/codepen_tag.rb
+++ b/app/liquid_tags/codepen_tag.rb
@@ -35,11 +35,7 @@ class CodepenTag < LiquidTagBase
option = validated_options.join("&")
- if option.blank?
- "default-tab=result"
- else
- option
- end
+ option.presence || "default-tab=result"
end
def parse_link(link)
diff --git a/app/liquid_tags/dev_comment_tag.rb b/app/liquid_tags/dev_comment_tag.rb
index 0adc190e5..fe66103da 100644
--- a/app/liquid_tags/dev_comment_tag.rb
+++ b/app/liquid_tags/dev_comment_tag.rb
@@ -36,7 +36,7 @@ class DevCommentTag < LiquidTagBase
+image_tag("/assets/twitter-logo.svg", class: "icon-img", alt: "twitter") + \
""
end
- return unless @comment.user.github_username.present?
+ return if @comment.user.github_username.blank?
result + "" \
+image_tag("/assets/github-logo.svg", class: "icon-img", alt: "github") + \
@@ -52,7 +52,7 @@ class DevCommentTag < LiquidTagBase
end
def find_comment
- comment = Comment.find_by_id(@id_code.to_i(26))
+ comment = Comment.find_by(id: @id_code.to_i(26))
raise_error unless comment
comment
end
diff --git a/app/liquid_tags/link_tag.rb b/app/liquid_tags/link_tag.rb
index 3453ed5ba..2136fce72 100644
--- a/app/liquid_tags/link_tag.rb
+++ b/app/liquid_tags/link_tag.rb
@@ -50,14 +50,14 @@ class LinkTag < LiquidTagBase
end
def find_article_by_user(hash)
- user = User.find_by_username(hash[:username])
+ user = User.find_by(username: hash[:username])
return unless user
user.articles.where(slug: hash[:slug])&.first
end
def find_article_by_org(hash)
- org = Organization.find_by_slug(hash[:username])
+ org = Organization.find_by(slug: hash[:username])
return unless org
org.articles.where(slug: hash[:slug])&.first
diff --git a/app/liquid_tags/podcast_tag.rb b/app/liquid_tags/podcast_tag.rb
index aefd579de..304fc158d 100644
--- a/app/liquid_tags/podcast_tag.rb
+++ b/app/liquid_tags/podcast_tag.rb
@@ -150,8 +150,8 @@ class PodcastTag < LiquidTagBase
def fetch_podcast(link)
cleaned_link = parse_link(link)
podcast_slug, episode_slug = cleaned_link.split("/").last(2)
- target_podcast = Podcast.find_by_slug(podcast_slug)
- target_episode = PodcastEpisode.find_by_slug(episode_slug)
+ target_podcast = Podcast.find_by(slug: podcast_slug)
+ target_episode = PodcastEpisode.find_by(slug: episode_slug)
raise_error unless target_podcast && target_episode
raise_error unless target_episode.podcast_id == target_podcast.id
@podcast = target_podcast
diff --git a/app/liquid_tags/tag_tag.rb b/app/liquid_tags/tag_tag.rb
index bf98c2186..99f4c8732 100644
--- a/app/liquid_tags/tag_tag.rb
+++ b/app/liquid_tags/tag_tag.rb
@@ -35,7 +35,7 @@ class TagTag < LiquidTagBase
def parse_tag_name_to_tag(input)
input_no_space = input.delete(" ")
- tag = Tag.find_by_name(input_no_space)
+ tag = Tag.find_by(name: input_no_space)
raise StandardError, "invalid tag name" if tag.nil?
tag
diff --git a/app/liquid_tags/user_tag.rb b/app/liquid_tags/user_tag.rb
index e3088f258..d4a7a8a2a 100644
--- a/app/liquid_tags/user_tag.rb
+++ b/app/liquid_tags/user_tag.rb
@@ -43,14 +43,14 @@ class UserTag < LiquidTagBase
def parse_username_to_user(input)
input_no_space = input.delete(" ")
- user = User.find_by_username(input_no_space)
+ user = User.find_by(username: input_no_space)
raise StandardError, "invalid username" if user.nil?
user
end
def twitter_link
- return unless @user.twitter_username.present?
+ return if @user.twitter_username.blank?
<<-HTML
@@ -60,7 +60,7 @@ class UserTag < LiquidTagBase
end
def github_link
- return unless @user.github_username.present?
+ return if @user.github_username.blank?
<<-HTML
@@ -70,7 +70,7 @@ class UserTag < LiquidTagBase
end
def website_link
- return unless @user.website_url.present?
+ return if @user.website_url.blank?
<<-HTML
diff --git a/app/models/article.rb b/app/models/article.rb
index 573625643..44bb9c7d8 100644
--- a/app/models/article.rb
+++ b/app/models/article.rb
@@ -10,14 +10,17 @@ class Article < ApplicationRecord
attr_accessor :publish_under_org
attr_writer :series
+ delegate :name, to: :user, prefix: true
+ delegate :username, to: :user, prefix: true
+
belongs_to :user
belongs_to :job_opportunity, optional: true
counter_culture :user
belongs_to :organization, optional: true
belongs_to :collection, optional: true
- has_many :comments, as: :commentable
+ has_many :comments, as: :commentable, inverse_of: :commentable
has_many :buffer_updates
- has_many :notifications, as: :notifiable
+ has_many :notifications, as: :notifiable, inverse_of: :notifiable
has_many :rating_votes
has_many :page_views
@@ -274,14 +277,6 @@ class Article < ApplicationRecord
user.username
end
- def user_name
- user.name
- end
-
- def user_username
- user.username
- end
-
def current_state_path
published ? "/#{username}/#{slug}" : "/#{username}/#{slug}?preview=#{password}"
end
@@ -356,7 +351,7 @@ class Article < ApplicationRecord
end
def readable_publish_date
- relevant_date = crossposted_at.present? ? crossposted_at : published_at
+ relevant_date = crossposted_at.presence || published_at
if relevant_date && relevant_date.year == Time.current.year
relevant_date&.strftime("%b %e")
else
@@ -509,7 +504,7 @@ class Article < ApplicationRecord
end
def create_password
- return unless password.blank?
+ return if password.present?
self.password = SecureRandom.hex(60)
end
diff --git a/app/models/broadcast.rb b/app/models/broadcast.rb
index 10465de0e..ee2d7952a 100644
--- a/app/models/broadcast.rb
+++ b/app/models/broadcast.rb
@@ -1,5 +1,5 @@
class Broadcast < ApplicationRecord
- has_many :notifications, as: :notifiable
+ has_many :notifications, as: :notifiable, inverse_of: :notifiable
validates :title, :type_of, :processed_html, presence: true
validates :type_of, inclusion: { in: %w[Announcement Onboarding] }
diff --git a/app/models/chat_channel.rb b/app/models/chat_channel.rb
index 26d0fe70d..ab90d552b 100644
--- a/app/models/chat_channel.rb
+++ b/app/models/chat_channel.rb
@@ -6,10 +6,10 @@ class ChatChannel < ApplicationRecord
has_many :chat_channel_memberships, dependent: :destroy
has_many :users, through: :chat_channel_memberships
- has_many :active_memberships, -> { where status: "active" }, class_name: "ChatChannelMembership"
- has_many :pending_memberships, -> { where status: "pending" }, class_name: "ChatChannelMembership"
- has_many :rejected_memberships, -> { where status: "rejected" }, class_name: "ChatChannelMembership"
- has_many :mod_memberships, -> { where role: "mod" }, class_name: "ChatChannelMembership"
+ has_many :active_memberships, -> { where status: "active" }, class_name: "ChatChannelMembership", inverse_of: :chat_channel
+ has_many :pending_memberships, -> { where status: "pending" }, class_name: "ChatChannelMembership", inverse_of: :chat_channel
+ has_many :rejected_memberships, -> { where status: "rejected" }, class_name: "ChatChannelMembership", inverse_of: :chat_channel
+ has_many :mod_memberships, -> { where role: "mod" }, class_name: "ChatChannelMembership", inverse_of: :chat_channel
has_many :active_users, through: :active_memberships, class_name: "User", source: :user
has_many :pending_users, through: :pending_memberships, class_name: "User", source: :user
has_many :rejected_users, through: :rejected_memberships, class_name: "User", source: :user
@@ -71,7 +71,7 @@ class ChatChannel < ApplicationRecord
slug = contrived_name.to_s.downcase.tr(" ", "-").gsub(/[^\w-]/, "").tr("_", "") + "-" + rand(100_000).to_s(26)
end
- if (channel = ChatChannel.find_by_slug(slug))
+ if (channel = ChatChannel.find_by(slug: slug))
channel.status = "active"
channel.save
else
diff --git a/app/models/collection.rb b/app/models/collection.rb
index 6751fa471..0400a223c 100644
--- a/app/models/collection.rb
+++ b/app/models/collection.rb
@@ -7,7 +7,6 @@ class Collection < ApplicationRecord
validates :slug, uniqueness: { scope: :user_id }
def self.find_series(slug, user)
- series = Collection.where(slug: slug, user: user).first
- series || Collection.create(slug: slug, user: user)
+ Collection.find_or_create_by(slug: slug, user: user)
end
end
diff --git a/app/models/comment.rb b/app/models/comment.rb
index 029164023..e1cf10ce8 100644
--- a/app/models/comment.rb
+++ b/app/models/comment.rb
@@ -6,7 +6,7 @@ class Comment < ApplicationRecord
counter_culture :commentable
belongs_to :user
counter_culture :user
- has_many :mentions, as: :mentionable, dependent: :destroy
+ has_many :mentions, as: :mentionable, inverse_of: :mentionable, dependent: :destroy
validates :body_markdown, presence: true, length: { in: 1..25_000 },
uniqueness: { scope: %i[user_id
diff --git a/app/models/concerns/reactable.rb b/app/models/concerns/reactable.rb
index d499f8362..96e2fa87a 100644
--- a/app/models/concerns/reactable.rb
+++ b/app/models/concerns/reactable.rb
@@ -2,7 +2,7 @@ module Reactable
extend ActiveSupport::Concern
included do
- has_many :reactions, as: :reactable, dependent: :destroy
+ has_many :reactions, as: :reactable, inverse_of: :reactable, dependent: :destroy
end
def sync_reactions_count
diff --git a/app/models/feedback_message.rb b/app/models/feedback_message.rb
index 40869d150..de6f21afc 100644
--- a/app/models/feedback_message.rb
+++ b/app/models/feedback_message.rb
@@ -1,12 +1,12 @@
class FeedbackMessage < ApplicationRecord
- belongs_to :offender, foreign_key: "offender_id", class_name: "User", optional: true
- belongs_to :reviewer, foreign_key: "reviewer_id", class_name: "User", optional: true
- belongs_to :reporter, foreign_key: "reporter_id", class_name: "User", optional: true
- belongs_to :affected, foreign_key: "affected_id", class_name: "User", optional: true
- has_many :notes, as: :noteable, dependent: :destroy
+ belongs_to :offender, foreign_key: "offender_id", class_name: "User", optional: true, inverse_of: :feedback_messages
+ belongs_to :reviewer, foreign_key: "reviewer_id", class_name: "User", optional: true, inverse_of: :feedback_messages
+ belongs_to :reporter, foreign_key: "reporter_id", class_name: "User", optional: true, inverse_of: :feedback_messages
+ belongs_to :affected, foreign_key: "affected_id", class_name: "User", optional: true, inverse_of: :feedback_messages
+ has_many :notes, as: :noteable, inverse_of: :noteable, dependent: :destroy
- validates_presence_of :feedback_type, :message
- validates_presence_of :reported_url, :category, if: :abuse_report?
+ validates :feedback_type, :message, presence: true
+ validates :reported_url, :category, presence: { if: :abuse_report? }
validates :category,
inclusion: {
in: ["spam", "other", "rude or vulgar", "harassment", "bug"]
@@ -21,6 +21,6 @@ class FeedbackMessage < ApplicationRecord
end
def capitalize_status
- self.status = status.capitalize unless status.blank?
+ self.status = status.capitalize if status.present?
end
end
diff --git a/app/models/follow.rb b/app/models/follow.rb
index 4cdb39518..0a62d797a 100644
--- a/app/models/follow.rb
+++ b/app/models/follow.rb
@@ -52,8 +52,7 @@ class Follow < ApplicationRecord
return unless followable_type == "User" && followable.following?(follower)
channel = follower.chat_channels.
- where("slug LIKE ? OR slug like ?", "%/#{followable.username}%", "%#{followable.username}/%").
- first
+ find_by("slug LIKE ? OR slug like ?", "%/#{followable.username}%", "%#{followable.username}/%")
channel&.update(status: "inactive")
end
end
diff --git a/app/models/github_issue.rb b/app/models/github_issue.rb
index d08d12460..a8e19c91b 100644
--- a/app/models/github_issue.rb
+++ b/app/models/github_issue.rb
@@ -3,7 +3,7 @@ class GithubIssue < ApplicationRecord
validates :category, inclusion: { in: %w[issue issue_comment] }
def self.find_or_fetch(url)
- find_by_url(url) || fetch(url)
+ find_by(url: url) || fetch(url)
end
def self.fetch(url)
diff --git a/app/models/github_repo.rb b/app/models/github_repo.rb
index 5be2275b8..e255ee417 100644
--- a/app/models/github_repo.rb
+++ b/app/models/github_repo.rb
@@ -19,7 +19,7 @@ class GithubRepo < ApplicationRecord
def self.update_to_latest
where("updated_at < ?", 1.day.ago).find_each do |repo|
- user_token = User.find_by_id(repo.user_id).identities.where(provider: "github").last.token
+ user_token = User.find_by(id: repo.user_id).identities.where(provider: "github").last.token
client = Octokit::Client.new(access_token: user_token)
begin
fetched_repo = client.repo(repo.info_hash[:full_name])
diff --git a/app/models/identity.rb b/app/models/identity.rb
index 404c5666b..98c5929ef 100644
--- a/app/models/identity.rb
+++ b/app/models/identity.rb
@@ -1,9 +1,9 @@
class Identity < ApplicationRecord
belongs_to :user
- validates_presence_of :uid, :provider
- validates_uniqueness_of :uid, scope: :provider
- validates_uniqueness_of :provider, scope: :uid
- validates_uniqueness_of :user_id, scope: :provider
+ validates :uid, :provider, presence: true
+ validates :uid, uniqueness: { scope: :provider }
+ validates :provider, uniqueness: { scope: :uid }
+ validates :user_id, uniqueness: { scope: :provider }
validates :provider, inclusion: { in: %w[github twitter] }
serialize :auth_data_dump
diff --git a/app/models/mention.rb b/app/models/mention.rb
index a1cc4f614..e2af70c55 100644
--- a/app/models/mention.rb
+++ b/app/models/mention.rb
@@ -20,7 +20,7 @@ class Mention < ApplicationRecord
mentions = []
doc.css(".comment-mentioned-user").each do |link|
username = link.text.delete("@").downcase
- if (user = User.find_by_username(username))
+ if (user = User.find_by(username: username))
usernames << username
mentions << create_mention(user)
end
@@ -35,7 +35,7 @@ class Mention < ApplicationRecord
def delete_removed_mentions(usernames)
user_ids = User.where(username: usernames).pluck(:id)
mentions = @notifiable.mentions.where.not(user_id: user_ids).destroy_all
- Notification.remove_each(mentions) unless mentions.blank?
+ Notification.remove_each(mentions) if mentions.present?
end
def create_mention(user)
diff --git a/app/models/mentor_relationship.rb b/app/models/mentor_relationship.rb
index 2a03cae13..7e664f984 100644
--- a/app/models/mentor_relationship.rb
+++ b/app/models/mentor_relationship.rb
@@ -4,7 +4,7 @@ class MentorRelationship < ApplicationRecord
validates :mentor, presence: true
validates :mentee, presence: true
validate :check_for_same_user
- validates_uniqueness_of :mentor_id, scope: :mentee_id
+ validates :mentor_id, uniqueness: { scope: :mentee_id }
after_create :mutual_follow
after_create :send_emails
diff --git a/app/models/message.rb b/app/models/message.rb
index 012ca75c4..800f2148b 100644
--- a/app/models/message.rb
+++ b/app/models/message.rb
@@ -101,7 +101,7 @@ class Message < ApplicationRecord
end
def rich_link_article(link)
- Article.find_by_slug(link["href"].split("/")[4].split("?")[0]) if link["href"].include?("//#{ApplicationConfig['APP_DOMAIN']}/") && link["href"].split("/")[4]
+ Article.find_by(slug: link["href"].split("/")[4].split("?")[0]) if link["href"].include?("//#{ApplicationConfig['APP_DOMAIN']}/") && link["href"].split("/")[4]
end
def send_email_if_appropriate
diff --git a/app/models/organization.rb b/app/models/organization.rb
index c5535f79a..e91ece2ab 100644
--- a/app/models/organization.rb
+++ b/app/models/organization.rb
@@ -113,6 +113,6 @@ class Organization < ApplicationRecord
handle_asynchronously :bust_cache
def unique_slug_including_users
- errors.add(:slug, "is taken.") if User.find_by_username(slug)
+ errors.add(:slug, "is taken.") if User.find_by(username: slug)
end
end
diff --git a/app/models/podcast_episode.rb b/app/models/podcast_episode.rb
index 0194fdb05..eea82731c 100644
--- a/app/models/podcast_episode.rb
+++ b/app/models/podcast_episode.rb
@@ -3,8 +3,12 @@ class PodcastEpisode < ApplicationRecord
acts_as_taggable
+ delegate :slug, to: :podcast, prefix: true
+ delegate :image_url, to: :podcast, prefix: true
+ delegate :title, to: :podcast, prefix: true
+
belongs_to :podcast
- has_many :comments, as: :commentable
+ has_many :comments, as: :commentable, inverse_of: :commentable
mount_uploader :image, ProfileImageUploader
mount_uploader :social_image, ProfileImageUploader
@@ -68,18 +72,6 @@ class PodcastEpisode < ApplicationRecord
"/#{podcast.slug}/#{slug}"
end
- def podcast_slug
- podcast.slug
- end
-
- def podcast_image_url
- podcast.image_url
- end
-
- def podcast_title
- podcast.title
- end
-
def published_at_int
published_at.to_i
end
@@ -158,7 +150,7 @@ class PodcastEpisode < ApplicationRecord
private
def prefix_all_images
- return unless body.present?
+ return if body.blank?
self.processed_html = body.
gsub("\r\n
\r\n", "").gsub("\r\n
\r\n", "").
diff --git a/app/models/rating_vote.rb b/app/models/rating_vote.rb
index a6278bc0c..4841ae010 100644
--- a/app/models/rating_vote.rb
+++ b/app/models/rating_vote.rb
@@ -2,7 +2,7 @@ class RatingVote < ApplicationRecord
belongs_to :article
belongs_to :user
- validates_uniqueness_of :user_id, scope: :article_id
+ validates :user_id, uniqueness: { scope: :article_id }
validates :group, inclusion: { in: %w[experience_level] }
validates :rating, numericality: { greater_than: 0.0, less_than_or_equal_to: 10.0 }
validate :permissions
diff --git a/app/models/tag.rb b/app/models/tag.rb
index 4224e56f1..11476522c 100644
--- a/app/models/tag.rb
+++ b/app/models/tag.rb
@@ -77,7 +77,7 @@ class Tag < ActsAsTaggableOn::Tag
end
def validate_alias
- errors.add(:tag, "alias_for must refer to existing tag") if alias_for.present? && !Tag.find_by_name(alias_for)
+ errors.add(:tag, "alias_for must refer to existing tag") if alias_for.present? && !Tag.find_by(name: alias_for)
end
def pound_it
diff --git a/app/models/tweet.rb b/app/models/tweet.rb
index 1802efcdd..c77b15c74 100644
--- a/app/models/tweet.rb
+++ b/app/models/tweet.rb
@@ -16,7 +16,7 @@ class Tweet < ApplicationRecord
validates :full_fetched_object_serialized, presence: true
def self.find_or_fetch(twitter_id_code)
- find_by_twitter_id_code(twitter_id_code) || fetch(twitter_id_code)
+ find_by(twitter_id_code: twitter_id_code) || fetch(twitter_id_code)
end
def self.fetch(twitter_id_code)
@@ -73,7 +73,7 @@ class Tweet < ApplicationRecord
tweet = Tweet.where(twitter_id_code: tweeted.attrs[:id_str]).first_or_initialize
tweet.twitter_uid = tweeted.user.id.to_s
tweet.twitter_username = tweeted.user.screen_name.downcase
- tweet.user_id = User.find_by_twitter_username(tweeted.user.screen_name).try(:id)
+ tweet.user_id = User.find_by(twitter_username: tweeted.user.screen_name).try(:id)
tweet.favorite_count = tweeted.favorite_count
tweet.retweet_count = tweeted.retweet_count
tweet.in_reply_to_user_id_code = tweeted.attrs[:in_reply_to_user_id_str]
diff --git a/app/models/user.rb b/app/models/user.rb
index c32b358ff..cf79e0832 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -24,8 +24,8 @@ class User < ApplicationRecord
has_many :identities, dependent: :destroy
has_many :mentions, dependent: :destroy
has_many :messages, dependent: :destroy
- has_many :notes, as: :noteable
- has_many :authored_notes, as: :author, class_name: "Note"
+ has_many :notes, as: :noteable, inverse_of: :noteable
+ has_many :authored_notes, as: :author, inverse_of: :author, class_name: "Note"
has_many :notifications, dependent: :destroy
has_many :reactions, dependent: :destroy
has_many :tweets, dependent: :destroy
@@ -37,9 +37,9 @@ class User < ApplicationRecord
has_many :html_variants, dependent: :destroy
has_many :page_views
has_many :mentor_relationships_as_mentee,
- class_name: "MentorRelationship", foreign_key: "mentee_id"
+ class_name: "MentorRelationship", foreign_key: "mentee_id", inverse_of: :mentee
has_many :mentor_relationships_as_mentor,
- class_name: "MentorRelationship", foreign_key: "mentor_id"
+ class_name: "MentorRelationship", foreign_key: "mentor_id", inverse_of: :mentor
has_many :mentors,
through: :mentor_relationships_as_mentee,
source: :mentor
@@ -133,7 +133,7 @@ class User < ApplicationRecord
validate :validate_feed_url
validate :unique_including_orgs
- scope :dev_account, -> { find_by_id(ApplicationConfig["DEVTO_USER_ID"]) }
+ scope :dev_account, -> { find_by(id: ApplicationConfig["DEVTO_USER_ID"]) }
after_create :send_welcome_notification
after_save :bust_cache
@@ -205,7 +205,7 @@ class User < ApplicationRecord
end
def estimate_default_language!
- identity = identities.where(provider: "twitter").first
+ identity = identities.find_by(provider: "twitter")
if email.end_with?(".jp")
update(estimated_default_language: "ja", prefer_language_ja: true)
elsif identity
@@ -336,7 +336,7 @@ class User < ApplicationRecord
end
def unique_including_orgs
- errors.add(:username, "is taken.") if Organization.find_by_slug(username)
+ errors.add(:username, "is taken.") if Organization.find_by(slug: username)
end
def subscribe_to_mailchimp_newsletter
@@ -416,7 +416,7 @@ class User < ApplicationRecord
end
def temp_name_exists?
- User.find_by_username(temp_username) || Organization.find_by_slug(temp_username)
+ User.find_by(username: temp_username) || Organization.find_by(slug: temp_username)
end
def temp_username
@@ -480,13 +480,13 @@ class User < ApplicationRecord
end
def validate_feed_url
- return unless feed_url.present?
+ return if feed_url.blank?
errors.add(:feed_url, "is not a valid rss feed") unless RssReader.new.valid_feed_url?(feed_url)
end
def validate_mastodon_url
- return unless mastodon_url.present?
+ return if mastodon_url.blank?
uri = URI.parse(mastodon_url)
return if uri.host&.in?(Constants::ALLOWED_MASTODON_INSTANCES)
diff --git a/app/services/article_api_index_service.rb b/app/services/article_api_index_service.rb
index 0126d3f06..95e6f1a82 100644
--- a/app/services/article_api_index_service.rb
+++ b/app/services/article_api_index_service.rb
@@ -30,14 +30,14 @@ class ArticleApiIndexService
else
30
end
- if (user = User.find_by_username(username))
+ if (user = User.find_by(username: username))
user.articles.
where(published: true).
includes(:user).
order("published_at DESC").
page(page).
per(num)
- elsif (organization = Organization.find_by_slug(username))
+ elsif (organization = Organization.find_by(slug: username))
organization.articles.
where(published: true).
includes(:user).
@@ -50,7 +50,7 @@ class ArticleApiIndexService
end
def tag_articles
- if Tag.find_by_name(tag)&.requires_approval
+ if Tag.find_by(name: tag)&.requires_approval
Article.
where(published: true, approved: true).
order("featured_number DESC").
diff --git a/app/services/article_creation_service.rb b/app/services/article_creation_service.rb
index bcdd056b9..d9ce311bc 100644
--- a/app/services/article_creation_service.rb
+++ b/app/services/article_creation_service.rb
@@ -23,7 +23,7 @@ class ArticleCreationService
end
def create_job_opportunity(article)
- return unless job_opportunity_params.present?
+ return if job_opportunity_params.blank?
job_opportunity = JobOpportunity.create(job_opportunity_params)
article.job_opportunity = job_opportunity
diff --git a/app/services/authorization_service.rb b/app/services/authorization_service.rb
index f1ca39246..2faea802d 100644
--- a/app/services/authorization_service.rb
+++ b/app/services/authorization_service.rb
@@ -83,13 +83,13 @@ class AuthorizationService
signed_in_resource
elsif identity.user
identity.user
- elsif !auth.info.email.blank?
- User.find_by_email(auth.info.email)
+ elsif auth.info.email.present?
+ User.find_by(email: auth.info.email)
end
end
def set_identity(identity, user)
- return unless identity.user_id.blank?
+ return if identity.user_id.present?
identity.user = user
identity.save!
diff --git a/app/services/rss_reader.rb b/app/services/rss_reader.rb
index 59c33c199..5da1f5427 100644
--- a/app/services/rss_reader.rb
+++ b/app/services/rss_reader.rb
@@ -90,7 +90,7 @@ class RssReader
show_comments: true,
# body_markdown: assemble_body_markdown(item, user, feed, feed_source_url),
body_markdown: RssReader::Assembler.call(item, user, feed, feed_source_url),
- organization_id: user.organization_id.present? ? user.organization_id : nil
+ organization_id: user.organization_id.presence
}
article = with_timer("save_article", metadata) do
Article.create!(article_params)
diff --git a/app/services/tag_adjustment_creation_service.rb b/app/services/tag_adjustment_creation_service.rb
index 0fe55c8bf..39659aeb1 100644
--- a/app/services/tag_adjustment_creation_service.rb
+++ b/app/services/tag_adjustment_creation_service.rb
@@ -21,7 +21,7 @@ class TagAdjustmentCreationService
def creation_args
args = @tag_adjustment_params
args[:user_id] = @user.id
- args[:tag_id] = Tag.find_by_name(args[:tag_name])&.id
+ args[:tag_id] = Tag.find_by(name: args[:tag_name])&.id
args
end
end
diff --git a/app/views/api/v0/users/index.json.jbuilder b/app/views/api/v0/users/index.json.jbuilder
index b3a592765..00f629e79 100644
--- a/app/views/api/v0/users/index.json.jbuilder
+++ b/app/views/api/v0/users/index.json.jbuilder
@@ -2,7 +2,7 @@ json.array! @users.each do |user|
json.id user.id
json.name user.name
json.username user.username
- json.summary truncate(user.summary.present? ? user.summary : "Active DEV author", length: 100)
+ json.summary truncate(user.summary.presence || "Active DEV author", length: 100)
json.profile_image_url ProfileImage.new(user).get(90)
json.following false
end
diff --git a/config/environments/development.rb b/config/environments/development.rb
index 484f5b7b9..e7ebe3a1c 100644
--- a/config/environments/development.rb
+++ b/config/environments/development.rb
@@ -20,7 +20,7 @@ Rails.application.configure do
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
- 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.cache_store = :memory_store
@@ -77,7 +77,7 @@ Rails.application.configure do
domain: "localhost:3000"
}
- config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews"
+ config.action_mailer.preview_path = Rails.root.join("spec", "mailers", "previews")
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
diff --git a/config/initializers/liquid.rb b/config/initializers/liquid.rb
index 8100f6197..7f6036580 100644
--- a/config/initializers/liquid.rb
+++ b/config/initializers/liquid.rb
@@ -3,7 +3,7 @@
# Liquid gem is evoked, hence the need for the fix below.
Rails.application.config.to_prepare do
- Dir.glob(Rails.root.join("app/liquid_tags/*.rb")).sort.each do |filename|
+ Dir.glob(Rails.root.join("app", "liquid_tags", "*.rb")).sort.each do |filename|
require_dependency filename
end
end
diff --git a/config/initializers/reverse_markdown.rb b/config/initializers/reverse_markdown.rb
index 86e6500d6..d85dbe44f 100644
--- a/config/initializers/reverse_markdown.rb
+++ b/config/initializers/reverse_markdown.rb
@@ -6,7 +6,7 @@
if Rails.env.development? || Rails.env.test?
Rails.application.config.to_prepare do
- Dir.glob(Rails.root.join("app/lib/reverse_markdown/converters/*.rb")).sort.each do |filename|
+ Dir.glob(Rails.root.join("app", "lib", "reverse_markdown", "converters", "*.rb")).sort.each do |filename|
require_dependency filename
end
end
diff --git a/db/seeds.rb b/db/seeds.rb
index 48c30b549..ae5ca8d13 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,4 +1,4 @@
-p "1/9 Creating Organizations"
+Rails.logger.info "1/9 Creating Organizations"
3.times do
Organization.create!(
@@ -17,7 +17,7 @@ end
##############################################################################
-p "2/9 Creating Users"
+Rails.logger.info "2/9 Creating Users"
roles = %i[level_1_member level_2_member level_3_member level_4_member
workshop_pass]
@@ -26,7 +26,7 @@ User.clear_index!
user = User.create!(
name: name = Faker::Name.unique.name,
summary: Faker::Lorem.paragraph_by_chars(199, false),
- profile_image: File.open("#{Rails.root}/app/assets/images/#{rand(1..40)}.png"),
+ profile_image: File.open(Rails.root.join("app", "assets", "images", "#{rand(1..40)}.png")),
website_url: Faker::Internet.url,
twitter_username: Faker::Internet.username(name),
email_comment_notifications: false,
@@ -50,7 +50,7 @@ end
##############################################################################
-p "3/9 Creating Tags"
+Rails.logger.info "3/9 Creating Tags"
tags = %w[beginners career computerscience git go
java javascript linux productivity python security webdev]
@@ -66,7 +66,7 @@ end
##############################################################################
-p "4/9 Creating Articles"
+Rails.logger.info "4/9 Creating Articles"
Article.clear_index!
25.times do |i|
@@ -97,7 +97,7 @@ end
##############################################################################
-p "5/9 Creating Comments"
+Rails.logger.info "5/9 Creating Comments"
Comment.clear_index!
30.times do
@@ -112,11 +112,9 @@ end
##############################################################################
-p "6/9 Creating Podcasts"
+Rails.logger.info "6/9 Creating Podcasts"
-image_file = File.join(
- Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"
-)
+image_file = Rails.root.join("spec", "support", "fixtures", "images", "image1.jpeg")
podcast_objects = [
{
@@ -177,7 +175,7 @@ end
##############################################################################
-p "7/9 Creating Broadcasts"
+Rails.logger.info "7/9 Creating Broadcasts"
Broadcast.create!(
title: "Welcome Notification",
@@ -188,7 +186,7 @@ Broadcast.create!(
##############################################################################
-p "8/9 Creating chat_channel"
+Rails.logger.info "8/9 Creating chat_channel"
ChatChannel.clear_index!
ChatChannel.without_auto_index do
@@ -202,7 +200,7 @@ ChatChannel.without_auto_index do
end
ChatChannel.reindex!
-p "9/9 Creating html_variant"
+Rails.logger.info "9/9 Creating html_variant"
HtmlVariant.create(
name: rand(100).to_s,
diff --git a/spec/factories/badges.rb b/spec/factories/badges.rb
index ec724e41e..d84f97f1b 100644
--- a/spec/factories/badges.rb
+++ b/spec/factories/badges.rb
@@ -1,6 +1,7 @@
FactoryBot.define do
image = Rack::Test::UploadedFile.new(
- File.join(Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"), "image/jpeg"
+ Rails.root.join("spec", "support", "fixtures", "images", "image1.jpeg"),
+ "image/jpeg",
)
factory :badge do
diff --git a/spec/factories/organizations.rb b/spec/factories/organizations.rb
index 853d6a7e0..dd0123f51 100644
--- a/spec/factories/organizations.rb
+++ b/spec/factories/organizations.rb
@@ -2,7 +2,7 @@ FactoryBot.define do
factory :organization do
name { Faker::Company.name }
summary { Faker::Hipster.paragraph(1)[0..150] }
- profile_image { File.open("#{Rails.root}/app/assets/images/android-icon-36x36.png") }
+ profile_image { File.open(Rails.root.join("app", "assets", "images", "android-icon-36x36.png")) }
nav_image { Faker::Avatar.image }
url { Faker::Internet.url }
slug { "org#{rand(10_000)}" }
diff --git a/spec/factories/podcasts.rb b/spec/factories/podcasts.rb
index 09e944d2a..0f114844f 100644
--- a/spec/factories/podcasts.rb
+++ b/spec/factories/podcasts.rb
@@ -1,6 +1,7 @@
FactoryBot.define do
image = Rack::Test::UploadedFile.new(
- File.join(Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"), "image/jpeg"
+ Rails.root.join("spec", "support", "fixtures", "images", "image1.jpeg"),
+ "image/jpeg",
)
factory :podcast do
diff --git a/spec/factories/users.rb b/spec/factories/users.rb
index 18bf58d84..614c7389c 100644
--- a/spec/factories/users.rb
+++ b/spec/factories/users.rb
@@ -5,7 +5,8 @@ FactoryBot.define do
sequence(:github_username) { |n| "github#{n}" }
image = Rack::Test::UploadedFile.new(
- File.join(Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"), "image/jpeg"
+ Rails.root.join("spec", "support", "fixtures", "images", "image1.jpeg"),
+ "image/jpeg",
)
factory :user do
diff --git a/spec/features/organization/user_updates_org_settings_spec.rb b/spec/features/organization/user_updates_org_settings_spec.rb
index 99fb0279c..298927f5d 100644
--- a/spec/features/organization/user_updates_org_settings_spec.rb
+++ b/spec/features/organization/user_updates_org_settings_spec.rb
@@ -13,7 +13,8 @@ RSpec.describe "Organization setting page(/settings/organization)", type: :featu
fill_in "organization[name]", with: "Organization Name"
fill_in "organization[slug]", with: "Organization"
attach_file(
- "organization_profile_image", "#{Rails.root}/app/assets/images/android-icon-36x36.png"
+ "organization_profile_image",
+ Rails.root.join("app", "assets", "images", "android-icon-36x36.png"),
)
fill_in "Text color (hex)", with: "#ffffff"
fill_in "Background color (hex)", with: "#000000"
@@ -25,7 +26,7 @@ RSpec.describe "Organization setting page(/settings/organization)", type: :featu
end
it "remove user from organization" do
- user.update_attributes(organization_id: organization.id, org_admin: true)
+ user.update(organization_id: organization.id, org_admin: true)
user2 = create(:user, username: "newuser", organization_id: organization.id)
visit "settings/organization"
click_button("Remove from org")
diff --git a/spec/labor/emoji_converter_spec.rb b/spec/labor/emoji_converter_spec.rb
index a046614c5..70057930d 100644
--- a/spec/labor/emoji_converter_spec.rb
+++ b/spec/labor/emoji_converter_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe EmojiConverter do
describe "#convert" do
it "converts emoji names wrapped in colons into unicode" do
- joy_emoji_unicode = Emoji.find_by_alias("joy").raw
+ joy_emoji_unicode = Emoji.find_by_alias("joy").raw # rubocop:disable Rails/DynamicFindBy
expect(convert_emoji(":joy:")).to include(joy_emoji_unicode)
end
diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb
index 09e4ce329..37dd60671 100644
--- a/spec/models/article_spec.rb
+++ b/spec/models/article_spec.rb
@@ -440,7 +440,7 @@ RSpec.describe Article, type: :model do
end
it "shows year in readable time if not current year" do
- article.published_at = 1.years.ago
+ article.published_at = 1.year.ago
last_year = 1.year.ago.year % 100
expect(article.readable_publish_date.include?("'#{last_year}")).to eq(true)
end
diff --git a/spec/models/comment_spec.rb b/spec/models/comment_spec.rb
index 95aeeec66..f3baf00a1 100644
--- a/spec/models/comment_spec.rb
+++ b/spec/models/comment_spec.rb
@@ -129,7 +129,7 @@ RSpec.describe Comment, type: :model do
end
it "shows year in readable time if not current year" do
- comment.created_at = 1.years.ago
+ comment.created_at = 1.year.ago
last_year = 1.year.ago.year % 100
expect(comment.readable_publish_date.include?("'#{last_year}")).to eq(true)
end
diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb
index 8e034d4eb..169e04a37 100644
--- a/spec/rails_helper.rb
+++ b/spec/rails_helper.rb
@@ -26,9 +26,9 @@ require "test_prof/recipes/rspec/before_all"
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
-Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
-Dir[Rails.root.join("spec/features/shared_examples/**/*.rb")].each { |f| require f }
-Dir[Rails.root.join("spec/models/shared_examples/**/*.rb")].each { |f| require f }
+Dir[Rails.root.join("spec", "support", "**", "*.rb")].each { |f| require f }
+Dir[Rails.root.join("spec", "features", "shared_examples", "**", "*.rb")].each { |f| require f }
+Dir[Rails.root.join("spec", "models", "shared_examples", "**", "*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
diff --git a/spec/requests/api/v0/github_repos_spec.rb b/spec/requests/api/v0/github_repos_spec.rb
index 44e05fd02..fe1f593d8 100644
--- a/spec/requests/api/v0/github_repos_spec.rb
+++ b/spec/requests/api/v0/github_repos_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe "Api::V0::GithubRepos", type: :request do
describe "GET /api/v0/github_repos" do
it "returns 200 on success" do
get "/api/github_repos"
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
end
@@ -25,7 +25,7 @@ RSpec.describe "Api::V0::GithubRepos", type: :request do
it "returns 200 and json response on success" do
param = stubbed_github_repos.first.to_h.to_json
post "/api/github_repos/update_or_create", params: { github_repo: param }
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
expect(response.content_type).to eq("application/json")
end
end
diff --git a/spec/requests/api_secrets_destroy_spec.rb b/spec/requests/api_secrets_destroy_spec.rb
index 4d3db9035..6a168be5b 100644
--- a/spec/requests/api_secrets_destroy_spec.rb
+++ b/spec/requests/api_secrets_destroy_spec.rb
@@ -22,7 +22,7 @@ RSpec.describe "ApiSecretsDestroy", type: :request do
context "when delete fails" do
before do
- allow(ApiSecret).to receive(:find_by_id).and_return api_secret
+ allow(ApiSecret).to receive(:find_by).with(id: api_secret.id.to_s).and_return api_secret
allow(api_secret).to receive(:destroy).and_return false
end
diff --git a/spec/requests/article_mutes_spec.rb b/spec/requests/article_mutes_spec.rb
index ba9c654ef..930d5bf00 100644
--- a/spec/requests/article_mutes_spec.rb
+++ b/spec/requests/article_mutes_spec.rb
@@ -10,7 +10,7 @@ RSpec.describe "ArticleMutes", type: :request do
article = create(:article, user: user)
patch "/article_mutes/#{article.id}",
params: { article: { receive_notifications: false } }
- expect(response).to have_http_status(302)
+ expect(response).to have_http_status(:found)
end
end
end
diff --git a/spec/requests/articles_api_spec.rb b/spec/requests/articles_api_spec.rb
index fbc9a9e4f..4ecd1b229 100644
--- a/spec/requests/articles_api_spec.rb
+++ b/spec/requests/articles_api_spec.rb
@@ -51,7 +51,7 @@ RSpec.describe "ArticlesApi", type: :request do
it "returns not tag articles if article and tag are not approved" do
article = create(:article, approved: false)
- tag = Tag.find_by_name(article.tag_list.first)
+ tag = Tag.find_by(name: article.tag_list.first)
tag.update(requires_approval: true)
get "/api/articles?tag=#{tag.name}"
expect(JSON.parse(response.body).size).to eq(0)
@@ -97,7 +97,7 @@ RSpec.describe "ArticlesApi", type: :request do
tag_list: "yo",
series: "helloyo" }
}
- expect(Article.last.collection).to eq(Collection.find_by_slug("helloyo"))
+ expect(Article.last.collection).to eq(Collection.find_by(slug: "helloyo"))
expect(Article.last.collection.user_id).to eq(Article.last.user_id)
end
@@ -108,7 +108,7 @@ RSpec.describe "ArticlesApi", type: :request do
tag_list: "yo"
}
}
- expect(Article.last.collection).to eq(Collection.find_by_slug("helloyo"))
+ expect(Article.last.collection).to eq(Collection.find_by(slug: "helloyo"))
expect(Article.last.collection.user_id).to eq(Article.last.user_id)
end
end
diff --git a/spec/requests/buffered_articles_spec.rb b/spec/requests/buffered_articles_spec.rb
index c8347c4f1..49353cf02 100644
--- a/spec/requests/buffered_articles_spec.rb
+++ b/spec/requests/buffered_articles_spec.rb
@@ -4,7 +4,7 @@ RSpec.describe "BufferedArticles", type: :request do
describe "GET /buffered_articles" do
it "works! (now write some real specs)" do
get "/buffered_articles"
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "responds with json" do
get "/buffered_articles"
diff --git a/spec/requests/comments_spec.rb b/spec/requests/comments_spec.rb
index 970fffaeb..fefb4aaa2 100644
--- a/spec/requests/comments_spec.rb
+++ b/spec/requests/comments_spec.rb
@@ -21,7 +21,7 @@ RSpec.describe "Comments", type: :request do
describe "GET comment index" do
it "returns 200" do
get comment.path
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "displays a comment" do
@@ -32,7 +32,7 @@ RSpec.describe "Comments", type: :request do
context "when the comment is for a podcast's episode" do
it "works" do
get podcast_comment.path
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
end
@@ -65,7 +65,7 @@ RSpec.describe "Comments", type: :request do
it "returns 200" do
get "/#{user.username}/#{article.slug}/comments/#{comment.id_code_generated}/edit"
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "returns the comment" do
@@ -80,7 +80,7 @@ RSpec.describe "Comments", type: :request do
post "/comments/preview",
params: { comment: { body_markdown: "hi" } },
headers: { HTTP_ACCEPT: "application/json" }
- expect(response).to have_http_status(401)
+ expect(response).to have_http_status(:unauthorized)
end
context "when logged-in" do
@@ -92,7 +92,7 @@ RSpec.describe "Comments", type: :request do
end
it "returns 200 on good request" do
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "returns json" do
diff --git a/spec/requests/editor_spec.rb b/spec/requests/editor_spec.rb
index a1c0ccb36..c605d1f02 100644
--- a/spec/requests/editor_spec.rb
+++ b/spec/requests/editor_spec.rb
@@ -43,7 +43,7 @@ RSpec.describe "Editor", type: :request do
context "when not logged-in" do
it "redirects to /enter" do
post "/articles/preview", headers: headers
- expect(response).to have_http_status(401)
+ expect(response).to have_http_status(:unauthorized)
end
end
diff --git a/spec/requests/followed_articles_spec.rb b/spec/requests/followed_articles_spec.rb
index b8a01bb3d..1a4e26c64 100644
--- a/spec/requests/followed_articles_spec.rb
+++ b/spec/requests/followed_articles_spec.rb
@@ -15,7 +15,7 @@ RSpec.describe "FollowedArticles", type: :request do
it "returns articles of tag I follow" do
article = create(:article)
- user.follow(Tag.find_by_name(article.tag_list.first))
+ user.follow(Tag.find_by(name: article.tag_list.first))
get "/followed_articles"
expect(JSON.parse(response.body)["articles"].first["title"]).to eq(article.title)
end
diff --git a/spec/requests/follows_create_spec.rb b/spec/requests/follows_create_spec.rb
index 2700b74bb..6d0da1f33 100644
--- a/spec/requests/follows_create_spec.rb
+++ b/spec/requests/follows_create_spec.rb
@@ -70,7 +70,7 @@ RSpec.describe "Following/Unfollowing", type: :request do
it "returns articles of tag the user follows" do
article = create(:article)
- user.follow(Tag.find_by_name(article.tag_list.first))
+ user.follow(Tag.find_by(name: article.tag_list.first))
get "/followed_articles"
expect(JSON.parse(response.body)["articles"].first["title"]).to eq(article.title)
end
diff --git a/spec/requests/github_repos_spec.rb b/spec/requests/github_repos_spec.rb
index 91ebe94f2..484295a30 100644
--- a/spec/requests/github_repos_spec.rb
+++ b/spec/requests/github_repos_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe "GithubRepos", type: :request do
describe "POST /github_repos" do
it "returns a 302" do
post "/github_repos", params: { github_repo: { github_id_code: repo.github_id_code } }
- expect(response).to have_http_status(302)
+ expect(response).to have_http_status(:found)
end
it "creates a new GithubRepo object" do
@@ -33,7 +33,7 @@ RSpec.describe "GithubRepos", type: :request do
it "returns a 302" do
put "/github_repos/#{repo.id}"
- expect(response).to have_http_status(302)
+ expect(response).to have_http_status(:found)
end
it "unfeatures the requested GithubRepo" do
diff --git a/spec/requests/image_uploads_spec.rb b/spec/requests/image_uploads_spec.rb
index 2d0bb24e0..7c943de7f 100644
--- a/spec/requests/image_uploads_spec.rb
+++ b/spec/requests/image_uploads_spec.rb
@@ -6,13 +6,13 @@ RSpec.describe "ImageUploads", type: :request do
let(:headers) { { "Content-Type": "application/json", Accept: "application/json" } }
let(:image) do
Rack::Test::UploadedFile.new(
- File.join(Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"),
+ Rails.root.join("spec", "support", "fixtures", "images", "image1.jpeg"),
"image/jpeg",
)
end
let(:bad_image) do
Rack::Test::UploadedFile.new(
- File.join(Rails.root, "spec", "support", "fixtures", "images", "bad-image.jpg"),
+ Rails.root.join("spec", "support", "fixtures", "images", "bad-image.jpg"),
"image/jpeg",
)
end
diff --git a/spec/requests/moderations_spec.rb b/spec/requests/moderations_spec.rb
index 45178b066..63fd35447 100644
--- a/spec/requests/moderations_spec.rb
+++ b/spec/requests/moderations_spec.rb
@@ -4,7 +4,7 @@ RSpec.shared_examples "an elevated privilege required request" do |path|
context "when not logged-in" do
it "does not grant acesss", proper_status: true do
get path
- expect(response).to have_http_status(404)
+ expect(response).to have_http_status(:not_found)
end
it "raises Pundit::NotAuthorizedError internally" do
@@ -17,7 +17,7 @@ RSpec.shared_examples "an elevated privilege required request" do |path|
it "does not grant acesss", proper_status: true do
get path
- expect(response).to have_http_status(404)
+ expect(response).to have_http_status(:not_found)
end
it "internally raise Pundit::NotAuthorized internally" do
@@ -39,17 +39,17 @@ RSpec.describe "Moderations", type: :request do
it "grant access to comment moderation" do
get comment.path + "/mod"
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "grant access to article moderation" do
get article.path + "/mod"
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "grants access to /mod index" do
get "/mod"
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
it "grants access to /mod index with articles" do
create(:article, published: true)
diff --git a/spec/requests/push_notification_subscriptions_spec.rb b/spec/requests/push_notification_subscriptions_spec.rb
index 4ed50afca..362067a8a 100644
--- a/spec/requests/push_notification_subscriptions_spec.rb
+++ b/spec/requests/push_notification_subscriptions_spec.rb
@@ -13,7 +13,7 @@ RSpec.describe "PushNotificationSubscriptions", type: :request do
endpoint: "random"
}
}
- expect(response).to have_http_status(201)
+ expect(response).to have_http_status(:created)
expect(JSON.parse(response.body)["endpoint"]).to eq("random")
end
end
diff --git a/spec/requests/reactions_api_spec.rb b/spec/requests/reactions_api_spec.rb
index 2f8f643d9..8d7d45f57 100644
--- a/spec/requests/reactions_api_spec.rb
+++ b/spec/requests/reactions_api_spec.rb
@@ -23,7 +23,7 @@ RSpec.describe "ArticlesApi", type: :request do
post "/api/reactions", params: {
reactable_id: article.id, reactable_type: "Article", category: "like", key: user.secret
}
- expect(response).to have_http_status(422)
+ expect(response).to have_http_status(:unprocessable_entity)
end
end
end
diff --git a/spec/requests/stripe_cancellations_spec.rb b/spec/requests/stripe_cancellations_spec.rb
index 54e14cc38..31a115f74 100644
--- a/spec/requests/stripe_cancellations_spec.rb
+++ b/spec/requests/stripe_cancellations_spec.rb
@@ -28,7 +28,7 @@ RSpec.describe "StripeCancellations", type: :request do
post "/stripe_cancellations", params: event.as_json
user.reload
expect(user.monthly_dues).to eq(0)
- expect(response).to have_http_status(200)
+ expect(response).to have_http_status(:ok)
end
# rubocop:enable RSpec/ExampleLength
end
diff --git a/spec/requests/video_states_update_spec.rb b/spec/requests/video_states_update_spec.rb
index 59696eea0..532fa277f 100644
--- a/spec/requests/video_states_update_spec.rb
+++ b/spec/requests/video_states_update_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe "VideoStatesUpdate", type: :request do
it "rejects non-authorized users" do
post "/video_states?key=#{regular_user.secret}",
params: { input: { key: article.video_code } }
- expect(response).to have_http_status(422)
+ expect(response).to have_http_status(:unprocessable_entity)
end
end
end