Enables Rails cops (#2186)

* Enable Rails cops

* Fix Rails/DynamicFindBy

* Fix Rails/HttpStatus

* Fix Rails/Blank

* Fix Rails/RequestReferer

* Fix Rails/ActiveRecordAliases

* Fix Rails/FindBy

* Fix Rails/Presence

* Fix Rails/Delegate

* Fix Rails/Validation

* Fix Rails/PluralizationGrammar

* Fix Rails/Present

* Fix Rails/Output

* Fix Rails/Blank

* Fix Rails/FilePath

* Fix Rails/InverseOf

* Fix Rails/LexicallyScopedActionFilter

* Add Rails/OutputSafety to TODO

* Add Rails/HasManyOrHasOneDependent to TODO

* Add Rails/SkipsModelValidations to TODO
This commit is contained in:
Abraham Williams 2019-03-25 08:25:55 -05:00 committed by Ben Halpern
parent 9470ad8e7f
commit 9cb40e546b
94 changed files with 238 additions and 231 deletions

View file

@ -249,6 +249,9 @@ Layout/InitialIndentation:
# Rails
Rails:
Enabled: true
Rails/Date:
Description: >-
Checks the correct usage of date aware methods,

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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).

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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!

View file

@ -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

View file

@ -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

View file

@ -1,5 +1,4 @@
class OrganizationsController < ApplicationController
before_action :authenticate_user!, except: [:show]
after_action :verify_authorized
def create

View file

@ -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],
)

View file

@ -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

View file

@ -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?

View file

@ -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"

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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" }

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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
<a class='comment-mentioned-user' href='#{ApplicationConfig['APP_PROTOCOL']}#{ApplicationConfig['APP_DOMAIN']}/#{username}'>@#{username}</a>
HTML

View file

@ -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

View file

@ -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)

View file

@ -36,7 +36,7 @@ class DevCommentTag < LiquidTagBase
+image_tag("/assets/twitter-logo.svg", class: "icon-img", alt: "twitter") + \
"</a>"
end
return unless @comment.user.github_username.present?
return if @comment.user.github_username.blank?
result + "<a href=\"https://github.com/#{@comment.user.github_username}\">" \
+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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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
<a href="https://twitter.com/#{@user.twitter_username}" target="_blank" rel="noopener">
@ -60,7 +60,7 @@ class UserTag < LiquidTagBase
end
def github_link
return unless @user.github_username.present?
return if @user.github_username.blank?
<<-HTML
<a href="https://github.com/#{@user.github_username}" target="_blank" rel="noopener">
@ -70,7 +70,7 @@ class UserTag < LiquidTagBase
end
def website_link
return unless @user.website_url.present?
return if @user.website_url.blank?
<<-HTML
<a href="#{@user.website_url}" target="_blank" rel="noopener">

View file

@ -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

View file

@ -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] }

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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])

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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<p>&nbsp;</p>\r\n", "").gsub("\r\n<p>&nbsp;</p>\r\n", "").

View file

@ -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

View file

@ -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

View file

@ -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]

View file

@ -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)

View file

@ -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").

View file

@ -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

View file

@ -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!

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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,

View file

@ -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

View file

@ -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)}" }

View file

@ -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

View file

@ -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

View file

@ -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")

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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.

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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"

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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