From 79fdfa86aecbdc9fa4758cc21d5a804c0ade21e9 Mon Sep 17 00:00:00 2001 From: evazion Date: Mon, 27 Sep 2021 00:44:41 -0500 Subject: [PATCH] Fix various rubocop warnings. --- app/controllers/posts_controller.rb | 2 +- app/helpers/application_helper.rb | 36 ++++++++++---------- app/helpers/artist_versions_helper.rb | 4 +-- app/helpers/forum_topics_helper.rb | 7 ++-- app/helpers/post_versions_helper.rb | 10 +++--- app/helpers/posts_helper.rb | 2 +- app/helpers/seo_helper.rb | 26 +++++++-------- app/helpers/wiki_page_versions_helper.rb | 2 +- app/models/api_key.rb | 9 ++--- app/models/application_record.rb | 26 +++++++-------- app/models/artist.rb | 10 +++--- app/models/artist_commentary.rb | 13 +++++--- app/models/artist_commentary_version.rb | 12 ++----- app/models/artist_url.rb | 42 ++++++++++++------------ app/models/artist_version.rb | 4 +-- app/models/dmail.rb | 2 +- app/models/dtext_link.rb | 2 +- app/models/email_address.rb | 3 +- app/models/favorite_group.rb | 4 +-- app/models/forum_post.rb | 2 +- app/models/forum_topic.rb | 7 ++-- app/models/ip_address.rb | 2 +- app/models/ip_geolocation.rb | 3 +- app/models/media_asset.rb | 3 +- app/models/media_metadata.rb | 3 +- app/models/moderation_report.rb | 2 +- app/models/news_update.rb | 3 +- app/models/note.rb | 2 +- app/models/pool.rb | 2 +- app/models/pool_version.rb | 2 +- app/models/post.rb | 22 +++++++------ app/models/post_flag.rb | 2 +- app/models/post_version.rb | 2 +- app/models/rate_limit.rb | 12 +++---- app/models/tag.rb | 6 ++-- app/models/tag_alias.rb | 2 +- app/models/upload.rb | 4 ++- app/models/user_event.rb | 3 +- app/models/user_upgrade.rb | 3 +- 39 files changed, 149 insertions(+), 154 deletions(-) diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 31d6a46b8..0dd5bd640 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -83,7 +83,7 @@ class PostsController < ApplicationController @error_message = @post.errors.full_messages.join("; ") render :json => {:success => false, :reason => @error_message}.to_json, :status => 400 else - head :no_content + head 204 end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 8f934dcb2..c2ae376e6 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -29,9 +29,9 @@ module ApplicationHelper return type == "previous" ? "New" : "" end - changed_fields = record.class.status_fields.select do |field, status| + changed_fields = record.class.status_fields.select do |field, _status| (record.has_attribute?(field) && record[field] != other[field]) || - (!record.has_attribute?(field) && record.send(field, type)) + (!record.has_attribute?(field) && record.send(field, type)) end statuses = changed_fields.map { |field, status| status } @@ -52,7 +52,7 @@ module ApplicationHelper html = [] %w[previous subsequent current].each do |type| if type == params[:type] - html << %(#{type}) + html << %{#{type}} else html << tag.li(link_to(type, params.except(:controller, :action).merge(type: type).permit!)) end @@ -106,7 +106,7 @@ module ApplicationHelper if number >= 10_000 "#{number / 1_000}k" elsif number >= 1_000 - "%.1fk" % (number / 1_000.0) + format("%.1fk", number / 1_000.0) else number.to_s end @@ -142,11 +142,11 @@ module ApplicationHelper end def external_link_to(url, text = url, truncate: nil, strip: false, **link_options) - text = text.gsub(%r!\Ahttps?://!i, "") if strip == :scheme - text = text.gsub(%r!\Ahttps?://(?:www\.)?!i, "") if strip == :subdomain + text = text.gsub(%r{\Ahttps?://}i, "") if strip == :scheme + text = text.gsub(%r{\Ahttps?://(?:www\.)?}i, "") if strip == :subdomain text = text.truncate(truncate) if truncate - if url =~ %r!\Ahttps?://!i + if url =~ %r{\Ahttps?://}i link_to text, url, rel: "external noreferrer nofollow", **link_options else url @@ -369,37 +369,37 @@ module ApplicationHelper def nav_link_match(controller, url) url =~ case controller when "sessions", "users", "admin/users" - /^\/(session|users)/ + %r{^/(session|users)} when "comments" - /^\/comments/ + %r{^/comments} when "notes", "note_versions" - /^\/notes/ + %r{^/notes} when "posts", "uploads", "post_versions", "explore/posts", "moderator/post/dashboards", "favorites" - /^\/post/ + %r{^/post} when "artists", "artist_versions" - /^\/artist/ + %r{^/artist} when "tags", "tag_aliases", "tag_implications" - /^\/tags/ + %r{^/tags} when "pools", "pool_versions" - /^\/pools/ + %r{^/pools} when "moderator/dashboards" - /^\/moderator/ + %r{^/moderator} when "wiki_pages", "wiki_page_versions" - /^\/wiki_pages/ + %r{^/wiki_pages} when "forum_topics", "forum_posts" - /^\/forum_topics/ + %r{^/forum_topics} else - /^\/static/ + %r{^/static} end end end diff --git a/app/helpers/artist_versions_helper.rb b/app/helpers/artist_versions_helper.rb index 3e5a366f6..998720d65 100644 --- a/app/helpers/artist_versions_helper.rb +++ b/app/helpers/artist_versions_helper.rb @@ -43,7 +43,7 @@ module ArtistVersionsHelper else name_diff = diff_name_html(other.name, artist_version.name) end - %(

Rename:
 #{name_diff}

).html_safe + %{

Rename:
 #{name_diff}

}.html_safe else "" end @@ -58,7 +58,7 @@ module ArtistVersionsHelper else group_name_diff = diff_name_html(other_group_name, artist_version.group_name) end - %(Group:
 #{group_name_diff}

).html_safe + %{Group:
 #{group_name_diff}

}.html_safe else "" end diff --git a/app/helpers/forum_topics_helper.rb b/app/helpers/forum_topics_helper.rb index 00876c87b..6acc6c16c 100644 --- a/app/helpers/forum_topics_helper.rb +++ b/app/helpers/forum_topics_helper.rb @@ -8,7 +8,7 @@ module ForumTopicsHelper end def new_forum_topic?(topic, read_forum_topics) - !read_forum_topics.map(&:id).include?(topic.id) + read_forum_topics.map(&:id).exclude?(topic.id) end def forum_topic_status(topic) @@ -24,9 +24,10 @@ module ForumTopicsHelper end def forum_post_vote_icon(vote) - if vote.score == 1 + case vote.score + when 1 upvote_icon - elsif vote.score == -1 + when -1 downvote_icon else meh_icon diff --git a/app/helpers/post_versions_helper.rb b/app/helpers/post_versions_helper.rb index 4758c849f..0f4d9eaaf 100644 --- a/app/helpers/post_versions_helper.rb +++ b/app/helpers/post_versions_helper.rb @@ -25,12 +25,12 @@ module PostVersionsHelper html = '' added_tags.each do |tag| - obsolete_class = (obsolete_added_tags.include?(tag) ? "diff-obsolete" : ""); - html << %(#{link_to(wordbreakify(tag), posts_path(:tags => tag))} ) + obsolete_class = (obsolete_added_tags.include?(tag) ? "diff-obsolete" : "") + html << %{#{link_to(wordbreakify(tag), posts_path(:tags => tag))} } end removed_tags.each do |tag| - obsolete_class = (obsolete_removed_tags.include?(tag) ? "diff-obsolete" : ""); - html << %(#{link_to(wordbreakify(tag), posts_path(:tags => tag))} ) + obsolete_class = (obsolete_removed_tags.include?(tag) ? "diff-obsolete" : "") + html << %{#{link_to(wordbreakify(tag), posts_path(:tags => tag))} } end html << "" @@ -42,7 +42,7 @@ module PostVersionsHelper prefix = (field == :parent_id ? "parent" : field.to_s) search = "#{prefix}:#{value}" display = (field == :rating ? post_version.pretty_rating : value) - %(#{field.to_s.titleize}: #{link_to(display, posts_path(:tags => search))}).html_safe + %{#{field.to_s.titleize}: #{link_to(display, posts_path(:tags => search))}}.html_safe end def post_version_value(value) diff --git a/app/helpers/posts_helper.rb b/app/helpers/posts_helper.rb index 3e8f35583..46190d915 100644 --- a/app/helpers/posts_helper.rb +++ b/app/helpers/posts_helper.rb @@ -35,7 +35,7 @@ module PostsHelper def post_source_tag(source, normalized_source = source) # Only allow http:// and https:// links. Disallow javascript: links. - if source =~ %r!\Ahttps?://!i + if source =~ %r{\Ahttps?://}i external_link_to(normalized_source, strip: :subdomain) + " ".html_safe + link_to("ยป", source, rel: "external noreferrer nofollow") else source diff --git a/app/helpers/seo_helper.rb b/app/helpers/seo_helper.rb index a26d7762d..e04b2163f 100644 --- a/app/helpers/seo_helper.rb +++ b/app/helpers/seo_helper.rb @@ -17,11 +17,11 @@ module SeoHelper json_ld_tag({ "@context": "https://schema.org", "@type": "VideoObject", - "name": page_title, - "description": meta_description, - "uploadDate": post.created_at.iso8601, - "thumbnailUrl": post.preview_file_url, - "contentUrl": post.file_url, + name: page_title, + description: meta_description, + uploadDate: post.created_at.iso8601, + thumbnailUrl: post.preview_file_url, + contentUrl: post.file_url, }) end @@ -30,7 +30,7 @@ module SeoHelper Danbooru.config.twitter_url, Danbooru.config.discord_server_url, Danbooru.config.source_code_url, - "https://en.wikipedia.org/wiki/Danbooru" + "https://en.wikipedia.org/wiki/Danbooru", ].compact json_ld_tag({ @@ -41,18 +41,18 @@ module SeoHelper url: root_url(host: Danbooru.config.hostname), name: Danbooru.config.app_name, logo: "#{root_url(host: Danbooru.config.hostname)}images/danbooru-logo-500x500.png", - sameAs: urls + sameAs: urls, }, { "@type": "WebSite", "@id": root_url(anchor: "website", host: Danbooru.config.hostname), - "url": root_url(host: Danbooru.config.hostname), - "name": Danbooru.config.app_name, - "description": site_description, - "potentialAction": [{ + url: root_url(host: Danbooru.config.hostname), + name: Danbooru.config.app_name, + description: site_description, + potentialAction: [{ "@type": "SearchAction", - "target": "#{posts_url(host: Danbooru.config.hostname)}?tags={search_term_string}", - "query-input": "required name=search_term_string" + target: "#{posts_url(host: Danbooru.config.hostname)}?tags={search_term_string}", + "query-input": "required name=search_term_string", }] } ] diff --git a/app/helpers/wiki_page_versions_helper.rb b/app/helpers/wiki_page_versions_helper.rb index 11123d929..221dd3d74 100644 --- a/app/helpers/wiki_page_versions_helper.rb +++ b/app/helpers/wiki_page_versions_helper.rb @@ -23,7 +23,7 @@ module WikiPageVersionsHelper else name_diff = diff_name_html(other.title, wiki_page_version.title) end - %((Rename: #{name_diff})).html_safe + %{(Rename: #{name_diff})}.html_safe else "" end diff --git a/app/models/api_key.rb b/app/models/api_key.rb index d841546f6..e0296f35a 100644 --- a/app/models/api_key.rb +++ b/app/models/api_key.rb @@ -23,8 +23,7 @@ class ApiKey < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :key, :user) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end concerning :PermissionMethods do @@ -59,9 +58,11 @@ class ApiKey < ApplicationRecord end def permissions_list - Rails.application.routes.routes.select do |route| + routes = Rails.application.routes.routes.select do |route| route.defaults[:controller].present? && !route.internal - end.map do |route| + end + + routes.map do |route| "#{route.defaults[:controller]}:#{route.defaults[:action]}" end.uniq.sort end diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 42c33a876..91c67e40e 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -26,7 +26,7 @@ class ApplicationRecord < ActiveRecord::Base concerning :PrivilegeMethods do class_methods do - def visible(user) + def visible(_user) all end @@ -47,14 +47,14 @@ class ApplicationRecord < ActiveRecord::Base end def multiple_includes - reflections.reject { |k,v| v.macro != :has_many }.keys.map(&:to_sym) + reflections.select { |_, v| v.macro == :has_many }.keys.map(&:to_sym) end def associated_models(name) if reflections[name].options[:polymorphic] - associated_models = reflections[name].active_record.try(:model_types) || [] + reflections[name].active_record.try(:model_types) || [] else - associated_models = [reflections[name].class_name] + [reflections[name].class_name] end end end @@ -77,7 +77,7 @@ class ApplicationRecord < ActiveRecord::Base def serializable_hash(options = {}) options ||= {} - if options[:only] && options[:only].is_a?(String) + if options[:only].is_a?(String) options.delete(:methods) options.delete(:include) options.merge!(ParameterBuilder.serial_parameters(options[:only], self)) @@ -116,20 +116,20 @@ class ApplicationRecord < ActiveRecord::Base concerning :ActiveRecordExtensions do class_methods do def without_timeout - connection.execute("SET STATEMENT_TIMEOUT = 0") unless Rails.env == "test" + connection.execute("SET STATEMENT_TIMEOUT = 0") unless Rails.env.test? yield ensure - connection.execute("SET STATEMENT_TIMEOUT = #{CurrentUser.user.try(:statement_timeout) || 3_000}") unless Rails.env == "test" + connection.execute("SET STATEMENT_TIMEOUT = #{CurrentUser.user.try(:statement_timeout) || 3_000}") unless Rails.env.test? end def with_timeout(n, default_value = nil, new_relic_params = {}) - connection.execute("SET STATEMENT_TIMEOUT = #{n}") unless Rails.env == "test" + connection.execute("SET STATEMENT_TIMEOUT = #{n}") unless Rails.env.test? yield - rescue ::ActiveRecord::StatementInvalid => x - DanbooruLogger.log(x, expected: false, **new_relic_params) - return default_value + rescue ::ActiveRecord::StatementInvalid => e + DanbooruLogger.log(e, expected: false, **new_relic_params) + default_value ensure - connection.execute("SET STATEMENT_TIMEOUT = #{CurrentUser.user.try(:statement_timeout) || 3_000}") unless Rails.env == "test" + connection.execute("SET STATEMENT_TIMEOUT = #{CurrentUser.user.try(:statement_timeout) || 3_000}") unless Rails.env.test? end def update!(*args) @@ -161,7 +161,7 @@ class ApplicationRecord < ActiveRecord::Base end concerning :DtextMethods do - def dtext_shortlink(**options) + def dtext_shortlink(**_options) "#{self.class.name.underscore.tr("_", " ")} ##{id}" end end diff --git a/app/models/artist.rb b/app/models/artist.rb index ef1e67e11..c5ccc2746 100644 --- a/app/models/artist.rb +++ b/app/models/artist.rb @@ -61,7 +61,7 @@ class Artist < ApplicationRecord concerning :NameMethods do class_methods do def normalize_name(name) - name.to_s.mb_chars.downcase.strip.gsub(/ /, '_').to_s + name.to_s.mb_chars.downcase.strip.gsub(/ /, "_").to_s end def normalize_other_names(other_names) @@ -216,7 +216,7 @@ class Artist < ApplicationRecord end def any_name_matches(query) - if query =~ %r!\A/(.*)/\z! + if query =~ %r{\A/(.*)/\z} where_regex(:name, $1).or(any_other_name_matches($1)).or(where_regex(:group_name, $1)) else normalized_name = normalize_name(query) @@ -228,11 +228,11 @@ class Artist < ApplicationRecord def url_matches(query) query = query.strip - if query =~ %r!\A/(.*)/\z! + if query =~ %r{\A/(.*)/\z} where(id: ArtistUrl.where_regex(:url, $1).select(:artist_id)) elsif query.include?("*") where(id: ArtistUrl.where_like(:url, query).select(:artist_id)) - elsif query =~ %r!\Ahttps?://!i + elsif query =~ %r{\Ahttps?://}i ArtistFinder.find_artists(query) else where(id: ArtistUrl.where_like(:url, "*#{query}*").select(:artist_id)) @@ -242,7 +242,7 @@ class Artist < ApplicationRecord def any_name_or_url_matches(query) query = query.strip - if query =~ %r!\Ahttps?://!i + if query =~ %r{\Ahttps?://}i url_matches(query) else any_name_matches(query) diff --git a/app/models/artist_commentary.rb b/app/models/artist_commentary.rb index d1b5bcee6..551ffb30e 100644 --- a/app/models/artist_commentary.rb +++ b/app/models/artist_commentary.rb @@ -1,10 +1,15 @@ class ArtistCommentary < ApplicationRecord class RevertError < StandardError; end - attr_accessor :remove_commentary_tag, :remove_commentary_request_tag, :remove_commentary_check_tag, :remove_partial_commentary_tag - attr_accessor :add_commentary_tag, :add_commentary_request_tag, :add_commentary_check_tag, :add_partial_commentary_tag + attr_accessor( + :remove_commentary_tag, :remove_commentary_request_tag, + :remove_commentary_check_tag, :remove_partial_commentary_tag, + :add_commentary_tag, :add_commentary_request_tag, :add_commentary_check_tag, + :add_partial_commentary_tag + ) + before_validation :trim_whitespace - validates_uniqueness_of :post_id + validates :post_id, uniqueness: true belongs_to :post has_many :versions, -> {order("artist_commentary_versions.id ASC")}, :class_name => "ArtistCommentaryVersion", :dependent => :destroy, :foreign_key => :post_id, :primary_key => :post_id has_one :previous_version, -> {order(id: :desc)}, :class_name => "ArtistCommentaryVersion", :foreign_key => :post_id, :primary_key => :post_id @@ -126,7 +131,7 @@ class ArtistCommentary < ApplicationRecord def revert_to(version) if post_id != version.post_id - raise RevertError.new("You cannot revert to a previous artist commentary of another post.") + raise RevertError, "You cannot revert to a previous artist commentary of another post." end self.original_description = version.original_description diff --git a/app/models/artist_commentary_version.rb b/app/models/artist_commentary_version.rb index 0b4c00436..93a2e36a7 100644 --- a/app/models/artist_commentary_version.rb +++ b/app/models/artist_commentary_version.rb @@ -22,23 +22,17 @@ class ArtistCommentaryVersion < ApplicationRecord end def previous - @previous ||= begin - ArtistCommentaryVersion.where("post_id = ? and updated_at < ?", post_id, updated_at).order("updated_at desc").limit(1).to_a - end + @previous ||= ArtistCommentaryVersion.where("post_id = ? and updated_at < ?", post_id, updated_at).order("updated_at desc").limit(1).to_a @previous.first end def subsequent - @subsequent ||= begin - ArtistCommentaryVersion.where("post_id = ? and updated_at > ?", post_id, updated_at).order("updated_at asc").limit(1).to_a - end + @subsequent ||= ArtistCommentaryVersion.where("post_id = ? and updated_at > ?", post_id, updated_at).order("updated_at asc").limit(1).to_a @subsequent.first end def current - @current ||= begin - ArtistCommentaryVersion.where("post_id = ?", post_id).order("updated_at desc").limit(1).to_a - end + @current ||= ArtistCommentaryVersion.where(post_id: post_id).order("updated_at desc").limit(1).to_a @current.first end diff --git a/app/models/artist_url.rb b/app/models/artist_url.rb index bc6d04d3e..f4a0358e2 100644 --- a/app/models/artist_url.rb +++ b/app/models/artist_url.rb @@ -20,22 +20,22 @@ class ArtistUrl < ApplicationRecord if url.nil? nil else - url = url.sub(%r!^https://!, "http://") - url = url.sub(%r!^http://blog-imgs-\d+\.fc2!, "http://blog.fc2") - url = url.sub(%r!^http://blog-imgs-\d+-\w+\.fc2!, "http://blog.fc2") - url = url.sub(%r!^http://blog\d*\.fc2\.com/(?:\w/){,3}(\w+)!, "http://\\1.blog.fc2.com") - url = url.sub(%r!^http://pictures.hentai-foundry.com//!, "http://pictures.hentai-foundry.com/") + url = url.sub(%r{^https://}, "http://") + url = url.sub(%r{^http://blog-imgs-\d+\.fc2}, "http://blog.fc2") + url = url.sub(%r{^http://blog-imgs-\d+-\w+\.fc2}, "http://blog.fc2") + url = url.sub(%r{^http://blog\d*\.fc2\.com/(?:\w/){,3}(\w+)}, "http://\\1.blog.fc2.com") + url = url.sub(%r{^http://pictures.hentai-foundry.com//}, "http://pictures.hentai-foundry.com/") # the strategy won't always work for twitter because it looks for a status - url = url.downcase if url =~ %r!^https?://(?:mobile\.)?twitter\.com! + url = url.downcase if url =~ %r{^https?://(?:mobile\.)?twitter\.com} url = Sources::Strategies.find(url).normalize_for_artist_finder # XXX the Pixiv strategy should implement normalize_for_artist_finder and return the correct url directly. - url = url.sub(%r!\Ahttps?://www\.pixiv\.net/(?:en/)?users/(\d+)\z!i, 'https://www.pixiv.net/member.php?id=\1') + url = url.sub(%r{\Ahttps?://www\.pixiv\.net/(?:en/)?users/(\d+)\z}i, 'https://www.pixiv.net/member.php?id=\1') - url = url.gsub(/\/+\Z/, "") - url = url.gsub(%r!^https://!, "http://") + url = url.gsub(%r{/+\Z}, "") + url = url.gsub(%r{^https://}, "http://") url + "/" end end @@ -60,7 +60,7 @@ class ArtistUrl < ApplicationRecord def self.url_attribute_matches(attr, url) if url.blank? all - elsif url =~ %r!\A/(.*)/\z! + elsif url =~ %r{\A/(.*)/\z} where_regex(attr, $1) elsif url.include?("*") where_ilike(attr, url) @@ -83,21 +83,21 @@ class ArtistUrl < ApplicationRecord # usually because it's redundant with the primary profile URL. def secondary_url? case url - when %r!pixiv\.net/stacc!i + when %r{pixiv\.net/stacc}i true - when %r!pixiv\.net/fanbox!i + when %r{pixiv\.net/fanbox}i true - when %r!twitter\.com/intent!i + when %r{twitter\.com/intent}i true - when %r!lohas\.nicoseiga\.jp!i + when %r{lohas\.nicoseiga\.jp}i true - when %r!(?:www|com|dic)\.nicovideo\.jp!i + when %r{(?:www|com|dic)\.nicovideo\.jp}i true - when %r!pawoo\.net/web/accounts!i + when %r{pawoo\.net/web/accounts}i true - when %r!www\.artstation\.com!i + when %r{www\.artstation\.com}i true - when %r!blogimg\.jp!i, %r!image\.blog\.livedoor\.jp!i + when %r{blogimg\.jp}i, %r{image\.blog\.livedoor\.jp}i true else false @@ -145,15 +145,15 @@ class ArtistUrl < ApplicationRecord end def validate_hostname(uri) - errors.add(:url, "'#{uri}' has a hostname '#{uri.host}' that does not contain a dot") unless uri.host&.include?('.') + errors.add(:url, "'#{uri}' has a hostname '#{uri.host}' that does not contain a dot") unless uri.host&.include?(".") end def validate_url_format uri = Addressable::URI.parse(url) validate_scheme(uri) validate_hostname(uri) - rescue Addressable::URI::InvalidURIError => error - errors.add(:url, "'#{uri}' is malformed: #{error}") + rescue Addressable::URI::InvalidURIError => e + errors.add(:url, "'#{uri}' is malformed: #{e}") end def self.available_includes diff --git a/app/models/artist_version.rb b/app/models/artist_version.rb index 723811f89..e78395703 100644 --- a/app/models/artist_version.rb +++ b/app/models/artist_version.rb @@ -42,9 +42,7 @@ class ArtistVersion < ApplicationRecord end def current - @previous ||= begin - ArtistVersion.where(artist_id: artist_id).order("created_at desc").limit(1).to_a - end + @previous ||= ArtistVersion.where(artist_id: artist_id).order("created_at desc").limit(1).to_a @previous.first end diff --git a/app/models/dmail.rb b/app/models/dmail.rb index 035a1e9ab..2dbc1498d 100644 --- a/app/models/dmail.rb +++ b/app/models/dmail.rb @@ -9,8 +9,8 @@ class Dmail < ApplicationRecord has_many :moderation_reports, as: :model, dependent: :destroy before_create :autoreport_spam - after_save :update_unread_dmail_count after_destroy :update_unread_dmail_count + after_save :update_unread_dmail_count after_commit :send_email, on: :create deletable diff --git a/app/models/dtext_link.rb b/app/models/dtext_link.rb index 6eff459f6..81ef5141a 100644 --- a/app/models/dtext_link.rb +++ b/app/models/dtext_link.rb @@ -47,7 +47,7 @@ class DtextLink < ApplicationRecord # postgres will raise an error if the link is more than 2712 bytes long # because it can't index values that take up more than 1/3 of an 8kb page. - self.link_target = self.link_target.truncate(2048, omission: "") + self.link_target = link_target.truncate(2048, omission: "") end def self.attribute_restriction(*) diff --git a/app/models/email_address.rb b/app/models/email_address.rb index 4d6c09101..d84033932 100644 --- a/app/models/email_address.rb +++ b/app/models/email_address.rb @@ -48,9 +48,8 @@ class EmailAddress < ApplicationRecord q = search_attributes(params, :id, :created_at, :updated_at, :user, :address, :normalized_address, :is_verified, :is_deliverable) q = q.restricted(params[:is_restricted]) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end def validate_deliverable diff --git a/app/models/favorite_group.rb b/app/models/favorite_group.rb index f831172ea..2cbaacc05 100644 --- a/app/models/favorite_group.rb +++ b/app/models/favorite_group.rb @@ -77,7 +77,7 @@ class FavoriteGroup < ApplicationRecord errors.add(:base, "Cannot add invalid post(s) to favgroup: #{nonexisting_post_ids.to_sentence}") end - duplicate_post_ids = post_ids.group_by(&:itself).transform_values(&:size).select { |id, count| count > 1 }.keys + duplicate_post_ids = post_ids.group_by(&:itself).transform_values(&:size).select { |_id, count| count > 1 }.keys if duplicate_post_ids.present? errors.add(:base, "Favgroup already contains post #{duplicate_post_ids.to_sentence}") end @@ -117,7 +117,7 @@ class FavoriteGroup < ApplicationRecord def posts favgroup_posts = FavoriteGroup.where(id: id).joins("CROSS JOIN unnest(favorite_groups.post_ids) WITH ORDINALITY AS row(post_id, favgroup_index)").select(:post_id, :favgroup_index) - posts = Post.joins("JOIN (#{favgroup_posts.to_sql}) favgroup_posts ON favgroup_posts.post_id = posts.id").order("favgroup_posts.favgroup_index ASC") + Post.joins("JOIN (#{favgroup_posts.to_sql}) favgroup_posts ON favgroup_posts.post_id = posts.id").order("favgroup_posts.favgroup_index ASC") end def add!(post) diff --git a/app/models/forum_post.rb b/app/models/forum_post.rb index 514fe3e48..93567f80e 100644 --- a/app/models/forum_post.rb +++ b/app/models/forum_post.rb @@ -179,7 +179,7 @@ class ForumPost < ApplicationRecord end end - def dtext_shortlink(**options) + def dtext_shortlink(**_options) "forum ##{id}" end diff --git a/app/models/forum_topic.rb b/app/models/forum_topic.rb index 515c427b3..d649018e8 100644 --- a/app/models/forum_topic.rb +++ b/app/models/forum_topic.rb @@ -94,11 +94,12 @@ class ForumTopic < ApplicationRecord q = q.public_only end - if params[:status] == "pending" + case params[:status] + when "pending" q = q.pending - elsif params[:status] == "approved" + when "approved" q = q.approved - elsif params[:status] == "rejected" + when "rejected" q = q.rejected end diff --git a/app/models/ip_address.rb b/app/models/ip_address.rb index 8898cb715..e46729406 100644 --- a/app/models/ip_address.rb +++ b/app/models/ip_address.rb @@ -20,7 +20,7 @@ class IpAddress < ApplicationRecord ipv4_masklen ||= 32 ipv6_masklen ||= 128 - q = select(sanitize_sql([<<~SQL, ipv4_masklen, ipv6_masklen])) + q = select(sanitize_sql([<<~SQL.squish, ipv4_masklen, ipv6_masklen])) CASE WHEN family(ip_addr) = 4 THEN network(set_masklen(ip_addr, ?)) diff --git a/app/models/ip_geolocation.rb b/app/models/ip_geolocation.rb index 9cd4920fe..2712395c1 100644 --- a/app/models/ip_geolocation.rb +++ b/app/models/ip_geolocation.rb @@ -16,8 +16,7 @@ class IpGeolocation < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :ip_addr, :network, :asn, :is_proxy, :latitude, :longitude, :organization, :time_zone, :continent, :country, :region, :city, :carrier) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end def self.create_or_update!(ip) diff --git a/app/models/media_asset.rb b/app/models/media_asset.rb index 44e01a7f1..bc14af6f7 100644 --- a/app/models/media_asset.rb +++ b/app/models/media_asset.rb @@ -12,8 +12,7 @@ class MediaAsset < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :md5, :file_ext, :file_size, :image_width, :image_height) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end def file=(file_or_path) diff --git a/app/models/media_metadata.rb b/app/models/media_metadata.rb index 5f1895394..dc7021cf4 100644 --- a/app/models/media_metadata.rb +++ b/app/models/media_metadata.rb @@ -16,8 +16,7 @@ class MediaMetadata < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :media_asset, :metadata) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end def file=(file_or_path) diff --git a/app/models/moderation_report.rb b/app/models/moderation_report.rb index bafe41b83..a5884939b 100644 --- a/app/models/moderation_report.rb +++ b/app/models/moderation_report.rb @@ -41,7 +41,7 @@ class ModerationReport < ApplicationRecord if topic.nil? CurrentUser.scoped(User.system) do topic = ForumTopic.create!(creator: User.system, title: forum_topic_title, category_id: 0, min_level: User::Levels::MODERATOR) - forum_post = ForumPost.create!(creator: User.system, body: forum_topic_body, topic: topic) + ForumPost.create!(creator: User.system, body: forum_topic_body, topic: topic) end end topic diff --git a/app/models/news_update.rb b/app/models/news_update.rb index a8cdb6fe9..f6b3f706a 100644 --- a/app/models/news_update.rb +++ b/app/models/news_update.rb @@ -13,7 +13,6 @@ class NewsUpdate < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :message, :creator, :updater) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end end diff --git a/app/models/note.rb b/app/models/note.rb index d9576ad5e..d8915355c 100644 --- a/app/models/note.rb +++ b/app/models/note.rb @@ -48,7 +48,7 @@ class Note < ApplicationRecord end def update_post - if self.saved_changes? + if saved_changes? if post.notes.active.exists? post.update_columns(last_noted_at: updated_at) else diff --git a/app/models/pool.rb b/app/models/pool.rb index 3fff0d2ed..01995915c 100644 --- a/app/models/pool.rb +++ b/app/models/pool.rb @@ -178,7 +178,7 @@ class Pool < ApplicationRecord # XXX unify with PostQueryBuilder ordpool search def posts pool_posts = Pool.where(id: id).joins("CROSS JOIN unnest(pools.post_ids) WITH ORDINALITY AS row(post_id, pool_index)").select(:post_id, :pool_index) - posts = Post.joins("JOIN (#{pool_posts.to_sql}) pool_posts ON pool_posts.post_id = posts.id").order("pool_posts.pool_index ASC") + Post.joins("JOIN (#{pool_posts.to_sql}) pool_posts ON pool_posts.post_id = posts.id").order("pool_posts.pool_index ASC") end def synchronize diff --git a/app/models/pool_version.rb b/app/models/pool_version.rb index b4efa26d7..bf008a429 100644 --- a/app/models/pool_version.rb +++ b/app/models/pool_version.rb @@ -78,7 +78,7 @@ class PoolVersion < ApplicationRecord name: pool.name, is_active: pool.is_active?, is_deleted: pool.is_deleted?, - category: pool.category + category: pool.category, } msg = "add pool version\n#{json.to_json}" sqs_service.send_message(msg, message_group_id: "pool:#{pool.id}") diff --git a/app/models/post.rb b/app/models/post.rb index a6588f188..30f83b7ca 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -444,7 +444,7 @@ class Post < ApplicationRecord invalid_tags = tag_names.map { |name| Tag.new(name: name) }.select { |tag| tag.invalid?(:name) } invalid_tags.each do |tag| - tag.errors.messages.each do |attribute, messages| + tag.errors.messages.each do |_attribute, messages| warnings.add(:base, "Couldn't add tag: #{messages.join(';')}") end end @@ -524,7 +524,7 @@ class Post < ApplicationRecord when /^newpool:(.+)$/i pool = Pool.find_by_name($1) if pool.nil? - pool = Pool.create(name: $1, description: "This pool was automatically generated") + Pool.create(name: $1, description: "This pool was automatically generated") end end end @@ -1073,7 +1073,7 @@ class Post < ApplicationRecord "tags" => tag_string, "height" => image_height, "file_size" => file_size, - "id" => id + "id" => id, } if visible? @@ -1148,7 +1148,7 @@ class Post < ApplicationRecord def with_flag_stats relation = left_outer_joins(:flags).group(:id).select("posts.*") - relation = relation.select("COUNT(post_flags.id) AS flag_count") + relation.select("COUNT(post_flags.id) AS flag_count") relation end @@ -1308,14 +1308,14 @@ class Post < ApplicationRecord image_width: media_file.width, image_height: media_file.height, file_size: media_file.file_size, - file_ext: media_file.file_ext, + file_ext: media_file.file_ext ) media_asset.update!( image_width: media_file.width, image_height: media_file.height, file_size: media_file.file_size, - file_ext: media_file.file_ext, + file_ext: media_file.file_ext ) purge_cached_urls! @@ -1328,7 +1328,7 @@ class Post < ApplicationRecord def purge_cached_urls! urls = [ preview_file_url, crop_file_url, large_file_url, file_url, - tagged_file_url(tagged_filenames: true), tagged_large_file_url(tagged_filenames: true) + tagged_file_url(tagged_filenames: true), tagged_large_file_url(tagged_filenames: true), ] CloudflareService.new.purge_cache(urls) @@ -1519,8 +1519,10 @@ class Post < ApplicationRecord def self.available_includes # attributes accessible through the ?only= parameter - [:uploader, :updater, :approver, :upload, :flags, :appeals, - :parent, :children, :notes, :comments, :approvals, :disapprovals, - :replacements, :pixiv_ugoira_frame_data, :artist_commentary] + %i[ + uploader updater approver upload flags appeals parent children notes + comments approvals disapprovals replacements pixiv_ugoira_frame_data + artist_commentary + ] end end diff --git a/app/models/post_flag.rb b/app/models/post_flag.rb index 232141ff8..1bed4bf39 100644 --- a/app/models/post_flag.rb +++ b/app/models/post_flag.rb @@ -11,7 +11,7 @@ class PostFlag < ApplicationRecord validates :reason, presence: true, length: { in: 1..140 } validate :validate_creator_is_not_limited, on: :create validate :validate_post, on: :create - validates_uniqueness_of :creator_id, scope: :post_id, on: :create, unless: :is_deletion, message: "have already flagged this post" + validates :creator_id, uniqueness: { scope: :post_id, on: :create, unless: :is_deletion, message: "have already flagged this post" } before_save :update_post attr_accessor :is_deletion diff --git a/app/models/post_version.rb b/app/models/post_version.rb index 15ce93239..a1a72b574 100644 --- a/app/models/post_version.rb +++ b/app/models/post_version.rb @@ -238,7 +238,7 @@ class PostVersion < ApplicationRecord end def truncated_source - source.gsub(/^http:\/\//, "").sub(/\/.+/, "") + source.gsub(%r{^http://}, "").sub(%r{/.+}, "") end def undo! diff --git a/app/models/rate_limit.rb b/app/models/rate_limit.rb index dc9daee90..4f6824c8d 100644 --- a/app/models/rate_limit.rb +++ b/app/models/rate_limit.rb @@ -17,8 +17,7 @@ class RateLimit < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :limited, :points, :action, :key) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end # `action` is the action being limited. Usually a controller endpoint. @@ -31,7 +30,7 @@ class RateLimit < ApplicationRecord key_params = keys.map.with_index { |key, i| [:"key#{i}", key] }.to_h # (created_at, updated_at, action, keyN, points) - values = keys.map.with_index { |key, i| "(:now, :now, :action, :key#{i}, :points)" } + values = keys.map.with_index { |_key, i| "(:now, :now, :action, :key#{i}, :points)" } # Do an upsert, creating a new rate limit object for each key that doesn't # already exist, and updating the limit for each limit that already exists. @@ -43,7 +42,7 @@ class RateLimit < ApplicationRecord # the point count and subtract the cost of the call. # # https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT - sql = <<~SQL + sql = <<~SQL.squish INSERT INTO rate_limits (created_at, updated_at, action, key, points) VALUES #{values.join(", ")} ON CONFLICT (action, key) DO UPDATE SET @@ -67,10 +66,9 @@ class RateLimit < ApplicationRecord cost: cost, points: burst - cost, minimum_points: minimum_points, - **key_params + **key_params, } - rate_limits = RateLimit.find_by_sql([sql, sql_params]) - rate_limits + RateLimit.find_by_sql([sql, sql_params]) end end diff --git a/app/models/tag.rb b/app/models/tag.rb index b888306d3..804fe88d9 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -74,7 +74,7 @@ class Tag < ApplicationRecord # fix tags where the post count is non-zero but the tag isn't present on any posts. def regenerate_nonexistent_post_counts! - Tag.find_by_sql(<<~SQL) + Tag.find_by_sql(<<~SQL.squish) UPDATE tags SET post_count = 0 WHERE @@ -90,7 +90,7 @@ class Tag < ApplicationRecord # fix tags where the stored post count doesn't match the true post count. def regenerate_incorrect_post_counts! - Tag.find_by_sql(<<~SQL) + Tag.find_by_sql(<<~SQL.squish) UPDATE tags SET post_count = true_count FROM ( @@ -223,7 +223,7 @@ class Tag < ApplicationRecord module SearchMethods def autocorrect_matches(name) - tags = fuzzy_name_matches(name).order_similarity(name) + fuzzy_name_matches(name).order_similarity(name) end # ref: https://www.postgresql.org/docs/current/static/pgtrgm.html#idm46428634524336 diff --git a/app/models/tag_alias.rb b/app/models/tag_alias.rb index 4070e61e0..e0eb31faf 100644 --- a/app/models/tag_alias.rb +++ b/app/models/tag_alias.rb @@ -1,7 +1,7 @@ class TagAlias < TagRelationship # Validate that the alias doesn't exist yet when it's created or when a BUR # is requested, but not when a BUR is approved (to allow failed BURs to be reapproved) - validates_uniqueness_of :antecedent_name, scope: :status, conditions: -> { active }, on: %i[create update request] + validates :antecedent_name, uniqueness: { scope: :status, conditions: -> { active }, on: %i[create update request] } validate :absence_of_transitive_relation before_create :delete_conflicting_relationships diff --git a/app/models/upload.rb b/app/models/upload.rb index 387be4e49..8a142787a 100644 --- a/app/models/upload.rb +++ b/app/models/upload.rb @@ -215,7 +215,9 @@ class Upload < ApplicationRecord end def assign_rating_from_tags - if rating = PostQueryBuilder.new(tag_string).find_metatag(:rating) + rating = PostQueryBuilder.new(tag_string).find_metatag(:rating) + + if rating.present? self.rating = rating.downcase.first end end diff --git a/app/models/user_event.rb b/app/models/user_event.rb index bb9b37006..3894251f9 100644 --- a/app/models/user_event.rb +++ b/app/models/user_event.rb @@ -33,8 +33,7 @@ class UserEvent < ApplicationRecord def self.search(params) q = search_attributes(params, :id, :created_at, :updated_at, :category, :user, :user_session) - q = q.apply_default_order(params) - q + q.apply_default_order(params) end def self.available_includes diff --git a/app/models/user_upgrade.rb b/app/models/user_upgrade.rb index 2eaead91b..4857fbeda 100644 --- a/app/models/user_upgrade.rb +++ b/app/models/user_upgrade.rb @@ -97,8 +97,7 @@ class UserUpgrade < ApplicationRecord q = q.self_upgrade end - q = q.apply_default_order(params) - q + q.apply_default_order(params) end concerning :UpgradeMethods do