Skip to content

A platform for community discussion. Free, open, simple.

DEV: Enable Style/RedundantSelf rubocop rule (#40098)

Jarek Radosz8baf4d5d4c37
diff --git a/.rubocop.yml b/.rubocop.yml
index d406028e208..ae99f8299d1 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -71,3 +71,6 @@ Style/RedundantBegin:
Rails/FilePath:
Enabled: true
+
+Style/RedundantSelf:
+ Enabled: true
diff --git a/app/controllers/list_controller.rb b/app/controllers/list_controller.rb
index 1ee6eaab59b..a4b7470fad1 100644
--- a/app/controllers/list_controller.rb
+++ b/app/controllers/list_controller.rb
@@ -116,11 +116,11 @@ class ListController < ApplicationController
define_method("category_#{filter}") do
canonical_url "#{Discourse.base_url_no_prefix}#{@category.url}"
- self.public_send(filter, category: @category.id)
+ public_send(filter, category: @category.id)
end
define_method("category_none_#{filter}") do
- self.public_send(filter, category: @category.id, no_subcategories: true)
+ public_send(filter, category: @category.id, no_subcategories: true)
end
end
@@ -148,7 +148,7 @@ class ListController < ApplicationController
view_method = @category.default_view
view_method = "latest" if %w[hot latest top].exclude?(view_method)
- self.public_send(view_method, category: @category.id)
+ public_send(view_method, category: @category.id)
end
def topics_by
@@ -344,12 +344,10 @@ class ListController < ApplicationController
respond_with_list(list)
end
- define_method("category_top_#{period}") do
- self.public_send("top_#{period}", category: @category.id)
- end
+ define_method("category_top_#{period}") { public_send("top_#{period}", category: @category.id) }
define_method("category_none_top_#{period}") do
- self.public_send("top_#{period}", category: @category.id, no_subcategories: true)
+ public_send("top_#{period}", category: @category.id, no_subcategories: true)
end
# rss feed
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 95c67502878..8ef5f7e8c74 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -841,11 +841,7 @@ module ApplicationHelper
name = :"#{name}_rtl" if opts[:supports_rtl] && rtl?
- manager.stylesheet_link_tag(
- name,
- opts[:media] || "all",
- self.method(:add_resource_preload_list),
- )
+ manager.stylesheet_link_tag(name, opts[:media] || "all", method(:add_resource_preload_list))
end
def discourse_preload_color_scheme_stylesheets
diff --git a/app/jobs/base.rb b/app/jobs/base.rb
index 0078c8c3c87..6d0ee67c2eb 100644
--- a/app/jobs/base.rb
+++ b/app/jobs/base.rb
@@ -211,7 +211,7 @@ module Jobs
end
def self.delayed_perform(opts = {})
- self.new.perform(opts)
+ new.perform(opts)
end
def execute(opts = {})
diff --git a/app/jobs/onceoff/onceoff.rb b/app/jobs/onceoff/onceoff.rb
index c795c0b916b..e70e4744fd9 100644
--- a/app/jobs/onceoff/onceoff.rb
+++ b/app/jobs/onceoff/onceoff.rb
@@ -43,7 +43,7 @@ class Jobs::Onceoff < ::Jobs::Base
def self.enqueue_all
previously_ran = OnceoffLog.pluck(:job_name).uniq
- self.onceoff_job_klasses.each do |klass|
+ onceoff_job_klasses.each do |klass|
job_name = name_for(klass)
Jobs.enqueue(job_name.underscore.to_sym) if previously_ran.exclude?(job_name)
end
diff --git a/app/jobs/scheduled/badge_grant.rb b/app/jobs/scheduled/badge_grant.rb
index 99aa2ab14f2..3547328ddbf 100644
--- a/app/jobs/scheduled/badge_grant.rb
+++ b/app/jobs/scheduled/badge_grant.rb
@@ -3,7 +3,7 @@
module Jobs
class BadgeGrant < ::Jobs::Scheduled
def self.run
- self.new.execute(nil)
+ new.execute(nil)
end
every 1.day
diff --git a/app/models/api_key.rb b/app/models/api_key.rb
index 6672dbd2231..325f87f92cc 100644
--- a/app/models/api_key.rb
+++ b/app/models/api_key.rb
@@ -20,7 +20,7 @@ class ApiKey < ActiveRecord::Base
after_initialize :generate_key
def generate_key
- if !self.key_hash
+ if !key_hash
@key ||= SecureRandom.hex(32) # Not saved to DB
self.truncated_key = key[0..3]
self.key_hash = ApiKey.hash_key(key)
diff --git a/app/models/application_request.rb b/app/models/application_request.rb
index 8e70c58f399..962ad285769 100644
--- a/app/models/application_request.rb
+++ b/app/models/application_request.rb
@@ -55,8 +55,8 @@ class ApplicationRequest < ActiveRecord::Base
def self.stats
s = ActiveSupport::HashWithIndifferentAccess.new({})
- self.req_types.each do |key, i|
- query = self.where(req_type: i)
+ req_types.each do |key, i|
+ query = where(req_type: i)
s["#{key}_total"] = query.sum(:count)
s["#{key}_30_days"] = query.where("date > ?", 30.days.ago).sum(:count)
s["#{key}_28_days"] = query.where("date > ?", 28.days.ago).sum(:count)
@@ -67,14 +67,14 @@ class ApplicationRequest < ActiveRecord::Base
end
def self.request_type_count_for_period(type, since)
- id = self.req_types[type]
+ id = req_types[type]
if !id
raise ArgumentError.new(
"unknown request type #{type.inspect} in ApplicationRequest.req_types",
)
end
- self.where(req_type: id).where("date >= ?", since).sum(:count)
+ where(req_type: id).where("date >= ?", since).sum(:count)
end
end
diff --git a/app/models/badge.rb b/app/models/badge.rb
index 56b5206b2f9..8fbbed5980d 100644
--- a/app/models/badge.rb
+++ b/app/models/badge.rb
@@ -126,7 +126,7 @@ class Badge < ActiveRecord::Base
after_save do
if saved_change_to_image_upload_id?
- UploadReference.ensure_exist!(upload_ids: [self.image_upload_id], target: self)
+ UploadReference.ensure_exist!(upload_ids: [image_upload_id], target: self)
end
end
@@ -181,13 +181,13 @@ class Badge < ActiveRecord::Base
end
def clear_user_titles!
- DB.exec(<<~SQL, badge_id: self.id, updated_at: Time.zone.now)
+ DB.exec(<<~SQL, badge_id: id, updated_at: Time.zone.now)
UPDATE users AS u
SET title = '', updated_at = :updated_at
FROM user_profiles AS up
WHERE up.user_id = u.id AND up.granted_title_badge_id = :badge_id
SQL
- DB.exec(<<~SQL, badge_id: self.id)
+ DB.exec(<<~SQL, badge_id: id)
UPDATE user_profiles AS up
SET granted_title_badge_id = NULL
WHERE up.granted_title_badge_id = :badge_id
@@ -197,7 +197,7 @@ class Badge < ActiveRecord::Base
##
# Update all user titles based on a badge to the new name
def update_user_titles!(new_title)
- DB.exec(<<~SQL, granted_title_badge_id: self.id, title: new_title, updated_at: Time.zone.now)
+ DB.exec(<<~SQL, granted_title_badge_id: id, title: new_title, updated_at: Time.zone.now)
UPDATE users AS u
SET title = :title, updated_at = :updated_at
FROM user_profiles AS up
@@ -209,7 +209,7 @@ class Badge < ActiveRecord::Base
# When a badge has its TranslationOverride cleared, reset
# all user titles granted to the standard name.
def reset_user_titles!
- DB.exec(<<~SQL, granted_title_badge_id: self.id, updated_at: Time.zone.now)
+ DB.exec(<<~SQL, granted_title_badge_id: id, updated_at: Time.zone.now)
UPDATE users AS u
SET title = badges.name, updated_at = :updated_at
FROM user_profiles AS up
@@ -246,31 +246,29 @@ class Badge < ActiveRecord::Base
end
def single_grant?
- !self.multiple_grant?
+ !multiple_grant?
end
def default_icon=(val)
- if self.image_upload_id.blank?
+ if image_upload_id.blank?
self.icon ||= val
self.icon = val if self.icon == "certificate"
end
end
def default_allow_title=(val)
- return if !self.new_record?
+ return if !new_record?
self.allow_title = val
end
def default_enabled=(val)
- return if !self.new_record?
+ return if !new_record?
self.enabled = val
end
def default_badge_grouping_id=(val)
# allow to correct orphans
- if !self.badge_grouping_id || self.badge_grouping_id <= BadgeGrouping::Other
- self.badge_grouping_id = val
- end
+ self.badge_grouping_id = val if !badge_grouping_id || badge_grouping_id <= BadgeGrouping::Other
end
def display_name
@@ -310,7 +308,7 @@ class Badge < ActiveRecord::Base
end
def slug
- Slug.for(self.display_name, "-")
+ Slug.for(display_name, "-")
end
def manually_grantable?
@@ -336,7 +334,7 @@ class Badge < ActiveRecord::Base
end
def sanitize_description
- self.description = sanitize_field(self.description) if description_changed?
+ self.description = sanitize_field(description) if description_changed?
end
end
diff --git a/app/models/base_timer.rb b/app/models/base_timer.rb
index d839ac6f0c9..930dd41df0e 100644
--- a/app/models/base_timer.rb
+++ b/app/models/base_timer.rb
@@ -19,7 +19,7 @@ class BaseTimer < ActiveRecord::Base
end
def enqueue_typed_job(time: nil)
- self.send("schedule_auto_#{status_type_name}_job")
+ send("schedule_auto_#{status_type_name}_job")
end
def self.type_job_map
@@ -64,15 +64,15 @@ class BaseTimer < ActiveRecord::Base
end
def public_type?
- !!self.class.public_types[self.status_type]
+ !!self.class.public_types[status_type]
end
def private_type?
- !!self.class.private_types[self.status_type]
+ !!self.class.private_types[status_type]
end
def publishing_to_category?
- self.status_type.to_i == TopicTimer.types[:publish_to_category]
+ status_type.to_i == TopicTimer.types[:publish_to_category]
end
private
diff --git a/app/models/bookmark.rb b/app/models/bookmark.rb
index f7efb6a7293..7446c652a02 100644
--- a/app/models/bookmark.rb
+++ b/app/models/bookmark.rb
@@ -70,13 +70,13 @@ class Bookmark < ActiveRecord::Base
validates :name, length: { maximum: 100 }
def registered_bookmarkable
- Bookmark.registered_bookmarkable_from_type(self.bookmarkable_type)
+ Bookmark.registered_bookmarkable_from_type(bookmarkable_type)
end
def polymorphic_columns_present
- return if self.bookmarkable_id.present? && self.bookmarkable_type.present?
+ return if bookmarkable_id.present? && bookmarkable_type.present?
- self.errors.add(:base, I18n.t("bookmarks.errors.bookmarkable_id_type_required"))
+ errors.add(:base, I18n.t("bookmarks.errors.bookmarkable_id_type_required"))
end
def unique_per_bookmarkable
@@ -88,16 +88,16 @@ class Bookmark < ActiveRecord::Base
return
end
- self.errors.add(:base, I18n.t("bookmarks.errors.already_bookmarked", type: bookmarkable_type))
+ errors.add(:base, I18n.t("bookmarks.errors.already_bookmarked", type: bookmarkable_type))
end
def ensure_sane_reminder_at_time
return if reminder_at.blank?
if reminder_at < Time.zone.now
- self.errors.add(:base, I18n.t("bookmarks.errors.cannot_set_past_reminder"))
+ errors.add(:base, I18n.t("bookmarks.errors.cannot_set_past_reminder"))
end
if reminder_at > 10.years.from_now.utc
- self.errors.add(:base, I18n.t("bookmarks.errors.cannot_set_reminder_in_distant_future"))
+ errors.add(:base, I18n.t("bookmarks.errors.cannot_set_reminder_in_distant_future"))
end
end
@@ -105,7 +105,7 @@ class Bookmark < ActiveRecord::Base
return if user.bookmarks.count < SiteSetting.max_bookmarks_per_user
return if !new_record?
- self.errors.add(
+ errors.add(
:base,
I18n.t(
"bookmarks.errors.too_many",
@@ -116,20 +116,17 @@ class Bookmark < ActiveRecord::Base
end
def valid_bookmarkable_type
- return if Bookmark.valid_bookmarkable_types.include?(self.bookmarkable_type)
+ return if Bookmark.valid_bookmarkable_types.include?(bookmarkable_type)
- self.errors.add(
- :base,
- I18n.t("bookmarks.errors.invalid_bookmarkable", type: self.bookmarkable_type),
- )
+ errors.add(:base, I18n.t("bookmarks.errors.invalid_bookmarkable", type: bookmarkable_type))
end
def auto_delete_when_reminder_sent?
- self.auto_delete_preference == Bookmark.auto_delete_preferences[:when_reminder_sent]
+ auto_delete_preference == Bookmark.auto_delete_preferences[:when_reminder_sent]
end
def auto_clear_reminder_when_reminder_sent?
- self.auto_delete_preference == Bookmark.auto_delete_preferences[:clear_reminder]
+ auto_delete_preference == Bookmark.auto_delete_preferences[:clear_reminder]
end
def reminder_at_ics(offset: 0)
@@ -139,7 +136,7 @@ class Bookmark < ActiveRecord::Base
def clear_reminder!(force_clear_reminder_at: false)
reminder_update_attrs = { reminder_last_sent_at: Time.zone.now, reminder_set_at: nil }
- if self.auto_clear_reminder_when_reminder_sent? || force_clear_reminder_at
+ if auto_clear_reminder_when_reminder_sent? || force_clear_reminder_at
reminder_update_attrs[:reminder_at] = nil
end
@@ -147,7 +144,7 @@ class Bookmark < ActiveRecord::Base
end
def reminder_at_in_zone(timezone)
- self.reminder_at.in_time_zone(timezone)
+ reminder_at.in_time_zone(timezone)
end
scope :with_reminders, -> { where.not(reminder_at: nil) }
diff --git a/app/models/category.rb b/app/models/category.rb
index 0b8eae747b5..6348c0f344a 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -147,10 +147,10 @@ class Category < ActiveRecord::Base
if saved_change_to_uploaded_logo_id? || saved_change_to_uploaded_logo_dark_id? ||
saved_change_to_uploaded_background_id? || saved_change_to_uploaded_background_dark_id?
upload_ids = [
- self.uploaded_logo_id,
- self.uploaded_logo_dark_id,
- self.uploaded_background_id,
- self.uploaded_background_dark_id,
+ uploaded_logo_id,
+ uploaded_logo_dark_id,
+ uploaded_background_id,
+ uploaded_background_dark_id,
]
UploadReference.ensure_exist!(upload_ids: upload_ids, target: self)
end
@@ -430,7 +430,7 @@ class Category < ActiveRecord::Base
end
def top_level?
- self.parent_category_id.nil?
+ parent_category_id.nil?
end
def self.scoped_to_permissions(guardian, permission_types)
@@ -538,11 +538,11 @@ class Category < ActiveRecord::Base
query =
Post
.joins(:topic)
- .where(["topics.category_id = ?", self.id])
+ .where(["topics.category_id = ?", id])
.where("topics.visible = true")
.where("posts.deleted_at IS NULL")
.where("posts.user_deleted = false")
- self.topic_id ? query.where.not(topics: { id: self.topic_id }) : query
+ topic_id ? query.where.not(topics: { id: topic_id }) : query
end
# Internal: Generate the text of post prompting to enter category description.
@@ -576,19 +576,19 @@ class Category < ActiveRecord::Base
def revise_category_definition
return if skip_category_definition
- return if self.topic.blank? || self.topic.first_post.blank?
+ return if topic.blank? || topic.first_post.blank?
# NOTE: Revising the first post will also update the category description,
# see PostRevisor#update_category_description
- self.topic.first_post.revise(self.user, { raw: self.description }, skip_validations: true)
+ topic.first_post.revise(user, { raw: description }, skip_validations: true)
end
def trash_category_definition
- self.topic&.trash!
+ topic&.trash!
end
def clear_related_site_settings
- SiteSetting.general_category_id = -1 if self.id == SiteSetting.general_category_id
+ SiteSetting.general_category_id = -1 if id == SiteSetting.general_category_id
end
def topic_url
@@ -600,39 +600,39 @@ class Category < ActiveRecord::Base
end
def description_text
- return nil unless self.description
+ return nil unless description
@@cache_text ||= LruRedux::ThreadSafeCache.new(1000)
- @@cache_text.getset(self.description) do
- text = Nokogiri::HTML5.fragment(self.description).text.strip
+ @@cache_text.getset(description) do
+ text = Nokogiri::HTML5.fragment(description).text.strip
ERB::Util.html_escape(text).html_safe
end
end
def description_excerpt
- return nil unless self.description
+ return nil unless description
@@cache_excerpt ||= LruRedux::ThreadSafeCache.new(1000)
- @@cache_excerpt.getset(self.description) { PrettyText.excerpt(description, 300) }
+ @@cache_excerpt.getset(description) { PrettyText.excerpt(description, 300) }
end
def access_category_via_group
Group
.joins(:category_groups)
- .where("category_groups.category_id = ?", self.id)
+ .where("category_groups.category_id = ?", id)
.where("groups.public_admission OR groups.allow_membership_requests")
.order(:allow_membership_requests)
.first
end
def duplicate_slug?
- Category.where(slug: self.slug, parent_category_id: parent_category_id).where.not(id: id).any?
+ Category.where(slug: slug, parent_category_id: parent_category_id).where.not(id: id).any?
end
def ensure_slug
return if name.blank?
- self.name.strip!
+ name.strip!
if slug.present?
# if we don't unescape it first we strip the % from the encoded version
@@ -655,17 +655,17 @@ class Category < ActiveRecord::Base
# only allow to use category itself id.
match_id = /\A(\d+)-category/.match(self.slug)
if match_id.present?
- errors.add(:slug, :invalid) if new_record? || (match_id[1] != self.id.to_s)
+ errors.add(:slug, :invalid) if new_record? || (match_id[1] != id.to_s)
end
end
def slug_for_url
- slug.present? ? self.slug : "#{self.id}-category"
+ slug.presence || "#{id}-category"
end
def publish_category
- if self.read_restricted
- group_ids = self.groups.pluck(:id)
+ if read_restricted
+ group_ids = groups.pluck(:id)
if group_ids.present?
MessageBus.publish(
@@ -684,18 +684,18 @@ class Category < ActiveRecord::Base
def remove_site_settings
SiteSetting.all_settings.each do |s|
- SiteSetting.set(s[:setting], "") if s[:type] == "category" && s[:value].to_i == self.id
+ SiteSetting.set(s[:setting], "") if s[:type] == "category" && s[:value].to_i == id
end
end
def publish_category_deletion
- MessageBus.publish("/categories", deleted_categories: [self.id])
+ MessageBus.publish("/categories", deleted_categories: [id])
end
# This is used in a validation so has to produce accurate results before the
# record has been saved
def height_of_ancestors(max_height = SiteSetting.max_category_nesting)
- parent_id = self.parent_category_id
+ parent_id = parent_category_id
return max_height if parent_id == id
@@ -723,7 +723,7 @@ class Category < ActiveRecord::Base
# This is used in a validation so has to produce accurate results before the
# record has been saved
def depth_of_descendants(max_depth = SiteSetting.max_category_nesting)
- parent_id = self.parent_category_id
+ parent_id = parent_category_id
return max_depth if parent_id == id
@@ -835,7 +835,7 @@ class Category < ActiveRecord::Base
def auto_bump_limiter
return nil if num_auto_bump_daily.to_i == 0
- RateLimiter.new(nil, "auto_bump_limit_#{self.id}", 1, 1.day.to_i / num_auto_bump_daily.to_i)
+ RateLimiter.new(nil, "auto_bump_limit_#{id}", 1, 1.day.to_i / num_auto_bump_daily.to_i)
end
def clear_auto_bump_cache!
@@ -870,9 +870,9 @@ class Category < ActiveRecord::Base
.visible
.listable_topics
.exclude_scheduled_bump_topics
- .where(category_id: self.id)
- .where.not(id: self.topic_id)
- .where("bumped_at < ?", (self.auto_bump_cooldown_days || 1).days.ago)
+ .where(category_id: id)
+ .where.not(id: topic_id)
+ .where("bumped_at < ?", (auto_bump_cooldown_days || 1).days.ago)
.where("pinned_at IS NULL AND NOT closed AND NOT archived")
.order("bumped_at ASC")
.limit(1)
@@ -917,15 +917,15 @@ class Category < ActiveRecord::Base
end
def email_in_validator
- return if self.email_in.blank?
+ return if email_in.blank?
email_in
.split("|")
.each do |email|
escaped = Rack::Utils.escape_html(email)
if !Email.is_valid?(email)
- self.errors.add(:base, I18n.t("category.errors.invalid_email_in", email: escaped))
+ errors.add(:base, I18n.t("category.errors.invalid_email_in", email: escaped))
elsif group = Group.find_by_email(email)
- self.errors.add(
+ errors.add(
:base,
I18n.t(
"category.errors.email_already_used_in_group",
@@ -933,8 +933,8 @@ class Category < ActiveRecord::Base
group_name: Rack::Utils.escape_html(group.name),
),
)
- elsif category = Category.where.not(id: self.id).find_by_email(email)
- self.errors.add(
+ elsif category = Category.where.not(id: id).find_by_email(email)
+ errors.add(
:base,
I18n.t(
"category.errors.email_already_used_in_category",
@@ -947,15 +947,15 @@ class Category < ActiveRecord::Base
end
def downcase_name
- self.name_lower = name.downcase if self.name
+ self.name_lower = name.downcase if name
end
def visible_group_names(user)
- self.groups.visible_groups(user)
+ groups.visible_groups(user)
end
def secure_group_ids
- groups.pluck("groups.id") if self.read_restricted?
+ groups.pluck("groups.id") if read_restricted?
end
def update_latest
@@ -964,7 +964,7 @@ class Category < ActiveRecord::Base
.order("posts.created_at desc")
.where("NOT hidden")
.joins("join topics on topics.id = topic_id")
- .where("topics.category_id = :id", id: self.id)
+ .where("topics.category_id = :id", id: id)
.limit(1)
.pluck("posts.id")
.first
@@ -973,30 +973,28 @@ class Category < ActiveRecord::Base
Topic
.order("topics.created_at desc")
.where("visible")
- .where("topics.category_id = :id", id: self.id)
+ .where("topics.category_id = :id", id: id)
.limit(1)
.pluck("topics.id")
.first
- self.update(latest_topic_id: latest_topic_id, latest_post_id: latest_post_id)
+ update(latest_topic_id: latest_topic_id, latest_post_id: latest_post_id)
end
def self.query_parent_category(parent_slug)
encoded_parent_slug = CGI.escape(parent_slug) if SiteSetting.slug_generation_method == "encoded"
- self.where(slug: encoded_parent_slug || parent_slug, parent_category_id: nil).pick(:id) ||
- self.where(id: parent_slug.to_i).pick(:id)
+ where(slug: encoded_parent_slug || parent_slug, parent_category_id: nil).pick(:id) ||
+ where(id: parent_slug.to_i).pick(:id)
end
def self.query_category(slug_or_id, parent_category_id)
encoded_slug_or_id = CGI.escape(slug_or_id) if SiteSetting.slug_generation_method == "encoded"
- self.where(
- slug: encoded_slug_or_id || slug_or_id,
- parent_category_id: parent_category_id,
- ).first || self.where(id: slug_or_id.to_i, parent_category_id: parent_category_id).first
+ where(slug: encoded_slug_or_id || slug_or_id, parent_category_id: parent_category_id).first ||
+ where(id: slug_or_id.to_i, parent_category_id: parent_category_id).first
end
def self.find_by_email(email)
- self.where("string_to_array(email_in, '|') @> ARRAY[?]", Email.downcase(email)).first
+ where("string_to_array(email_in, '|') @> ARRAY[?]", Email.downcase(email)).first
end
def has_children?
@@ -1029,9 +1027,7 @@ class Category < ActiveRecord::Base
end
def url
- @@url_cache.defer_get_set(self.id.to_s) do
- "#{Discourse.base_path}/c/#{slug_path.join("/")}/#{self.id}"
- end
+ @@url_cache.defer_get_set(id.to_s) { "#{Discourse.base_path}/c/#{slug_path.join("/")}/#{id}" }
end
def slug_url_without_id
@@ -1076,7 +1072,7 @@ class Category < ActiveRecord::Base
def index_search
Jobs.enqueue(
:index_category_for_search,
- category_id: self.id,
+ category_id: id,
force: saved_change_to_attribute?(:name),
)
end
@@ -1190,46 +1186,46 @@ class Category < ActiveRecord::Base
end
def slug_path(parent_ids = Set.new)
- if self.parent_category_id.present?
- if parent_ids.add?(self.parent_category_id)
- self.parent_category.slug_path(parent_ids) << self.slug_for_url
+ if parent_category_id.present?
+ if parent_ids.add?(parent_category_id)
+ parent_category.slug_path(parent_ids) << slug_for_url
else
[]
end
else
- [self.slug_for_url]
+ [slug_for_url]
end
end
def slug_ref(depth: 1)
- if self.parent_category_id.present?
- built_ref = [self.slug]
- parent = self.parent_category
+ if parent_category_id.present?
+ built_ref = [slug]
+ parent = parent_category
while parent.present? && (built_ref.length < depth + 1)
built_ref << parent.slug
parent = parent.parent_category
end
built_ref.reverse.join(Category::SLUG_REF_SEPARATOR)
else
- self.slug
+ slug
end
end
def cannot_delete_reason
- return I18n.t("category.cannot_delete.uncategorized") if self.uncategorized?
- return I18n.t("category.cannot_delete.has_subcategories") if self.has_children?
+ return I18n.t("category.cannot_delete.uncategorized") if uncategorized?
+ return I18n.t("category.cannot_delete.has_subcategories") if has_children?
- if self.topic_count != 0
- oldest_topic = self.topics.where.not(id: self.topic_id).order("created_at ASC").limit(1).first
+ if topic_count != 0
+ oldest_topic = topics.where.not(id: topic_id).order("created_at ASC").limit(1).first
if oldest_topic
I18n.t(
"category.cannot_delete.topic_exists",
- count: self.topic_count,
+ count: topic_count,
topic_link: "<a href=\"#{oldest_topic.url}\">#{CGI.escapeHTML(oldest_topic.title)}</a>",
)
else
# This is a weird case, probably indicating a bug.
- I18n.t("category.cannot_delete.topic_exists_no_oldest", count: self.topic_count)
+ I18n.t("category.cannot_delete.topic_exists_no_oldest", count: topic_count)
end
end
end
@@ -1269,7 +1265,7 @@ class Category < ActiveRecord::Base
end
def ensure_category_setting
- self.build_category_setting if self.category_setting.blank?
+ build_category_setting if category_setting.blank?
end
def group_based_posting_review_mode?(post_type)
diff --git a/app/models/category_tag_stat.rb b/app/models/category_tag_stat.rb
index f94a5862235..50b5741d0ed 100644
--- a/app/models/category_tag_stat.rb
+++ b/app/models/category_tag_stat.rb
@@ -6,15 +6,14 @@ class CategoryTagStat < ActiveRecord::Base
def self.topic_moved(topic, from_category_id, to_category_id)
if from_category_id
- self
- .where(tag_id: topic.tags.map(&:id), category_id: from_category_id)
- .where("topic_count > 0")
- .update_all("topic_count = topic_count - 1")
+ where(tag_id: topic.tags.map(&:id), category_id: from_category_id).where(
+ "topic_count > 0",
+ ).update_all("topic_count = topic_count - 1")
end
if to_category_id
sql = <<~SQL
- UPDATE #{self.table_name}
+ UPDATE #{table_name}
SET topic_count = topic_count + 1
WHERE tag_id in (:tag_ids)
AND category_id = :category_id
@@ -39,7 +38,7 @@ class CategoryTagStat < ActiveRecord::Base
end
def self.ensure_consistency!
- self.update_topic_counts
+ update_topic_counts
end
# Recalculate all topic counts if they got out of sync
diff --git a/app/models/category_user.rb b/app/models/category_user.rb
index 90441743a96..8c361ca8d65 100644
--- a/app/models/category_user.rb
+++ b/app/models/category_user.rb
@@ -5,7 +5,7 @@ class CategoryUser < ActiveRecord::Base
belongs_to :user
def self.lookup(user, level)
- self.where(user: user, notification_level: notification_levels[level])
+ where(user: user, notification_level: notification_levels[level])
end
def self.notification_levels
diff --git a/app/models/color_scheme.rb b/app/models/color_scheme.rb
index 59487a76760..3a606e84394 100644
--- a/app/models/color_scheme.rb
+++ b/app/models/color_scheme.rb
@@ -464,17 +464,15 @@ class ColorScheme < ActiveRecord::Base
def colors=(arr)
@colors_by_name = nil
- arr.each { |c| self.color_scheme_colors << ColorSchemeColor.new(name: c[:name], hex: c[:hex]) }
+ arr.each { |c| color_scheme_colors << ColorSchemeColor.new(name: c[:name], hex: c[:hex]) }
end
def colors_by_name
@colors_by_name ||=
- self
- .colors
- .inject({}) do |sum, c|
- sum[c.name] = c
- sum
- end
+ colors.inject({}) do |sum, c|
+ sum[c.name] = c
+ sum
+ end
end
def clear_colors_cache
@@ -526,7 +524,7 @@ class ColorScheme < ActiveRecord::Base
end
def publish_discourse_stylesheet
- self.class.publish_discourse_stylesheets!(self.id) if self.id
+ self.class.publish_discourse_stylesheets!(id) if id
end
def self.publish_discourse_stylesheets!(id = nil)
@@ -562,7 +560,7 @@ class ColorScheme < ActiveRecord::Base
end
def bump_version
- self.version += 1 if self.id
+ self.version += 1 if id
end
def is_dark?
@@ -580,20 +578,20 @@ class ColorScheme < ActiveRecord::Base
def diverge_from_remote
new_scheme = dup
- new_scheme.colors = self.colors_hashes
+ new_scheme.colors = colors_hashes
new_scheme.via_wizard = false
new_scheme.user_selectable = false
new_scheme.base_scheme_id = nil
new_scheme.skip_publish = true
new_scheme.remote_copy = true
- DistributedMutex.synchronize("color_scheme_diverge_from_remote_#{self.id}") do
- self.reload
- if self.base_scheme.blank?
- self.transaction do
+ DistributedMutex.synchronize("color_scheme_diverge_from_remote_#{id}") do
+ reload
+ if base_scheme.blank?
+ transaction do
new_scheme.save!
self.base_scheme_id = new_scheme.id
- self.save!
+ save!
end
end
end
diff --git a/app/models/concerns/has_post_upload_references.rb b/app/models/concerns/has_post_upload_references.rb
index e17f2c3e599..239adba4a78 100644
--- a/app/models/concerns/has_post_upload_references.rb
+++ b/app/models/concerns/has_post_upload_references.rb
@@ -32,7 +32,7 @@ module HasPostUploadReferences
upload_references =
upload_ids.map do |upload_id|
{
- target_id: self.id,
+ target_id: id,
target_type: self.class.name,
upload_id: upload_id,
created_at: Time.zone.now,
@@ -63,7 +63,7 @@ module HasPostUploadReferences
%r{/uploads/short-url/[a-zA-Z0-9]+(\.[a-z0-9]+)?},
]
- fragments ||= Nokogiri::HTML5.fragment(self.cooked)
+ fragments ||= Nokogiri::HTML5.fragment(cooked)
selectors =
fragments.css(
diff --git a/app/models/concerns/has_search_data.rb b/app/models/concerns/has_search_data.rb
index f96b4106022..ca31e150d44 100644
--- a/app/models/concerns/has_search_data.rb
+++ b/app/models/concerns/has_search_data.rb
@@ -4,7 +4,7 @@ module HasSearchData
extend ActiveSupport::Concern
included do
- _associated_record_name = self.name.sub("SearchData", "").underscore
+ _associated_record_name = name.sub("SearchData", "").underscore
self.primary_key = "#{_associated_record_name}_id"
belongs_to _associated_record_name.to_sym
validates :search_data, presence: true
diff --git a/app/models/concerns/has_url.rb b/app/models/concerns/has_url.rb
index d11aa69321e..407de22d03f 100644
--- a/app/models/concerns/has_url.rb
+++ b/app/models/concerns/has_url.rb
@@ -32,18 +32,18 @@ module HasUrl
if data.blank?
result = nil
- result ||= self.find_by(url: uri.path)
+ result ||= find_by(url: uri.path)
return result
end
result = nil
- if self.name == "Upload"
+ if name == "Upload"
sha1 = data[2]
- result = self.find_by(sha1: sha1) if sha1&.length == Upload::SHA1_LENGTH
+ result = find_by(sha1: sha1) if sha1&.length == Upload::SHA1_LENGTH
end
- result || self.find_by("url LIKE ?", "%#{data[1]}")
+ result || find_by("url LIKE ?", "%#{data[1]}")
end
def get_from_urls(upload_urls)
@@ -64,11 +64,11 @@ module HasUrl
if data = extract_url(uri.path).presence
urls << data[1]
- sha1s << data[2] if self.name == "Upload"
+ sha1s << data[2] if name == "Upload"
end
end
- self.where(url: urls).or(self.where(sha1: sha1s))
+ where(url: urls).or(where(sha1: sha1s))
end
end
end
diff --git a/app/models/concerns/reviewable_action_builder.rb b/app/models/concerns/reviewable_action_builder.rb
index 55a22c6b5e6..d563f02445a 100644
--- a/app/models/concerns/reviewable_action_builder.rb
+++ b/app/models/concerns/reviewable_action_builder.rb
@@ -82,7 +82,7 @@ module ReviewableActionBuilder
end
def perform_delete_post(performed_by, _args)
- PostDestroyer.new(performed_by, target_post, reviewable_id: self.id).destroy
+ PostDestroyer.new(performed_by, target_post, reviewable_id: id).destroy
create_result(:success, :rejected, [created_by_id], false)
end
@@ -149,7 +149,7 @@ module ReviewableActionBuilder
def delete_user(user, delete_options, performed_by)
email = user.email
- UserDestroyer.new(performed_by).destroy(user, delete_options.merge(reviewable_id: self.id))
+ UserDestroyer.new(performed_by).destroy(user, delete_options.merge(reviewable_id: id))
message = UserNotifications.account_deleted(email, self)
Email::Sender.new(message, :account_deleted).send
diff --git a/app/models/concerns/roleable.rb b/app/models/concerns/roleable.rb
index bbabd1b6240..54a84092436 100644
--- a/app/models/concerns/roleable.rb
+++ b/app/models/concerns/roleable.rb
@@ -54,13 +54,13 @@ module Roleable
def save_and_refresh_staff_groups!
transaction do
- self.save!
+ save!
Group.refresh_automatic_groups!(:admins, :moderators, :staff)
end
end
def set_permission(permission_name, value)
- self.public_send("#{permission_name}=", value)
+ public_send("#{permission_name}=", value)
save_and_refresh_staff_groups!
end
@@ -83,7 +83,7 @@ module Roleable
reviewable.perform(Discourse.system_user, :approve_user, send_email: false)
else
ReviewableUser.set_approved_fields!(self, Discourse.system_user)
- self.save!
+ save!
end
end
end
diff --git a/app/models/concerns/searchable.rb b/app/models/concerns/searchable.rb
index aaea8d98451..211d14ef657 100644
--- a/app/models/concerns/searchable.rb
+++ b/app/models/concerns/searchable.rb
@@ -5,5 +5,5 @@ module Searchable
PRIORITIES = Enum.new(ignore: 1, very_low: 2, low: 3, normal: 0, high: 4, very_high: 5)
- included { has_one :"#{self.name.underscore}_search_data", dependent: :destroy }
+ included { has_one :"#{name.underscore}_search_data", dependent: :destroy }
end
diff --git a/app/models/concerns/second_factor_manager.rb b/app/models/concerns/second_factor_manager.rb
index cd92db95e72..cf3d78649a7 100644
--- a/app/models/concerns/second_factor_manager.rb
+++ b/app/models/concerns/second_factor_manager.rb
@@ -20,11 +20,9 @@ module SecondFactorManager
def create_totp(opts = {})
require_rotp
UserSecondFactor.create!(
- {
- user_id: self.id,
- method: UserSecondFactor.methods[:totp],
- data: ROTP::Base32.random,
- }.merge(opts),
+ { user_id: id, method: UserSecondFactor.methods[:totp], data: ROTP::Base32.random }.merge(
+ opts,
+ ),
)
end
@@ -34,11 +32,11 @@ module SecondFactorManager
end
def totp_provisioning_uri(data)
- get_totp_object(data).provisioning_uri(self.email)
+ get_totp_object(data).provisioning_uri(email)
end
def authenticate_totp(token)
- totps = self.user_second_factors&.totps
+ totps = user_second_factors&.totps
authenticated = false
totps.each do |totp|
last_used = 0
@@ -64,26 +62,26 @@ module SecondFactorManager
def totp_enabled?
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
- self.user_second_factors&.totps&.exists?
+ user_second_factors&.totps&.exists?
end
def backup_codes_enabled?
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
- self.user_second_factors&.backup_codes&.exists?
+ user_second_factors&.backup_codes&.exists?
end
def security_keys_enabled?
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
- self
- .security_keys
- &.where(factor_type: UserSecurityKey.factor_types[:second_factor], enabled: true)
- &.exists?
+ security_keys&.where(
+ factor_type: UserSecurityKey.factor_types[:second_factor],
+ enabled: true,
+ )&.exists?
end
def passkeys_for_2fa_enabled?
SiteSetting.allow_passkeys_for_2fa && SiteSetting.enable_passkeys &&
!SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
- self.security_keys&.where(factor_type: UserSecurityKey.factor_types[:first_factor])&.exists?
+ security_keys&.where(factor_type: UserSecurityKey.factor_types[:first_factor])&.exists?
end
# Passkey-as-2FA (`passkeys_for_2fa_enabled?`) is intentionally excluded:
@@ -111,7 +109,7 @@ module SecondFactorManager
end
def remaining_backup_codes
- self.user_second_factors&.backup_codes&.count
+ user_second_factors&.backup_codes&.count
end
def authenticate_second_factor(params, server_session)
@@ -237,10 +235,10 @@ module SecondFactorManager
{ salt: salt, code_hash: hash_backup_code(code, salt) }
end
- if self.user_second_factors.backup_codes.empty?
+ if user_second_factors.backup_codes.empty?
create_backup_codes(codes_json)
else
- self.user_second_factors.where(method: UserSecondFactor.methods[:backup_codes]).destroy_all
+ user_second_factors.where(method: UserSecondFactor.methods[:backup_codes]).destroy_all
create_backup_codes(codes_json)
end
@@ -250,7 +248,7 @@ module SecondFactorManager
def create_backup_codes(codes)
codes.each do |code|
UserSecondFactor.create!(
- user_id: self.id,
+ user_id: id,
data: code.to_json,
enabled: true,
method: UserSecondFactor.methods[:backup_codes],
@@ -260,7 +258,7 @@ module SecondFactorManager
def authenticate_backup_code(backup_code)
if backup_code.present?
- codes = self.user_second_factors&.backup_codes
+ codes = user_second_factors&.backup_codes
codes.each do |code|
parsed_data = JSON.parse(code.data)
diff --git a/app/models/concerns/trashable.rb b/app/models/concerns/trashable.rb
index bc75463de7c..d433f49a2af 100644
--- a/app/models/concerns/trashable.rb
+++ b/app/models/concerns/trashable.rb
@@ -32,6 +32,6 @@ module Trashable
private
def trash_update(deleted_at, deleted_by_id)
- self.update_columns(deleted_at: deleted_at, deleted_by_id: deleted_by_id)
+ update_columns(deleted_at: deleted_at, deleted_by_id: deleted_by_id)
end
end
diff --git a/app/models/custom_emoji.rb b/app/models/custom_emoji.rb
index a88fa4bfa7e..64e5440edb3 100644
--- a/app/models/custom_emoji.rb
+++ b/app/models/custom_emoji.rb
@@ -14,7 +14,7 @@ class CustomEmoji < ActiveRecord::Base
after_save do
if saved_change_to_upload_id?
- UploadReference.ensure_exist!(upload_ids: [self.upload_id], target: self)
+ UploadReference.ensure_exist!(upload_ids: [upload_id], target: self)
end
end
diff --git a/app/models/draft.rb b/app/models/draft.rb
index 87e604462cd..151308747b0 100644
--- a/app/models/draft.rb
+++ b/app/models/draft.rb
@@ -193,8 +193,8 @@ class Draft < ActiveRecord::Base
topic_ids = drafts.map(&:topic_id)
post_ids = drafts.map(&:post_id)
- topics = self.allowed_draft_topics_for_user(user).where(id: topic_ids)
- posts = self.allowed_draft_posts_for_user(user).where(id: post_ids)
+ topics = allowed_draft_topics_for_user(user).where(id: topic_ids)
+ posts = allowed_draft_posts_for_user(user).where(id: post_ids)
drafts.each do |draft|
draft.preload_topic(topics.detect { |t| t.id == draft.topic_id })
@@ -210,7 +210,7 @@ class Draft < ActiveRecord::Base
def self.allowed_draft_posts_for_user(user)
# .secured handles whispers, merge handles topic/pm visibility
- Post.secured(Guardian.new(user)).joins(:topic).merge(self.allowed_draft_topics_for_user(user))
+ Post.secured(Guardian.new(user)).joins(:topic).merge(allowed_draft_topics_for_user(user))
end
def self.stream(opts = nil)
@@ -341,7 +341,7 @@ class Draft < ActiveRecord::Base
end
def update_draft_count
- UserStat.update_draft_count(self.user_id)
+ UserStat.update_draft_count(user_id)
end
end
diff --git a/app/models/email_change_request.rb b/app/models/email_change_request.rb
index add48196960..4502f14f556 100644
--- a/app/models/email_change_request.rb
+++ b/app/models/email_change_request.rb
@@ -22,11 +22,11 @@ class EmailChangeRequest < ActiveRecord::Base
end
def requested_by_admin?
- self.requested_by&.admin? && !self.requested_by_self?
+ requested_by&.admin? && !requested_by_self?
end
def requested_by_self?
- self.requested_by_user_id == self.user_id
+ requested_by_user_id == user_id
end
end
diff --git a/app/models/email_log.rb b/app/models/email_log.rb
index 9cf79c09714..7d506642edd 100644
--- a/app/models/email_log.rb
+++ b/app/models/email_log.rb
@@ -37,8 +37,8 @@ class EmailLog < ActiveRecord::Base
SQL
before_save do
- if self.bounce_error_code.present?
- match = SMTP_ERROR_CODE_REGEXP.match(self.bounce_error_code)
+ if bounce_error_code.present?
+ match = SMTP_ERROR_CODE_REGEXP.match(bounce_error_code)
self.bounce_error_code = match.present? ? match[0] : nil
end
end
@@ -49,7 +49,7 @@ class EmailLog < ActiveRecord::Base
end
def topic
- @topic ||= self.topic_id.present? ? Topic.find_by(id: self.topic_id) : self.post&.topic
+ @topic ||= topic_id.present? ? Topic.find_by(id: topic_id) : post&.topic
end
def self.unique_email_per_post(post, user)
@@ -82,11 +82,11 @@ class EmailLog < ActiveRecord::Base
end
def self.for(reply_key)
- self.find_by(reply_key: reply_key)
+ find_by(reply_key: reply_key)
end
def self.last_sent_email_address
- self.where(email_type: "signup").order(created_at: :desc).limit(1).pluck(:to_address).first
+ where(email_type: "signup").order(created_at: :desc).limit(1).pluck(:to_address).first
end
def bounce_key
@@ -94,26 +94,26 @@ class EmailLog < ActiveRecord::Base
end
def cc_users
- return [] if !self.cc_user_ids
- @cc_users ||= User.where(id: self.cc_user_ids)
+ return [] if !cc_user_ids
+ @cc_users ||= User.where(id: cc_user_ids)
end
def cc_addresses_split
- @cc_addresses_split ||= self.cc_addresses&.split(";") || []
+ @cc_addresses_split ||= cc_addresses&.split(";") || []
end
def as_mail_message
- return if self.raw.blank?
- @mail_message ||= Mail.new(self.raw)
+ return if raw.blank?
+ @mail_message ||= Mail.new(raw)
end
def raw_headers
- return if self.raw.blank?
+ return if raw.blank?
as_mail_message.header.raw_source
end
def raw_body
- return if self.raw.blank?
+ return if raw.blank?
as_mail_message.body
end
end
diff --git a/app/models/email_token.rb b/app/models/email_token.rb
index 723de3f216a..d44e61473ea 100644
--- a/app/models/email_token.rb
+++ b/app/models/email_token.rb
@@ -18,7 +18,7 @@ class EmailToken < ActiveRecord::Base
end
after_initialize do
- if self.token_hash.blank?
+ if token_hash.blank?
@token ||= SecureRandom.hex
self.token_hash = self.class.hash_token(@token)
end
@@ -26,18 +26,16 @@ class EmailToken < ActiveRecord::Base
after_create do
EmailToken
- .where(user_id: self.user_id)
- .where(scope: [nil, self.scope])
- .where.not(id: self.id)
+ .where(user_id: user_id)
+ .where(scope: [nil, scope])
+ .where.not(id: id)
.update_all(expired: true)
end
- before_validation { self.email = self.email.downcase if self.email }
+ before_validation { self.email = email.downcase if email }
before_save do
- if self.scope.blank?
- Discourse.deprecate("EmailToken#scope cannot be empty.", output_in_test: true)
- end
+ Discourse.deprecate("EmailToken#scope cannot be empty.", output_in_test: true) if scope.blank?
end
def self.scopes
diff --git a/app/models/embeddable_host.rb b/app/models/embeddable_host.rb
index af313c6898a..c3cac8a0b29 100644
--- a/app/models/embeddable_host.rb
+++ b/app/models/embeddable_host.rb
@@ -9,8 +9,8 @@ class EmbeddableHost < ActiveRecord::Base
after_destroy :reset_embedding_settings
before_validation do
- self.host.sub!(%r{\Ahttps?://}, "")
- self.host.sub!(%r{/.*\z}, "")
+ host.sub!(%r{\Ahttps?://}, "")
+ host.sub!(%r{/.*\z}, "")
end
def self.record_for_url(uri)
diff --git a/app/models/external_upload_stub.rb b/app/models/external_upload_stub.rb
index 16a41a85867..dd01160ca8e 100644
--- a/app/models/external_upload_stub.rb
+++ b/app/models/external_upload_stub.rb
@@ -36,7 +36,7 @@ class ExternalUploadStub < ActiveRecord::Base
before_create do
self.unique_identifier = SecureRandom.uuid
- self.status = ExternalUploadStub.statuses[:created] if self.status.blank?
+ self.status = ExternalUploadStub.statuses[:created] if status.blank?
end
def self.statuses
diff --git a/app/models/flag.rb b/app/models/flag.rb
index 86ab15e1f84..28b1adffb8c 100644
--- a/app/models/flag.rb
+++ b/app/models/flag.rb
@@ -20,8 +20,8 @@ class Flag < ActiveRecord::Base
end
def used?
- PostAction.exists?(post_action_type_id: self.id) ||
- ReviewableScore.exists?(reviewable_score_type: self.id)
+ PostAction.exists?(post_action_type_id: id) ||
+ ReviewableScore.exists?(reviewable_score_type: id)
end
def self.valid_applies_to_types
@@ -48,11 +48,11 @@ class Flag < ActiveRecord::Base
end
def system?
- self.id.present? && self.id < MAX_SYSTEM_FLAG_ID
+ id.present? && id < MAX_SYSTEM_FLAG_ID
end
def applies_to?(type)
- self.applies_to.include?(type)
+ applies_to.include?(type)
end
private
@@ -62,12 +62,12 @@ class Flag < ActiveRecord::Base
end
def set_position
- self.position = Flag.maximum(:position).to_i + 1 if !self.position
+ self.position = Flag.maximum(:position).to_i + 1 if !position
end
def set_name_key
- prefix = self.system? ? "" : "custom_"
- self.name_key = "#{prefix}#{self.name.squeeze(" ").gsub(" ", "_").gsub(/[^\w]/, "").downcase}"
+ prefix = system? ? "" : "custom_"
+ self.name_key = "#{prefix}#{name.squeeze(" ").gsub(" ", "_").gsub(/[^\w]/, "").downcase}"
end
end
diff --git a/app/models/global_setting.rb b/app/models/global_setting.rb
index 1d7cb57c04d..abd6b8c03f1 100644
--- a/app/models/global_setting.rb
+++ b/app/models/global_setting.rb
@@ -141,7 +141,7 @@ class GlobalSetting
replica_host
replica_port
].each do |s|
- if val = self.public_send("db_#{s}")
+ if val = public_send("db_#{s}")
hash[s] = val
end
end
@@ -154,16 +154,16 @@ class GlobalSetting
hash["host_names"] = hostnames
hash["database"] = db_name
- hash["prepared_statements"] = !!self.db_prepared_statements
+ hash["prepared_statements"] = !!db_prepared_statements
hash["idle_timeout"] = connection_reaper_age if connection_reaper_age.present?
hash["reaping_frequency"] = connection_reaper_interval if connection_reaper_interval.present?
- hash["advisory_locks"] = !!self.db_advisory_locks
+ hash["advisory_locks"] = !!db_advisory_locks
db_variables = provider.keys.filter { |k| k.to_s.starts_with? "db_variables_" }
if db_variables.length > 0
hash["variables"] = {}
db_variables.each do |k|
- hash["variables"][k.slice(("db_variables_".length)..)] = self.public_send(k)
+ hash["variables"][k.slice(("db_variables_".length)..)] = public_send(k)
end
end
@@ -259,7 +259,7 @@ class GlobalSetting
end
def self.add_default(name, default)
- define_singleton_method(name) { default } unless self.respond_to? name
+ define_singleton_method(name) { default } unless respond_to? name
end
def self.smtp_settings
@@ -338,7 +338,7 @@ class GlobalSetting
end
def self.parse(file)
- provider = self.new(file)
+ provider = new(file)
provider.read
provider
end
diff --git a/app/models/group.rb b/app/models/group.rb
index 1146e1659ca..71f37404628 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -71,7 +71,7 @@ class Group < ActiveRecord::Base
after_save do
if saved_change_to_flair_upload_id?
- UploadReference.ensure_exist!(upload_ids: [self.flair_upload_id], target: self)
+ UploadReference.ensure_exist!(upload_ids: [flair_upload_id], target: self)
end
end
@@ -303,7 +303,7 @@ class Group < ActiveRecord::Base
lambda { |user, include_public: true|
groups =
where(
- self.mentionable_sql_clause(include_public: include_public),
+ mentionable_sql_clause(include_public: include_public),
levels: alias_levels(user),
user_id: user&.id,
)
@@ -379,40 +379,35 @@ class Group < ActiveRecord::Base
end
def cook_bio
- if self.bio_raw.present?
- self.bio_cooked = PrettyText.cook(self.bio_raw)
+ if bio_raw.present?
+ self.bio_cooked = PrettyText.cook(bio_raw)
else
self.bio_cooked = nil
end
end
def record_email_setting_changes!(user)
- if (self.previous_changes.keys & SMTP_SETTING_ATTRIBUTES).any?
+ if (previous_changes.keys & SMTP_SETTING_ATTRIBUTES).any?
self.smtp_updated_at = Time.zone.now
self.smtp_updated_by_id = user.id
end
- self.smtp_enabled = [
- self.smtp_port,
- self.smtp_server,
- self.email_password,
- self.email_username,
- ].all?(&:present?)
+ self.smtp_enabled = [smtp_port, smtp_server, email_password, email_username].all?(&:present?)
- self.save
+ save
end
def incoming_email_validator
- return if self.automatic || self.incoming_email.blank?
+ return if automatic || incoming_email.blank?
incoming_email
.split("|")
.each do |email|
escaped = Rack::Utils.escape_html(email)
if !Email.is_valid?(email)
- self.errors.add(:base, I18n.t("groups.errors.invalid_incoming_email", email: escaped))
- elsif group = Group.where.not(id: self.id).find_by_email(email)
- self.errors.add(
+ errors.add(:base, I18n.t("groups.errors.invalid_incoming_email", email: escaped))
+ elsif group = Group.where.not(id: id).find_by_email(email)
+ errors.add(
:base,
I18n.t(
"groups.errors.email_already_used_in_group",
@@ -421,7 +416,7 @@ class Group < ActiveRecord::Base
),
)
elsif category = Category.find_by_email(email)
- self.errors.add(
+ errors.add(
:base,
I18n.t(
"groups.errors.email_already_used_in_category",
@@ -465,7 +460,7 @@ class Group < ActiveRecord::Base
.where.not(topics: { archetype: Archetype.private_message })
.where("topics.visible")
.where(post_type: Post.types[:regular])
- .where("group_mentions.group_id = ?", self.id)
+ .where("group_mentions.group_id = ?", id)
if opts[:category_id].present?
result = result.where("topics.category_id = ?", opts[:category_id].to_i)
@@ -534,7 +529,7 @@ class Group < ActiveRecord::Base
def self.refresh_automatic_group!(name)
return unless id = AUTO_GROUPS[name]
- unless group = self.lookup_group(name)
+ unless group = lookup_group(name)
group = Group.new(name: name.to_s, automatic: true)
if AUTO_GROUPS[:moderators] == id
@@ -869,15 +864,15 @@ class Group < ActiveRecord::Base
end
def add_owner(user)
- if group_user = self.group_users.find_by(user: user)
+ if group_user = group_users.find_by(user: user)
group_user.update!(owner: true) if !group_user.owner
else
- self.group_users.create!(user: user, owner: true)
+ group_users.create!(user: user, owner: true)
end
end
def self.find_by_email(email)
- self.where(
+ where(
"email_username = :email OR
string_to_array(incoming_email, '|') @> ARRAY[:email] OR
email_from_alias = :email",
@@ -901,7 +896,7 @@ class Group < ActiveRecord::Base
FROM group_users gu
WHERE gu.group_id = g.id
AND gu.user_id > 0)
- WHERE g.id = #{self.id};
+ WHERE g.id = #{id};
SQL
end
@@ -920,7 +915,7 @@ class Group < ActiveRecord::Base
end
def staff?
- STAFF_GROUPS.include?(self.name.to_sym)
+ STAFF_GROUPS.include?(name.to_sym)
end
def self.member_of(groups, user)
@@ -931,7 +926,7 @@ class Group < ActiveRecord::Base
end
def self.owner_of(groups, user)
- self.member_of(groups, user).where("gu.owner")
+ member_of(groups, user).where("gu.owner")
end
def cache_group_users_for_destroyed_event
@@ -1013,21 +1008,21 @@ class Group < ActiveRecord::Base
user,
owner ? :user_added_to_group_as_owner : :user_added_to_group_as_member,
group_name: name_full_preferred,
- group_path: "/g/#{self.name}",
+ group_path: "/g/#{name}",
)
end
def name_full_preferred
- self.full_name.presence || self.name
+ full_name.presence || name
end
def message_count
- return 0 unless self.has_messages
- TopicAllowedGroup.where(group_id: self.id).joins(:topic).count
+ return 0 unless has_messages
+ TopicAllowedGroup.where(group_id: id).joins(:topic).count
end
def full_url
- "#{Discourse.base_url}/g/#{UrlHelper.encode_component(self.name)}"
+ "#{Discourse.base_url}/g/#{UrlHelper.encode_component(name)}"
end
protected
@@ -1038,17 +1033,16 @@ class Group < ActiveRecord::Base
# avoid strip! here, it works now
# but may not continue to work long term, especially
# once we start returning frozen strings
- if self.name != (stripped = self.name.unicode_normalize.strip)
+ if name != (stripped = name.unicode_normalize.strip)
self.name = stripped
end
UsernameValidator.perform_validation(self, "name", skip_length_validation: automatic) ||
begin
- normalized_name = User.normalize_username(self.name)
+ normalized_name = User.normalize_username(name)
- if self.will_save_change_to_name? &&
- User.normalize_username(self.name_was) != normalized_name &&
- User.username_exists?(self.name)
+ if will_save_change_to_name? && User.normalize_username(name_was) != normalized_name &&
+ User.username_exists?(name)
errors.add(:name, I18n.t("activerecord.errors.messages.taken"))
end
end
@@ -1061,22 +1055,22 @@ class Group < ActiveRecord::Base
end
def automatic_membership_email_domains_validator
- return if self.automatic_membership_email_domains.blank?
+ return if automatic_membership_email_domains.blank?
domains =
- Group.get_valid_email_domains(self.automatic_membership_email_domains) do |domain|
- self.errors.add :base, I18n.t("groups.errors.invalid_domain", domain: domain)
+ Group.get_valid_email_domains(automatic_membership_email_domains) do |domain|
+ errors.add :base, I18n.t("groups.errors.invalid_domain", domain: domain)
end
max_domains = SiteSetting.max_automatic_membership_email_domains
if domains.size > max_domains
- self.errors.add :base, I18n.t("groups.errors.too_many_domains", max: max_domains)
+ errors.add :base, I18n.t("groups.errors.too_many_domains", max: max_domains)
end
domains.each do |domain|
if domain.length > MAX_EMAIL_DOMAIN_LENGTH
- self.errors.add :base, I18n.t("groups.errors.invalid_domain", domain: domain)
+ errors.add :base, I18n.t("groups.errors.invalid_domain", domain: domain)
end
end
@@ -1099,15 +1093,15 @@ class Group < ActiveRecord::Base
end
def automatic_group_membership
- if self.automatic_membership_email_domains.present?
- Jobs.enqueue(:automatic_group_membership, group_id: self.id)
+ if automatic_membership_email_domains.present?
+ Jobs.enqueue(:automatic_group_membership, group_id: id)
end
end
def update_title
- return if new_record? && !self.title.present?
+ return if new_record? && !title.present?
- if self.saved_change_to_title?
+ if saved_change_to_title?
sql = <<~SQL
UPDATE users
SET title = :title
@@ -1121,9 +1115,9 @@ class Group < ActiveRecord::Base
end
def update_primary_group
- return if new_record? && !self.primary_group?
+ return if new_record? && !primary_group?
- if self.saved_change_to_primary_group?
+ if saved_change_to_primary_group?
sql = <<~SQL
UPDATE users
/*set*/
@@ -1201,10 +1195,10 @@ class Group < ActiveRecord::Base
end
def validate_grant_trust_level
- unless TrustLevel.valid?(self.grant_trust_level)
- self.errors.add(
+ unless TrustLevel.valid?(grant_trust_level)
+ errors.add(
:base,
- I18n.t("groups.errors.grant_trust_level_not_valid", trust_level: self.grant_trust_level),
+ I18n.t("groups.errors.grant_trust_level_not_valid", trust_level: grant_trust_level),
)
end
end
@@ -1213,21 +1207,17 @@ class Group < ActiveRecord::Base
valid = true
valid =
- if self.persisted?
- self.group_users.where(owner: true).exists?
+ if persisted?
+ group_users.where(owner: true).exists?
else
- self.group_users.any?(&:owner)
+ group_users.any?(&:owner)
end
- self.errors.add(:base, I18n.t("groups.errors.cant_allow_membership_requests")) if !valid
+ errors.add(:base, I18n.t("groups.errors.cant_allow_membership_requests")) if !valid
end
def enqueue_update_mentions_job
- Jobs.enqueue(
- :update_group_mentions,
- previous_name: self.name_before_last_save,
- group_id: self.id,
- )
+ Jobs.enqueue(:update_group_mentions, previous_name: name_before_last_save, group_id: id)
end
end
diff --git a/app/models/group_category_notification_default.rb b/app/models/group_category_notification_default.rb
index 705c92d2a0a..151b86b3470 100644
--- a/app/models/group_category_notification_default.rb
+++ b/app/models/group_category_notification_default.rb
@@ -9,7 +9,7 @@ class GroupCategoryNotificationDefault < ActiveRecord::Base
end
def self.lookup(group, level)
- self.where(group: group, notification_level: notification_levels[level])
+ where(group: group, notification_level: notification_levels[level])
end
def self.batch_set(group, level, category_ids)
diff --git a/app/models/group_history.rb b/app/models/group_history.rb
index 49dc5e66fbf..fd518bbdbca 100644
--- a/app/models/group_history.rb
+++ b/app/models/group_history.rb
@@ -26,16 +26,13 @@ class GroupHistory < ActiveRecord::Base
def self.with_filters(group, params = {})
records =
- self
- .includes(:acting_user, :target_user)
- .where(group_id: group.id)
- .order("group_histories.created_at DESC")
+ includes(:acting_user, :target_user).where(group_id: group.id).order(
+ "group_histories.created_at DESC",
+ )
if params.present?
params = params.slice(*filters)
- records = records.where(action: self.actions[params[:action].to_sym]) if params[
- :action
- ].present?
+ records = records.where(action: actions[params[:action].to_sym]) if params[:action].present?
records = records.where(subject: params[:subject]) if params[:subject].present?
%i[acting_user target_user].each do |filter|
diff --git a/app/models/group_tag_notification_default.rb b/app/models/group_tag_notification_default.rb
index c39cef3cca5..cb9f392f9d7 100644
--- a/app/models/group_tag_notification_default.rb
+++ b/app/models/group_tag_notification_default.rb
@@ -9,14 +9,14 @@ class GroupTagNotificationDefault < ActiveRecord::Base
end
def self.lookup(group, level)
- self.where(group: group, notification_level: notification_levels[level])
+ where(group: group, notification_level: notification_levels[level])
end
def self.batch_set(group, level, tag_names)
tag_names ||= []
changed = false
- records = self.where(group: group, notification_level: notification_levels[level])
+ records = where(group: group, notification_level: notification_levels[level])
old_ids = records.pluck(:tag_id)
tag_ids = tag_names.empty? ? [] : Tag.where_name(tag_names).pluck(:id)
diff --git a/app/models/incoming_email.rb b/app/models/incoming_email.rb
index 8e266437ac1..c01683a276e 100644
--- a/app/models/incoming_email.rb
+++ b/app/models/incoming_email.rb
@@ -28,7 +28,7 @@ class IncomingEmail < ActiveRecord::Base
)
SQL
- scope :without_raw, -> { select(self.column_names - ["raw"]) }
+ scope :without_raw, -> { select(column_names - ["raw"]) }
def self.created_via_types
@types ||=
@@ -36,7 +36,7 @@ class IncomingEmail < ActiveRecord::Base
end
def as_mail_message
- @mail_message ||= Mail.new(self.raw)
+ @mail_message ||= Mail.new(raw)
end
def raw_headers
@@ -48,11 +48,11 @@ class IncomingEmail < ActiveRecord::Base
end
def to_addresses_split
- self.to_addresses&.split(";") || []
+ to_addresses&.split(";") || []
end
def cc_addresses_split
- self.cc_addresses&.split(";") || []
+ cc_addresses&.split(";") || []
end
def to_addresses=(to)
diff --git a/app/models/incoming_link.rb b/app/models/incoming_link.rb
index feb47e2e906..ba282c141db 100644
--- a/app/models/incoming_link.rb
+++ b/app/models/incoming_link.rb
@@ -75,9 +75,7 @@ class IncomingLink < ActiveRecord::Base
end
def referer
- if self.incoming_referer
- self.incoming_referer.incoming_domain.to_url + self.incoming_referer.path
- end
+ incoming_referer.incoming_domain.to_url + incoming_referer.path if incoming_referer
end
def domain
diff --git a/app/models/incoming_links_report.rb b/app/models/incoming_links_report.rb
index 9c965ad8d6a..6a1b716ba1f 100644
--- a/app/models/incoming_links_report.rb
+++ b/app/models/incoming_links_report.rb
@@ -20,11 +20,11 @@ class IncomingLinksReport
def as_json(_options = nil)
{
- type: self.type,
- title: I18n.t("reports.#{self.type}.title"),
- xaxis: I18n.t("reports.#{self.type}.xaxis"),
- ytitles: self.y_titles,
- data: self.data,
+ type: type,
+ title: I18n.t("reports.#{type}.title"),
+ xaxis: I18n.t("reports.#{type}.xaxis"),
+ ytitles: y_titles,
+ data: data,
start_date: start_date,
end_date: end_date,
}
diff --git a/app/models/invite.rb b/app/models/invite.rb
index 88560ffa038..1419ac96d35 100644
--- a/app/models/invite.rb
+++ b/app/models/invite.rb
@@ -63,7 +63,7 @@ class Invite < ActiveRecord::Base
return if email.blank?
user = Invite.find_user_by_email(email)
- if user && user.id != self.invited_users&.first&.user_id
+ if user && user.id != invited_users&.first&.user_id
self.email_already_exists = true
errors.add(:base, user_exists_error_msg(email))
end
@@ -76,13 +76,13 @@ class Invite < ActiveRecord::Base
# Even if a domain is specified on the invite, it still counts as
# an invite link.
def is_invite_link?
- self.email.blank?
+ email.blank?
end
# Email invites have specific behaviour and it's easier to visually
# parse is_email_invite? than !is_invite_link?
def is_email_invite?
- self.email.present?
+ email.present?
end
def redeemable?
@@ -90,14 +90,14 @@ class Invite < ActiveRecord::Base
end
def redeemed_by_user?(redeeming_user)
- self.invited_users.exists?(user: redeeming_user)
+ invited_users.exists?(user: redeeming_user)
end
def redeemed?
if is_invite_link?
redemption_count >= max_redemptions_allowed
else
- self.invited_users.count > 0
+ invited_users.count > 0
end
end
@@ -111,11 +111,11 @@ class Invite < ActiveRecord::Base
end
def can_be_redeemed_by?(user)
- return false if !self.redeemable?
+ return false if !redeemable?
return false if redeemed_by_user?(user)
- return true if self.domain.blank? && self.email.blank?
- return true if self.email.present? && email_matches?(user.email)
- self.domain.present? && domain_matches?(user.email)
+ return true if domain.blank? && email.blank?
+ return true if email.present? && email_matches?(user.email)
+ domain.present? && domain_matches?(user.email)
end
def expired?
@@ -293,12 +293,12 @@ class Invite < ActiveRecord::Base
end
def resend_invite
- self.update_columns(
+ update_columns(
updated_at: Time.zone.now,
invalidated_at: nil,
expires_at: SiteSetting.invite_expiry_days.days.from_now,
)
- Jobs.enqueue(:invite_email, invite_id: self.id)
+ Jobs.enqueue(:invite_email, invite_id: id)
end
def limit_invites_per_day
@@ -310,7 +310,7 @@ class Invite < ActiveRecord::Base
end
def ensure_max_redemptions_allowed
- if self.max_redemptions_allowed.nil?
+ if max_redemptions_allowed.nil?
self.max_redemptions_allowed = 1
else
limit =
@@ -322,9 +322,9 @@ class Invite < ActiveRecord::Base
end
)
- if self.email.present? && self.max_redemptions_allowed != 1
+ if email.present? && max_redemptions_allowed != 1
errors.add(:max_redemptions_allowed, I18n.t("invite.max_redemptions_allowed_one"))
- elsif !self.max_redemptions_allowed.between?(1, limit)
+ elsif !max_redemptions_allowed.between?(1, limit)
errors.add(
:max_redemptions_allowed,
I18n.t("invite_link.max_redemptions_limit", max_limit: limit),
@@ -334,25 +334,23 @@ class Invite < ActiveRecord::Base
end
def valid_redemption_count
- if self.redemption_count > self.max_redemptions_allowed
+ if redemption_count > max_redemptions_allowed
errors.add(
:redemption_count,
I18n.t(
"invite.redemption_count_less_than_max",
- max_redemptions_allowed: self.max_redemptions_allowed,
+ max_redemptions_allowed: max_redemptions_allowed,
),
)
end
end
def valid_domain
- return if self.domain.blank?
+ return if domain.blank?
- self.domain.downcase!
+ domain.downcase!
- if self.domain !~ Invite::DOMAIN_REGEX
- self.errors.add(:base, I18n.t("invite.domain_not_allowed_admin"))
- end
+ errors.add(:base, I18n.t("invite.domain_not_allowed_admin")) if domain !~ Invite::DOMAIN_REGEX
end
def user_exists_error_msg(email)
diff --git a/app/models/notification.rb b/app/models/notification.rb
index 5c891c7c631..e0c26f1a8da 100644
--- a/app/models/notification.rb
+++ b/app/models/notification.rb
@@ -74,7 +74,7 @@ class Notification < ActiveRecord::Base
# if we have manually set the notification to high_priority on create then
# make sure that is respected
self.high_priority =
- self.high_priority || Notification.high_priority_types.include?(self.notification_type)
+ high_priority || Notification.high_priority_types.include?(notification_type)
end
def self.consolidate_or_create!(notification_params)
@@ -420,7 +420,7 @@ class Notification < ActiveRecord::Base
end
def unread_high_priority?
- self.high_priority? && !read
+ high_priority? && !read
end
def post_id
@@ -451,7 +451,7 @@ class Notification < ActiveRecord::Base
return if skip_send_email
if user.do_not_disturb?
- ShelvedNotification.create(notification_id: self.id)
+ ShelvedNotification.create(notification_id: id)
else
NotificationEmailer.process_notification(self)
end
diff --git a/app/models/optimized_image.rb b/app/models/optimized_image.rb
index 0501e03b009..cea7c618e53 100644
--- a/app/models/optimized_image.rb
+++ b/app/models/optimized_image.rb
@@ -152,7 +152,7 @@ class OptimizedImage < ActiveRecord::Base
def destroy
OptimizedImage.transaction do
- Discourse.store.remove_optimized_image(self) if self.upload
+ Discourse.store.remove_optimized_image(self) if upload
super
end
end
@@ -330,7 +330,7 @@ class OptimizedImage < ActiveRecord::Base
def self.optimize(operation, from, to, dimensions, opts = {})
method_name = "#{operation}_instructions"
- instructions = self.public_send(method_name.to_sym, from, to, dimensions, opts)
+ instructions = public_send(method_name.to_sym, from, to, dimensions, opts)
convert_with(instructions, to, opts)
end
diff --git a/app/models/post.rb b/app/models/post.rb
index 1162e38a187..533f911ff3f 100644
--- a/app/models/post.rb
+++ b/app/models/post.rb
@@ -254,8 +254,8 @@ class Post < ActiveRecord::Base
end
def trash!(trashed_by = nil)
- self.topic_links.each(&:destroy)
- self.save_custom_fields if self.custom_fields.delete(Post::NOTICE)
+ topic_links.each(&:destroy)
+ save_custom_fields if custom_fields.delete(Post::NOTICE)
super(trashed_by)
end
@@ -332,11 +332,11 @@ class Post < ActiveRecord::Base
# this when cooking #hashtags to determine whether we should render
# the found hashtag based on whether the user can access the category it
# is referencing.
- options[:user_id] = self.last_editor_id
+ options[:user_id] = last_editor_id
options[:omit_nofollow] = true if omit_nofollow?
- options[:post_id] = self.id
+ options[:post_id] = id
- if self.should_secure_uploads?
+ if should_secure_uploads?
each_upload_url do |url|
uri = URI.parse(url)
if FileHelper.is_supported_media?(File.basename(uri.path))
@@ -381,7 +381,7 @@ class Post < ActiveRecord::Base
end
def last_editor
- self.last_editor_id ? (User.find_by_id(self.last_editor_id) || user) : user
+ last_editor_id ? (User.find_by_id(last_editor_id) || user) : user
end
def allowed_spam_hosts
@@ -471,22 +471,22 @@ class Post < ActiveRecord::Base
end
def delete_post_notices
- self.custom_fields.delete(Post::NOTICE)
- self.save_custom_fields
+ custom_fields.delete(Post::NOTICE)
+ save_custom_fields
end
def recover_public_post_actions
PostAction
.publics
.with_deleted
- .where(post_id: self.id, id: self.custom_fields["deleted_public_actions"])
+ .where(post_id: id, id: custom_fields["deleted_public_actions"])
.find_each do |post_action|
post_action.recover!
post_action.save!
end
- self.custom_fields.delete("deleted_public_actions")
- self.save_custom_fields
+ custom_fields.delete("deleted_public_actions")
+ save_custom_fields
end
def filter_quotes(parent_post = nil)
@@ -616,7 +616,7 @@ class Post < ActiveRecord::Base
# consider how it interacts with UploadSecurity and the uploads.rake tasks.
def should_secure_uploads?
return false if !SiteSetting.secure_uploads?
- topic_including_deleted = Topic.with_deleted.find_by(id: self.topic_id)
+ topic_including_deleted = Topic.with_deleted.find_by(id: topic_id)
return false if topic_including_deleted.blank?
# NOTE: This is to be used for plugins where adding a new public upload
@@ -668,7 +668,7 @@ class Post < ActiveRecord::Base
Post.exists?(topic_id: topic_id, hidden: false, post_type: Post.types[:regular])
if is_first_post? || !any_visible_posts_in_topic
- self.topic.update_status(
+ topic.update_status(
"visible",
false,
Discourse.system_user,
@@ -713,18 +713,18 @@ class Post < ActiveRecord::Base
def unhide!
Post.transaction do
- self.update!(hidden: false)
+ update!(hidden: false)
should_update_user_stat = true
# NOTE: We have to consider `nil` a valid reason here because historically
# topics didn't have a visibility_reason_id, if we didn't do this we would
# break backwards compat since we cannot backfill data.
hidden_because_of_op_flagging =
- self.topic.visibility_reason_id == Topic.visibility_reasons[:op_flag_threshold_reached] ||
- self.topic.visibility_reason_id.nil?
+ topic.visibility_reason_id == Topic.visibility_reasons[:op_flag_threshold_reached] ||
+ topic.visibility_reason_id.nil?
if is_first_post? && hidden_because_of_op_flagging
- self.topic.update_status(
+ topic.update_status(
"visible",
true,
Discourse.system_user,
@@ -733,7 +733,7 @@ class Post < ActiveRecord::Base
should_update_user_stat = false
end
- self.topic.reset_bumped_at(self) if is_last_reply? && !whisper?
+ topic.reset_bumped_at(self) if is_last_reply? && !whisper?
# We need to do this because TopicStatusUpdater also does the increment
# and we don't want to double count for the OP.
@@ -897,7 +897,7 @@ class Post < ActiveRecord::Base
old_user = user
revise(
actor,
- { raw: self.raw, user_id: new_user.id, edit_reason: edit_reason },
+ { raw: raw, user_id: new_user.id, edit_reason: edit_reason },
bypass_bump: true,
skip_revision: skip_revision,
skip_validations: true,
@@ -961,10 +961,10 @@ class Post < ActiveRecord::Base
def save_reply_relationships
add_to_quoted_post_numbers(reply_to_post_number)
- return if self.quoted_post_numbers.blank?
+ return if quoted_post_numbers.blank?
# Create a reply relationship between quoted posts and this new post
- self.quoted_post_numbers.each do |p|
+ quoted_post_numbers.each do |p|
post = Post.find_by(topic_id: topic_id, post_number: p)
create_reply_relationship_with(post)
end
@@ -979,14 +979,14 @@ class Post < ActiveRecord::Base
)
args = {
bypass_bump: bypass_bump,
- cooking_options: self.cooking_options,
+ cooking_options: cooking_options,
new_post: new_post,
- post_id: self.id,
+ post_id: id,
skip_pull_hotlinked_images: skip_pull_hotlinked_images,
}
- args[:image_sizes] = image_sizes if self.image_sizes.present?
- args[:invalidate_oneboxes] = true if self.invalidate_oneboxes.present?
+ args[:image_sizes] = image_sizes if image_sizes.present?
+ args[:invalidate_oneboxes] = true if invalidate_oneboxes.present?
args[:queue] = priority.to_s if priority && priority != :normal
Jobs.enqueue(:process_post, args)
@@ -1120,7 +1120,7 @@ class Post < ActiveRecord::Base
def update_uploads_secure_status(source:)
if Discourse.store.external?
- self.uploads.each { |upload| upload.update_secure_status(source: source) }
+ uploads.each { |upload| upload.update_secure_status(source: source) }
end
end
@@ -1193,7 +1193,7 @@ class Post < ActiveRecord::Base
end
def owned_uploads_via_access_control
- Upload.where(access_control_post_id: self.id)
+ Upload.where(access_control_post_id: id)
end
def image_url
@@ -1202,10 +1202,10 @@ class Post < ActiveRecord::Base
end
def cannot_permanently_delete_reason(user)
- if self.deleted_by_id == user&.id && self.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
+ if deleted_by_id == user&.id && deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
time_left =
RateLimiter.time_left(
- Post::PERMANENT_DELETE_TIMER.to_i - Time.zone.now.to_i + self.deleted_at.to_i,
+ Post::PERMANENT_DELETE_TIMER.to_i - Time.zone.now.to_i + deleted_at.to_i,
)
I18n.t("post.cannot_permanently_delete.wait_or_different_admin", time_left: time_left)
end
@@ -1218,15 +1218,15 @@ class Post < ActiveRecord::Base
private
def access_control_post_id_for_upload
- self.id
+ id
end
def handle_video_thumbnail(thumbnail)
- if self.is_first_post? && !self.topic.image_upload_id
- self.topic.update_column(:image_upload_id, thumbnail.id)
+ if is_first_post? && !topic.image_upload_id
+ topic.update_column(:image_upload_id, thumbnail.id)
extra_sizes =
ThemeModifierHelper.new(theme_ids: Theme.user_selectable.pluck(:id)).topic_thumbnail_sizes
- self.topic.generate_thumbnails!(extra_sizes: extra_sizes)
+ topic.generate_thumbnails!(extra_sizes: extra_sizes)
end
end
@@ -1244,10 +1244,10 @@ class Post < ActiveRecord::Base
end
def create_reply_relationship_with(post)
- return if post.nil? || self.deleted_at.present?
+ return if post.nil? || deleted_at.present?
post_reply = post.post_replies.new(reply_post_id: id)
if post_reply.save
- if Topic.visible_post_types.include?(self.post_type)
+ if Topic.visible_post_types.include?(post_type)
Post.where(id: post.id).update_all ["reply_count = reply_count + 1"]
end
end
diff --git a/app/models/post_localization.rb b/app/models/post_localization.rb
index 21760898963..561cdbcc5b8 100644
--- a/app/models/post_localization.rb
+++ b/app/models/post_localization.rb
@@ -18,7 +18,7 @@ class PostLocalization < ActiveRecord::Base
private
def access_control_post_id_for_upload
- self.post_id
+ post_id
end
end
diff --git a/app/models/post_reply.rb b/app/models/post_reply.rb
index 1bde3b55727..ae34902458f 100644
--- a/app/models/post_reply.rb
+++ b/app/models/post_reply.rb
@@ -11,7 +11,7 @@ class PostReply < ActiveRecord::Base
def ensure_same_topic
if post.topic_id != reply.topic_id
- self.errors.add(:base, I18n.t("activerecord.errors.models.post_reply.base.different_topic"))
+ errors.add(:base, I18n.t("activerecord.errors.models.post_reply.base.different_topic"))
end
end
end
diff --git a/app/models/private_message_topic_tracking_state.rb b/app/models/private_message_topic_tracking_state.rb
index 5b9da537b54..d4a6917fe2c 100644
--- a/app/models/private_message_topic_tracking_state.rb
+++ b/app/models/private_message_topic_tracking_state.rb
@@ -147,7 +147,7 @@ class PrivateMessageTopicTrackingState
},
}
- MessageBus.publish(self.user_channel(tu.user_id), message.as_json, user_ids: [tu.user_id])
+ MessageBus.publish(user_channel(tu.user_id), message.as_json, user_ids: [tu.user_id])
end
end
@@ -170,14 +170,14 @@ class PrivateMessageTopicTrackingState
.pluck(:id)
.each do |user_id|
next if user_id == topic.user_id # skip topic creator
- MessageBus.publish(self.user_channel(user_id), message, user_ids: [user_id])
+ MessageBus.publish(user_channel(user_id), message, user_ids: [user_id])
end
topic
.allowed_groups
.pluck(:id)
.each do |group_id|
- MessageBus.publish(self.group_channel(group_id), message, group_ids: [group_id])
+ MessageBus.publish(group_channel(group_id), message, group_ids: [group_id])
end
end
@@ -193,13 +193,13 @@ class PrivateMessageTopicTrackingState
},
}.as_json
- MessageBus.publish(self.group_channel(group_id), message, group_ids: [group_id])
+ MessageBus.publish(group_channel(group_id), message, group_ids: [group_id])
end
def self.publish_read(topic_id, last_read_post_number, user, notification_level = nil)
- self.publish_read_message(
+ publish_read_message(
message_type: READ_MESSAGE_TYPE,
- channel_name: self.user_channel(user.id),
+ channel_name: user_channel(user.id),
topic_id: topic_id,
user: user,
last_read_post_number: last_read_post_number,
diff --git a/app/models/problem_check.rb b/app/models/problem_check.rb
index 4e9c42908bd..20bf1543f02 100644
--- a/app/models/problem_check.rb
+++ b/app/models/problem_check.rb
@@ -222,7 +222,7 @@ class ProblemCheck
target.present? ? translation_data(target) : translation_data,
).symbolize_keys,
),
- priority: self.config.priority,
+ priority: config.priority,
identifier:,
target: target_identifier,
details:,
diff --git a/app/models/remote_theme.rb b/app/models/remote_theme.rb
index 0db7d1bbb83..1faebdcdf0f 100644
--- a/app/models/remote_theme.rb
+++ b/app/models/remote_theme.rb
@@ -206,15 +206,14 @@ class RemoteTheme < ActiveRecord::Base
end
def self.out_of_date_themes
- self
- .joined_remotes
+ joined_remotes
.where("commits_behind > 0 OR remote_version <> local_version")
.where(themes: { enabled: true })
.pluck("themes.name", "themes.id")
end
def self.unreachable_themes
- self.joined_remotes.where.not(last_error_text: nil).pluck("themes.name", "themes.id")
+ joined_remotes.where.not(last_error_text: nil).pluck("themes.name", "themes.id")
end
def out_of_date?
@@ -233,7 +232,7 @@ class RemoteTheme < ActiveRecord::Base
self.remote_version, self.commits_behind = importer.commits_since(local_version)
self.last_error_text = nil
ensure
- self.save!
+ save!
begin
importer.cleanup!
rescue => e
@@ -260,7 +259,7 @@ class RemoteTheme < ActiveRecord::Base
importer.import!
rescue RemoteTheme::ImportError => err
self.last_error_text = err.message
- self.save!
+ save!
return self
else
self.last_error_text = nil
@@ -303,22 +302,17 @@ class RemoteTheme < ActiveRecord::Base
end
# Update all theme attributes if this is just a placeholder
- if self.remote_url.present? && !self.local_version && !self.commits_behind
- self.theme.name = theme_info["name"]
- self.theme.component = [true, "true"].include?(theme_info["component"])
- self.theme.child_components = theme_info["components"].presence || []
+ if remote_url.present? && !local_version && !commits_behind
+ theme.name = theme_info["name"]
+ theme.component = [true, "true"].include?(theme_info["component"])
+ theme.child_components = theme_info["components"].presence || []
end
- METADATA_PROPERTIES.each do |property|
- self.public_send(:"#{property}=", theme_info[property.to_s])
- end
+ METADATA_PROPERTIES.each { |property| public_send(:"#{property}=", theme_info[property.to_s]) }
- if !self.valid?
+ if !valid?
raise ImportError,
- I18n.t(
- "themes.import_error.about_json_values",
- errors: self.errors.full_messages.join(","),
- )
+ I18n.t("themes.import_error.about_json_values", errors: errors.full_messages.join(","))
end
ThemeModifierSet.modifiers.keys.each do |modifier_name|
@@ -393,7 +387,7 @@ class RemoteTheme < ActiveRecord::Base
update_theme_color_schemes(theme, theme_info["color_schemes"]) unless theme.component
- self.save!
+ save!
before_save&.call(theme)
@@ -416,7 +410,7 @@ class RemoteTheme < ActiveRecord::Base
if already_in_transaction
transaction_block.call
else
- self.transaction(&transaction_block)
+ transaction(&transaction_block)
end
theme.theme_modifier_set.save! if theme.theme_modifier_set.refresh_theme_setting_modifiers
diff --git a/app/models/report.rb b/app/models/report.rb
index 3b1a65095a6..67c6e97ff1e 100644
--- a/app/models/report.rb
+++ b/app/models/report.rb
@@ -242,11 +242,11 @@ class Report
end
def prev_start_date
- self.start_date - (self.end_date - self.start_date)
+ start_date - (end_date - start_date)
end
def prev_end_date
- self.start_date
+ start_date
end
def as_json(options = nil)
@@ -263,30 +263,30 @@ class Report
data: data,
start_date: start_date&.iso8601,
end_date: end_date&.iso8601,
- prev_data: self.prev_data,
+ prev_data: prev_data,
prev_start_date: prev_start_date&.iso8601,
prev_end_date: prev_end_date&.iso8601,
- prev30Days: self.prev30Days,
- dates_filtering: self.dates_filtering,
+ prev30Days: prev30Days,
+ dates_filtering: dates_filtering,
report_key: Report.cache_key(self),
- primary_color: self.primary_color,
- secondary_color: self.secondary_color,
- available_filters: self.available_filters.map { |k, v| { id: k }.merge(v) },
+ primary_color: primary_color,
+ secondary_color: secondary_color,
+ available_filters: available_filters.map { |k, v| { id: k }.merge(v) },
labels: labels || Report.default_labels,
- average: self.average,
- percent: self.percent,
- higher_is_better: self.higher_is_better,
- modes: self.modes,
+ average: average,
+ percent: percent,
+ higher_is_better: higher_is_better,
+ modes: modes,
}.tap do |json|
- json[:legacy] = self.legacy if self.legacy
- json[:icon] = self.icon if self.icon
- json[:error] = self.error if self.error
- json[:total] = self.total if self.total
- json[:prev_period] = self.prev_period if self.prev_period
- json[:prev30Days] = self.prev30Days if self.prev30Days
- json[:limit] = self.limit if self.limit
- json[:default_group_by] = self.default_group_by if self.default_group_by
- json[:y_axis_title] = self.y_axis_title if self.y_axis_title
+ json[:legacy] = legacy if legacy
+ json[:icon] = icon if icon
+ json[:error] = error if error
+ json[:total] = total if total
+ json[:prev_period] = prev_period if prev_period
+ json[:prev30Days] = prev30Days if prev30Days
+ json[:limit] = limit if limit
+ json[:default_group_by] = default_group_by if default_group_by
+ json[:y_axis_title] = y_axis_title if y_axis_title
if type == "page_view_crawler_reqs"
json[:related_report] = Report.find(
diff --git a/app/models/reviewable.rb b/app/models/reviewable.rb
index f6dd804ad4f..d8b825b2039 100644
--- a/app/models/reviewable.rb
+++ b/app/models/reviewable.rb
@@ -52,7 +52,7 @@ class Reviewable < ActiveRecord::Base
after_commit(on: :create) { DiscourseEvent.trigger(:reviewable_created, self) }
after_commit(on: %i[create update]) do
- Jobs.enqueue(:notify_reviewable, reviewable_id: self.id) if pending?
+ Jobs.enqueue(:notify_reviewable, reviewable_id: id) if pending?
end
# Can be used if several actions are equivalent
@@ -83,7 +83,7 @@ class Reviewable < ActiveRecord::Base
end
def self.sti_names
- self.types.map(&:sti_name)
+ types.map(&:sti_name)
end
def self.source_for(type)
@@ -228,7 +228,7 @@ class Reviewable < ActiveRecord::Base
rs.save!
update(
- score: self.score + rs.score,
+ score: score + rs.score,
latest_score: rs.created_at,
force_review: self.force_review || force_review,
)
@@ -333,7 +333,7 @@ class Reviewable < ActiveRecord::Base
def update_fields(params, performed_by, version: nil)
return true if params.blank?
- (params[:payload] || {}).each { |k, v| self.payload[k] = v }
+ (params[:payload] || {}).each { |k, v| payload[k] = v }
self.category_id = params[:category_id] if params.has_key?(:category_id)
result = false
@@ -378,7 +378,7 @@ class Reviewable < ActiveRecord::Base
if update_count || result.remove_reviewable_ids.present?
Jobs.enqueue(
:notify_reviewable,
- reviewable_id: self.id,
+ reviewable_id: id,
performing_username: performed_by.username,
updated_reviewable_ids: result.remove_reviewable_ids,
)
@@ -470,7 +470,7 @@ class Reviewable < ActiveRecord::Base
end
def self.unseen_reviewable_count(user)
- self.unseen_list_for(user).count
+ unseen_list_for(user).count
end
def self.list_for(
@@ -631,11 +631,11 @@ class Reviewable < ActiveRecord::Base
end
def basic_serializer
- TYPE_TO_BASIC_SERIALIZER[self.type.to_sym] || BasicReviewableSerializer
+ TYPE_TO_BASIC_SERIALIZER[type.to_sym] || BasicReviewableSerializer
end
def type_class
- Reviewable.sti_class_for(self.type)
+ Reviewable.sti_class_for(type)
end
def self.lookup_serializer_for(type)
@@ -728,7 +728,7 @@ class Reviewable < ActiveRecord::Base
result =
DB.query(
sql,
- id: self.id,
+ id: id,
pending: ReviewableScore.statuses[:pending],
agreed: ReviewableScore.statuses[:agreed],
)
@@ -756,7 +756,7 @@ class Reviewable < ActiveRecord::Base
DiscourseEvent.trigger(:reviewable_score_updated, self)
- self.score
+ score
end
def delete_user_actions(actions, bundle = nil, require_reject_reason: false)
@@ -792,14 +792,14 @@ class Reviewable < ActiveRecord::Base
DB.query_single(
"UPDATE reviewables SET version = version + 1 WHERE id = :id AND version = :version RETURNING version",
version: version,
- id: self.id,
+ id: id,
)
else
# We didn't supply a version to update safely, so just increase it
version_result =
DB.query_single(
"UPDATE reviewables SET version = version + 1 WHERE id = :id RETURNING version",
- id: self.id,
+ id: id,
)
end
diff --git a/app/models/reviewable_flagged_post.rb b/app/models/reviewable_flagged_post.rb
index a1ce92e0eff..c828082c8e6 100644
--- a/app/models/reviewable_flagged_post.rb
+++ b/app/models/reviewable_flagged_post.rb
@@ -257,7 +257,7 @@ class ReviewableFlaggedPost < Reviewable
def perform_delete_and_ignore_replies(performed_by, args)
result = perform_ignore_and_do_nothing(performed_by, args)
- PostDestroyer.delete_with_replies(performed_by, post, self.id)
+ PostDestroyer.delete_with_replies(performed_by, post, id)
result
end
@@ -270,7 +270,7 @@ class ReviewableFlaggedPost < Reviewable
def perform_delete_and_agree_replies(performed_by, args)
result = agree(performed_by, args)
- PostDestroyer.delete_with_replies(performed_by, post, self.id)
+ PostDestroyer.delete_with_replies(performed_by, post, id)
result
end
@@ -345,7 +345,7 @@ class ReviewableFlaggedPost < Reviewable
private
def destroyer(performed_by, post)
- PostDestroyer.new(performed_by, post, reviewable_id: self.id)
+ PostDestroyer.new(performed_by, post, reviewable_id: id)
end
def notify_poster(performed_by)
diff --git a/app/models/reviewable_post.rb b/app/models/reviewable_post.rb
index 2ed8b525893..db41bdae2da 100644
--- a/app/models/reviewable_post.rb
+++ b/app/models/reviewable_post.rb
@@ -115,7 +115,7 @@ class ReviewablePost < Reviewable
end
def perform_reject_and_delete(performed_by, _args)
- PostDestroyer.new(performed_by, post, reviewable_id: self.id).destroy
+ PostDestroyer.new(performed_by, post, reviewable_id: id).destroy
create_result(:success, :rejected, [created_by_id], false)
end
diff --git a/app/models/reviewable_queued_post.rb b/app/models/reviewable_queued_post.rb
index 393d00ad69d..a559224304e 100644
--- a/app/models/reviewable_queued_post.rb
+++ b/app/models/reviewable_queued_post.rb
@@ -13,9 +13,8 @@ class ReviewableQueuedPost < Reviewable
end
after_save do
- if saved_change_to_payload? && self.status.to_sym == :pending &&
- self.payload&.[]("raw").present?
- upload_ids = Upload.extract_upload_ids(self.payload["raw"])
+ if saved_change_to_payload? && status.to_sym == :pending && payload&.[]("raw").present?
+ upload_ids = Upload.extract_upload_ids(payload["raw"])
UploadReference.ensure_exist!(upload_ids: upload_ids, target: self)
end
end
@@ -115,11 +114,11 @@ class ReviewableQueuedPost < Reviewable
save
if target_created_by.silenced?
- UserSilencer.unsilence(target_created_by, performed_by, reviewable_id: self.id)
+ UserSilencer.unsilence(target_created_by, performed_by, reviewable_id: id)
end
if performed_by.staff?
- StaffActionLogger.new(performed_by).log_post_approved(created_post, reviewable_id: self.id)
+ StaffActionLogger.new(performed_by).log_post_approved(created_post, reviewable_id: id)
end
# Backwards compatibility, new code should listen for `reviewable_transitioned_to`
@@ -159,7 +158,7 @@ class ReviewableQueuedPost < Reviewable
def perform_revise_and_reject_post(performed_by, args)
has_contact_user = SiteSetting.site_contact_username.present?
- is_new_topic = self.topic.blank?
+ is_new_topic = topic.blank?
edit_instructions_key =
if is_new_topic && has_contact_user
@@ -173,18 +172,17 @@ class ReviewableQueuedPost < Reviewable
end
pm_translation_args = {
- topic_title: self.topic&.title || self.payload["title"],
- topic_url: self.topic&.url,
+ topic_title: topic&.title || payload["title"],
+ topic_url: topic&.url,
reason: args[:revise_custom_reason].presence || args[:revise_reason],
feedback: args[:revise_feedback],
- original_post: self.payload["raw"],
+ original_post: payload["raw"],
site_name: SiteSetting.title,
- edit_instructions:
- I18n.t(edit_instructions_key, locale: self.target_created_by.effective_locale),
+ edit_instructions: I18n.t(edit_instructions_key, locale: target_created_by.effective_locale),
}
SystemMessage.create(
- self.target_created_by,
+ target_created_by,
(
if is_new_topic
:reviewable_queued_post_revise_and_reject_new_topic
diff --git a/app/models/reviewable_user.rb b/app/models/reviewable_user.rb
index 31fd2e2ff5d..f937e9d8ab2 100644
--- a/app/models/reviewable_user.rb
+++ b/app/models/reviewable_user.rb
@@ -59,7 +59,7 @@ class ReviewableUser < Reviewable
if args[:send_email] != false && SiteSetting.must_approve_users?
Jobs.enqueue(:critical_user_email, type: "signup_after_approval", user_id: target.id)
end
- StaffActionLogger.new(performed_by).log_user_approve(target, reviewable_id: self.id)
+ StaffActionLogger.new(performed_by).log_user_approve(target, reviewable_id: id)
create_result(:success, :approved)
end
@@ -88,7 +88,7 @@ class ReviewableUser < Reviewable
scrubbed_reason: reason,
scrubbed_at:,
}
- self.save!
+ save!
result = create_result(:success)
@@ -109,12 +109,12 @@ class ReviewableUser < Reviewable
self.reject_reason = args[:reject_reason]
# Without this, we end up sending the email even if this reject_reason is too long.
- self.validate!
+ validate!
if args[:send_email] && SiteSetting.must_approve_users?
# Execute job instead of enqueue because user has to exists to send email
Jobs::CriticalUserEmail.new.execute(
- { type: :signup_after_reject, user_id: target.id, reject_reason: self.reject_reason },
+ { type: :signup_after_reject, user_id: target.id, reject_reason: reject_reason },
)
end
@@ -126,7 +126,7 @@ class ReviewableUser < Reviewable
else
I18n.t("user.destroy_reasons.reviewable_reject")
end
- delete_args[:reviewable_id] = self.id
+ delete_args[:reviewable_id] = id
destroyer.destroy(target, delete_args)
rescue UserDestroyer::PostsExistError, Discourse::InvalidAccess
diff --git a/app/models/screened_ip_address.rb b/app/models/screened_ip_address.rb
index 77968143549..a4d3d9cebab 100644
--- a/app/models/screened_ip_address.rb
+++ b/app/models/screened_ip_address.rb
@@ -29,10 +29,10 @@ class ScreenedIpAddress < ActiveRecord::Base
end
def check_for_match
- if self.errors[:ip_address].blank?
- matched = self.class.match_for_ip_address(self.ip_address)
- if matched && matched.action_type == self.action_type
- self.errors.add(:ip_address, :ip_address_already_screened)
+ if errors[:ip_address].blank?
+ matched = self.class.match_for_ip_address(ip_address)
+ if matched && matched.action_type == action_type
+ errors.add(:ip_address, :ip_address_already_screened)
end
end
end
@@ -42,7 +42,7 @@ class ScreenedIpAddress < ActiveRecord::Base
# inet/cidr columns:
def ip_address=(val)
if val.nil?
- self.errors.add(:ip_address, :invalid)
+ errors.add(:ip_address, :invalid)
return
end
@@ -54,7 +54,7 @@ class ScreenedIpAddress < ActiveRecord::Base
v = IPAddr.handle_wildcards(val)
if v.nil?
- self.errors.add(:ip_address, :invalid)
+ errors.add(:ip_address, :invalid)
return
end
@@ -63,7 +63,7 @@ class ScreenedIpAddress < ActiveRecord::Base
# this gets even messier, Ruby 1.9.2 raised a different exception to Ruby 2.0.0
# handle both exceptions
rescue ArgumentError, IPAddr::InvalidAddressError
- self.errors.add(:ip_address, :invalid)
+ errors.add(:ip_address, :invalid)
end
# Return a string with the ip address and mask in standard format. e.g., "127.0.0.0/8".
diff --git a/app/models/screened_url.rb b/app/models/screened_url.rb
index 6e3bbc0e8e9..39ea8863066 100644
--- a/app/models/screened_url.rb
+++ b/app/models/screened_url.rb
@@ -16,8 +16,8 @@ class ScreenedUrl < ActiveRecord::Base
validates :domain, presence: true
def normalize
- self.url = ScreenedUrl.normalize_url(self.url) if self.url
- self.domain = self.domain.downcase.sub(/\Awww\./, "") if self.domain
+ self.url = ScreenedUrl.normalize_url(url) if url
+ self.domain = domain.downcase.sub(/\Awww\./, "") if domain
end
def self.watch(url, domain, opts = {})
diff --git a/app/models/search_log.rb b/app/models/search_log.rb
index bb6c404628c..272bbac5f24 100644
--- a/app/models/search_log.rb
+++ b/app/models/search_log.rb
@@ -66,7 +66,7 @@ class SearchLog < ActiveRecord::Base
if !result
log =
- self.create!(
+ create!(
term: term,
search_type: search_type,
ip_address: ip_address,
diff --git a/app/models/sidebar_section.rb b/app/models/sidebar_section.rb
index 4e6ce3d4292..11dffea1dd0 100644
--- a/app/models/sidebar_section.rb
+++ b/app/models/sidebar_section.rb
@@ -32,8 +32,8 @@ class SidebarSection < ActiveRecord::Base
def reset_community!
ActiveRecord::Base.transaction do
- self.update!(title: "Community")
- self.sidebar_section_links.destroy_all
+ update!(title: "Community")
+ sidebar_section_links.destroy_all
community_urls =
SidebarUrl::COMMUNITY_SECTION_LINKS.map do |url_data|
"('#{url_data[:name]}', '#{url_data[:path]}', '#{url_data[:icon]}', '#{url_data[:segment]}', false, now(), now())"
@@ -47,7 +47,7 @@ class SidebarSection < ActiveRecord::Base
sidebar_section_links =
result.map.with_index do |url, index|
- "(-1, #{url.id}, 'SidebarUrl', #{self.id}, #{index}, now(), now())"
+ "(-1, #{url.id}, 'SidebarUrl', #{id}, #{index}, now(), now())"
end
DB.query <<~SQL
@@ -60,7 +60,7 @@ class SidebarSection < ActiveRecord::Base
private
def set_system_user_for_public_section
- self.user_id = Discourse.system_user.id if self.public
+ self.user_id = Discourse.system_user.id if public
end
end
diff --git a/app/models/sidebar_section_link.rb b/app/models/sidebar_section_link.rb
index 5b625ce27b5..91e7cb1588f 100644
--- a/app/models/sidebar_section_link.rb
+++ b/app/models/sidebar_section_link.rb
@@ -14,12 +14,12 @@ class SidebarSectionLink < ActiveRecord::Base
before_validation :inherit_user_id
before_create do
- if self.user_id && self.sidebar_section
- self.position = self.sidebar_section.sidebar_section_links.maximum(:position).to_i + 1
+ if user_id && sidebar_section
+ self.position = sidebar_section.sidebar_section_links.maximum(:position).to_i + 1
end
end
- after_destroy { self.linkable.destroy! if self.linkable_type == "SidebarUrl" }
+ after_destroy { linkable.destroy! if linkable_type == "SidebarUrl" }
private
@@ -28,9 +28,9 @@ class SidebarSectionLink < ActiveRecord::Base
end
def ensure_supported_linkable_type
- if !SUPPORTED_LINKABLE_TYPES.include?(self.linkable_type) ||
- (self.linkable_type == "Tag" && !SiteSetting.tagging_enabled)
- self.errors.add(
+ if !SUPPORTED_LINKABLE_TYPES.include?(linkable_type) ||
+ (linkable_type == "Tag" && !SiteSetting.tagging_enabled)
+ errors.add(
:linkable_type,
I18n.t("activerecord.errors.models.sidebar_section_link.attributes.linkable_type.invalid"),
)
diff --git a/app/models/sidebar_url.rb b/app/models/sidebar_url.rb
index 0fb6eb87a64..76fe9530d4e 100644
--- a/app/models/sidebar_url.rb
+++ b/app/models/sidebar_url.rb
@@ -75,7 +75,7 @@ class SidebarUrl < ActiveRecord::Base
end
def remove_internal_hostname
- self.value = self.value.sub(%r{\Ahttp(s)?://#{Discourse.current_hostname}}, "")
+ self.value = value.sub(%r{\Ahttp(s)?://#{Discourse.current_hostname}}, "")
end
def set_external
diff --git a/app/models/site_setting.rb b/app/models/site_setting.rb
index 336fa22b94d..5a4b206cc5c 100644
--- a/app/models/site_setting.rb
+++ b/app/models/site_setting.rb
@@ -87,16 +87,16 @@ class SiteSetting < ActiveRecord::Base
after_save do
if saved_change_to_value?
- if self.data_type == SiteSettings::TypeSupervisor.types[:upload]
- UploadReference.ensure_exist!(upload_ids: [self.value], target: self)
- elsif self.data_type == SiteSettings::TypeSupervisor.types[:uploaded_image_list]
- upload_ids = self.value.split("|").compact.uniq
+ if data_type == SiteSettings::TypeSupervisor.types[:upload]
+ UploadReference.ensure_exist!(upload_ids: [value], target: self)
+ elsif data_type == SiteSettings::TypeSupervisor.types[:uploaded_image_list]
+ upload_ids = value.split("|").compact.uniq
UploadReference.ensure_exist!(upload_ids: upload_ids, target: self)
- elsif self.data_type == SiteSettings::TypeSupervisor.types[:objects] && self.value.present?
+ elsif data_type == SiteSettings::TypeSupervisor.types[:objects] && value.present?
upload_values =
SchemaSettingsObjectValidator.property_values_of_type(
- schema: SiteSetting.type_supervisor.type_hash(self.name.to_sym)[:schema],
- objects: JSON.parse(self.value),
+ schema: SiteSetting.type_supervisor.type_hash(name.to_sym)[:schema],
+ objects: JSON.parse(value),
type: "upload",
)
@@ -328,8 +328,8 @@ class SiteSetting < ActiveRecord::Base
end
def self.s3_base_url
- path = self.s3_upload_bucket.split("/", 2)[1]
- "#{self.absolute_base_url}#{path ? "/" + path : ""}"
+ path = s3_upload_bucket.split("/", 2)[1]
+ "#{absolute_base_url}#{path ? "/" + path : ""}"
end
def self.absolute_base_url
@@ -396,7 +396,7 @@ class SiteSetting < ActiveRecord::Base
return SiteIconManager.public_send("#{setting_name}_url")
end
- upload = self.public_send(setting_name)
+ upload = public_send(setting_name)
upload ? full_cdn_url(upload.url) : ""
end
end
diff --git a/app/models/site_setting_group.rb b/app/models/site_setting_group.rb
index dab257b5898..a9e476acb8f 100644
--- a/app/models/site_setting_group.rb
+++ b/app/models/site_setting_group.rb
@@ -27,7 +27,7 @@ class SiteSettingGroup < ActiveRecord::Base
def self.can_access_db?
!GlobalSetting.skip_redis? && !GlobalSetting.skip_db? &&
- ActiveRecord::Base.connection.table_exists?(self.table_name)
+ ActiveRecord::Base.connection.table_exists?(table_name)
end
end
diff --git a/app/models/skipped_email_log.rb b/app/models/skipped_email_log.rb
index 31dd4a6d391..10332f2b4e3 100644
--- a/app/models/skipped_email_log.rb
+++ b/app/models/skipped_email_log.rb
@@ -50,14 +50,14 @@ class SkippedEmailLog < ActiveRecord::Base
def reason
if is_custom?
- self.custom_reason
+ custom_reason
else
- type = self.reason_type
+ type = reason_type
I18n.t(
"skipped_email_log.#{SkippedEmailLog.reason_types[type]}",
- user_id: self.user_id,
- post_id: self.post_id,
+ user_id: user_id,
+ post_id: post_id,
)
end
end
@@ -65,11 +65,11 @@ class SkippedEmailLog < ActiveRecord::Base
private
def is_custom?
- self.reason_type == self.class.reason_types[:custom]
+ reason_type == self.class.reason_types[:custom]
end
def ensure_valid_reason_type
- self.errors.add(:reason_type, :invalid) unless self.class.reason_types[self.reason_type]
+ errors.add(:reason_type, :invalid) unless self.class.reason_types[reason_type]
end
end
diff --git a/app/models/tag.rb b/app/models/tag.rb
index e911f9d2e43..a4b806cdc1a 100644
--- a/app/models/tag.rb
+++ b/app/models/tag.rb
@@ -132,7 +132,7 @@ class Tag < ActiveRecord::Base
end
def self.find_by_name(name)
- self.find_by("lower(name) = ?", name.downcase)
+ find_by("lower(name) = ?", name.downcase)
end
def self.top_tags(limit_arg: nil, category: nil, guardian: Guardian.new)
@@ -253,7 +253,7 @@ class Tag < ActiveRecord::Base
end
def synonym?
- !self.target_tag_id.nil?
+ !target_tag_id.nil?
end
def target_tag_validator
@@ -314,11 +314,11 @@ class Tag < ActiveRecord::Base
end
def sanitize_description
- self.description = sanitize_field(self.description) if description_changed?
+ self.description = sanitize_field(description) if description_changed?
end
def name_validator
- errors.add(:name, :invalid) if name.present? && RESERVED_TAGS.include?(self.name.strip.downcase)
+ errors.add(:name, :invalid) if name.present? && RESERVED_TAGS.include?(name.strip.downcase)
end
end
diff --git a/app/models/tag_group.rb b/app/models/tag_group.rb
index 6988d0e9375..77252c89ff3 100644
--- a/app/models/tag_group.rb
+++ b/app/models/tag_group.rb
@@ -66,13 +66,13 @@ class TagGroup < ActiveRecord::Base
# TODO: long term we can cache this if TONs of tag groups exist
def self.find_id_by_slug(slug)
- self.pluck(:id, :name).each { |id, name| return id if Slug.for(name) == slug }
+ pluck(:id, :name).each { |id, name| return id if Slug.for(name) == slug }
nil
end
# Same as Tag#find_by_name
def self.find_by_name_insensitive(name)
- self.find_by("lower(name) = ?", name.downcase)
+ find_by("lower(name) = ?", name.downcase)
end
def self.resolve_permissions(permissions)
diff --git a/app/models/theme.rb b/app/models/theme.rb
index bf6b2c2ef62..c4cbdd7a050 100644
--- a/app/models/theme.rb
+++ b/app/models/theme.rb
@@ -226,15 +226,15 @@ class Theme < ActiveRecord::Base
after_destroy do
remove_from_cache!
- Theme.clear_default! if SiteSetting.default_theme_id == self.id
+ Theme.clear_default! if SiteSetting.default_theme_id == id
- if self.id
+ if id
ColorScheme
- .where(theme_id: self.id)
+ .where(theme_id: id)
.where("id NOT IN (SELECT color_scheme_id FROM themes where color_scheme_id IS NOT NULL)")
.destroy_all
- ColorScheme.where(theme_id: self.id).update_all(theme_id: nil)
+ ColorScheme.where(theme_id: id).update_all(theme_id: nil)
end
Theme.expire_site_cache!
@@ -272,7 +272,7 @@ class Theme < ActiveRecord::Base
end
def self.is_parent_theme?(id)
- self.parent_theme_ids.include?(id)
+ parent_theme_ids.include?(id)
end
def self.user_theme_ids
@@ -340,7 +340,7 @@ class Theme < ActiveRecord::Base
get_set_cache "transformed_ids_#{id}" do
all_ids =
- if self.is_parent_theme?(id)
+ if is_parent_theme?(id)
components = components_for(id).tap { |c| c.sort!.uniq! }
[id, *components]
else
@@ -431,7 +431,7 @@ class Theme < ActiveRecord::Base
Theme.clear_default! if default?
ChildTheme.where("parent_theme_id = ?", id).destroy_all
- self.save!
+ save!
end
end
@@ -442,7 +442,7 @@ class Theme < ActiveRecord::Base
self.enabled = true
self.component = false
ChildTheme.where("child_theme_id = ?", id).destroy_all
- self.save!
+ save!
end
end
@@ -492,7 +492,7 @@ class Theme < ActiveRecord::Base
end
def self.lookup_target(target_id)
- self.targets.invert[target_id]
+ targets.invert[target_id]
end
def self.notify_theme_change(
@@ -770,15 +770,15 @@ class Theme < ActiveRecord::Base
end
def cached_settings
- Theme.get_set_cache "settings_for_theme_#{self.id}" do
+ Theme.get_set_cache "settings_for_theme_#{id}" do
build_settings_hash
end
end
def cached_default_settings
- Theme.get_set_cache "default_settings_for_theme_#{self.id}" do
+ Theme.get_set_cache "default_settings_for_theme_#{id}" do
settings_hash = {}
- self.settings.each { |name, setting| settings_hash[name] = setting.default }
+ settings.each { |name, setting| settings_hash[name] = setting.default }
theme_uploads = build_theme_uploads_hash
settings_hash["theme_uploads"] = theme_uploads if theme_uploads.present?
@@ -792,7 +792,7 @@ class Theme < ActiveRecord::Base
def build_settings_hash
hash = {}
- self.settings.each { |name, setting| hash[name] = setting.value }
+ settings.each { |name, setting| hash[name] = setting.value }
theme_uploads = build_theme_uploads_hash
hash["theme_uploads"] = theme_uploads if theme_uploads.present?
@@ -884,9 +884,9 @@ class Theme < ActiveRecord::Base
end
meta[:color_schemes] = {}.tap do |hash|
- schemes = self.color_schemes
+ schemes = color_schemes
# The selected color scheme may not belong to the theme, so include it anyway
- schemes = [self.color_scheme] + schemes if self.color_scheme
+ schemes = [color_scheme] + schemes if color_scheme
schemes.uniq.each do |scheme|
hash[scheme.name] = {}.tap do |colors|
scheme.colors.each { |color| colors[color.name] = color.hex }
@@ -896,7 +896,7 @@ class Theme < ActiveRecord::Base
meta[:modifiers] = {}.tap do |hash|
ThemeModifierSet.modifiers.keys.each do |modifier|
- value = self.theme_modifier_set.public_send(modifier)
+ value = theme_modifier_set.public_send(modifier)
hash[modifier] = value if !value.nil?
end
end
@@ -976,13 +976,13 @@ class Theme < ActiveRecord::Base
next if results.blank?
- old_settings = self.theme_settings.pluck(:name)
- self.theme_settings.destroy_all
+ old_settings = theme_settings.pluck(:name)
+ theme_settings.destroy_all
final_result = results.last
final_result[:settings_after].each do |key, val|
- self.update_setting(key.to_sym, val)
+ update_setting(key.to_sym, val)
rescue Discourse::NotFound
if old_settings.include?(key)
final_result[:settings_after].delete(key)
@@ -1000,7 +1000,7 @@ class Theme < ActiveRecord::Base
results.each do |res|
record =
ThemeSettingsMigration.new(
- theme_id: self.id,
+ theme_id: id,
version: res[:version],
name: res[:name],
theme_field_id: res[:theme_field_id],
@@ -1013,12 +1013,12 @@ class Theme < ActiveRecord::Base
allow_out_of_sequence_migration ? record.save : record.save!
end
- self.reload
- self.update_javascript_cache!
+ reload
+ update_javascript_cache!
end
if start_transaction
- self.transaction(&block)
+ transaction(&block)
else
block.call
end
@@ -1084,11 +1084,11 @@ class Theme < ActiveRecord::Base
end
def user_selectable_count
- UserOption.where(theme_ids: [self.id]).count
+ UserOption.where(theme_ids: [id]).count
end
def themeable_site_settings
- return [] if self.component?
+ return [] if component?
ThemeSiteSettingResolver.new(theme: self).resolved_theme_site_settings
end
diff --git a/app/models/theme_field.rb b/app/models/theme_field.rb
index bb686aa7e4b..b382f54e069 100644
--- a/app/models/theme_field.rb
+++ b/app/models/theme_field.rb
@@ -23,10 +23,10 @@ class ThemeField < ActiveRecord::Base
after_save do
if (
- self.type_id == ThemeField.types[:theme_screenshot_upload_var] ||
- self.type_id == ThemeField.types[:theme_upload_var]
+ type_id == ThemeField.types[:theme_screenshot_upload_var] ||
+ type_id == ThemeField.types[:theme_upload_var]
) && saved_change_to_upload_id?
- UploadReference.ensure_exist!(upload_ids: [self.upload_id], target: self)
+ UploadReference.ensure_exist!(upload_ids: [upload_id], target: self)
end
end
@@ -136,7 +136,7 @@ class ThemeField < ActiveRecord::Base
.select { |node| inline_javascript?(node) }
.each_with_index do |node, index|
unique_name =
- "theme-#{theme_id}-inline-#{Theme.targets[self.target_id]}-#{name}#{"-#{index + 1}" if index > 0}"
+ "theme-#{theme_id}-inline-#{Theme.targets[target_id]}-#{name}#{"-#{index + 1}" if index > 0}"
cache =
raw_javascript_caches.find { |c| c.name == unique_name } ||
@@ -170,9 +170,9 @@ class ThemeField < ActiveRecord::Base
end
def validate_svg_sprite_xml
- upload = Upload.find_by(id: self.upload_id)
+ upload = Upload.find_by(id: upload_id)
- return "Error with #{self.name}: No upload found for the provided upload_id" if upload.nil?
+ return "Error with #{name}: No upload found for the provided upload_id" if upload.nil?
if Discourse.store.external?
path = Discourse.store.download(upload)
@@ -180,19 +180,19 @@ class ThemeField < ActiveRecord::Base
path = Discourse.store.path_for(upload)
end
- return "Error with #{self.name}: Could not download icon sprite" if path.nil?
+ return "Error with #{name}: Could not download icon sprite" if path.nil?
error = nil
begin
content = File.read(path)
if content.to_s.bytesize > SvgSprite::MAX_THEME_SPRITE_SIZE
- error = "Error with #{self.name}: Icon sprite file is too large"
+ error = "Error with #{name}: Icon sprite file is too large"
else
Nokogiri.XML(content) { |config| config.options = Nokogiri::XML::ParseOptions::NOBLANKS }
end
rescue => e
- error = "Error with #{self.name}: #{e.inspect}"
+ error = "Error with #{name}: #{e.inspect}"
end
error
@@ -236,10 +236,10 @@ class ThemeField < ActiveRecord::Base
data = translation_data
js = <<~JS
- /* Translation data for theme #{self.theme_id} (#{self.name})*/
+ /* Translation data for theme #{theme_id} (#{name})*/
const localeData = window._discourse_locale_data ??= {};
localeData.theme ??= {};
- localeData.theme[#{self.theme_id}] = #{data.to_json};
+ localeData.theme[#{theme_id}] = #{data.to_json};
JS
javascript_cache.content = js
@@ -256,7 +256,7 @@ class ThemeField < ActiveRecord::Base
end
def validate_yaml!
- return unless self.name == "yaml"
+ return unless name == "yaml"
errors = []
@@ -326,52 +326,50 @@ class ThemeField < ActiveRecord::Base
end
def basic_html_field?
- ThemeField.basic_targets.include?(Theme.targets[self.target_id].to_s) &&
- ThemeField.html_fields.include?(self.name)
+ ThemeField.basic_targets.include?(Theme.targets[target_id].to_s) &&
+ ThemeField.html_fields.include?(name)
end
def extra_js_field?
- Theme.targets[self.target_id] == :extra_js
+ Theme.targets[target_id] == :extra_js
end
def js_tests_field?
- Theme.targets[self.target_id] == :tests_js
+ Theme.targets[target_id] == :tests_js
end
def basic_scss_field?
- ThemeField.basic_targets.include?(Theme.targets[self.target_id].to_s) &&
- ThemeField.scss_fields.include?(self.name)
+ ThemeField.basic_targets.include?(Theme.targets[target_id].to_s) &&
+ ThemeField.scss_fields.include?(name)
end
def extra_scss_field?
- Theme.targets[self.target_id] == :extra_scss
+ Theme.targets[target_id] == :extra_scss
end
def settings_field?
- Theme.targets[:settings] == self.target_id
+ Theme.targets[:settings] == target_id
end
def translation_field?
- Theme.targets[:translations] == self.target_id
+ Theme.targets[:translations] == target_id
end
def svg_sprite_field?
- ThemeField.theme_var_type_ids.include?(self.type_id) &&
- self.name == SvgSprite.theme_sprite_variable_name
+ ThemeField.theme_var_type_ids.include?(type_id) && name == SvgSprite.theme_sprite_variable_name
end
def migration_field?
- Theme.targets[:migrations] == self.target_id
+ Theme.targets[:migrations] == target_id
end
def ensure_baked!
- needs_baking = !self.value_baked || compiler_version != Theme.compiler_version
+ needs_baking = !value_baked || compiler_version != Theme.compiler_version
return unless needs_baking
if basic_html_field? || translation_field?
- self.value_baked, self.error =
- translation_field? ? process_translation : process_html(self.value)
- self.error = nil if self.error.blank?
+ self.value_baked, self.error = translation_field? ? process_translation : process_html(value)
+ self.error = nil if error.blank?
self.compiler_version = Theme.compiler_version
CSP::Extension.clear_theme_extensions_cache!
elsif extra_js_field? || js_tests_field?
@@ -397,13 +395,9 @@ class ThemeField < ActiveRecord::Base
self.compiler_version = Theme.compiler_version
end
- if self.will_save_change_to_value_baked? || self.will_save_change_to_compiler_version? ||
- self.will_save_change_to_error?
- self.update_columns(
- value_baked: value_baked,
- compiler_version: compiler_version,
- error: error,
- )
+ if will_save_change_to_value_baked? || will_save_change_to_compiler_version? ||
+ will_save_change_to_error?
+ update_columns(value_baked: value_baked, compiler_version: compiler_version, error: error)
end
rescue ActiveRecord::ReadOnlyError
# Just noop if ActiveRecord is preventing writes for now. In an ideal world, this method will not be called in GET
@@ -412,7 +406,7 @@ class ThemeField < ActiveRecord::Base
def scss_entrypoint_name
if name == "scss"
- self.target_name
+ target_name
elsif target_name == "common" && name == "color_definitions"
"color_definitions"
elsif target_name == "common" && name == "embedded_scss"
@@ -425,15 +419,15 @@ class ThemeField < ActiveRecord::Base
def compile_scss(prepended_scss = nil)
prepended_scss ||= Stylesheet::Importer.new({}).prepended_scss
- self.theme.with_scss_load_paths do |load_paths|
+ theme.with_scss_load_paths do |load_paths|
Stylesheet::Compiler.compile(
<<~SCSS,
#{prepended_scss}
- #{self.theme.scss_variables}
+ #{theme.scss_variables}
@import \"theme-entrypoint/#{scss_entrypoint_name}\";
SCSS
- "#{Theme.targets[self.target_id]}.scss",
- theme: self.theme,
+ "#{Theme.targets[target_id]}.scss",
+ theme: theme,
load_paths: load_paths,
)
end
@@ -456,15 +450,15 @@ class ThemeField < ActiveRecord::Base
result = ["failed"]
begin
result = compile_scss
- if contains_optimized_link?(self.value)
+ if contains_optimized_link?(value)
self.error = I18n.t("themes.errors.optimized_link")
- elsif contains_ember_css_selector?(self.value)
+ elsif contains_ember_css_selector?(value)
self.error = I18n.t("themes.ember_selector_error")
else
self.error = nil unless error.nil?
end
rescue SassC::SyntaxError, SassC::NotRenderedError, AssetProcessor::TranspileError => e
- self.error = e.message unless self.destroyed?
+ self.error = e.message unless destroyed?
end
self.compiler_version = Theme.compiler_version
self.value_baked = Digest::SHA1.hexdigest(result.join(",")) # We don't use the compiled CSS here, we just use it to invalidate the stylesheet cache
@@ -693,7 +687,7 @@ class ThemeField < ActiveRecord::Base
end
def upload_url
- self.upload&.url
+ upload&.url
end
private
@@ -712,17 +706,14 @@ class ThemeField < ActiveRecord::Base
def migration_filename_is_valid
if !name.match?(/\A\d{4}-[a-zA-Z0-9]+/)
- self.errors.add(
- :base,
- I18n.t("themes.import_error.migrations.invalid_filename", filename: name),
- )
+ errors.add(:base, I18n.t("themes.import_error.migrations.invalid_filename", filename: name))
return
end
# the 5 here is the length of the first 4 digits and the dash that follows
# them
if name.size - 5 > MIGRATION_NAME_PART_MAX_LENGTH
- self.errors.add(
+ errors.add(
:base,
I18n.t(
"themes.import_error.migrations.name_too_long",
diff --git a/app/models/theme_modifier_set.rb b/app/models/theme_modifier_set.rb
index 7b46870758d..ce685d132d7 100644
--- a/app/models/theme_modifier_set.rb
+++ b/app/models/theme_modifier_set.rb
@@ -6,7 +6,7 @@ class ThemeModifierSet < ActiveRecord::Base
belongs_to :theme
def self.modifiers
- @modifiers ||= self.load_modifiers
+ @modifiers ||= load_modifiers
end
validate :type_validator
@@ -38,11 +38,10 @@ class ThemeModifierSet < ActiveRecord::Base
# Given the ids of multiple active themes / theme components, this function
# will combine them into a 'resolved' behavior
def self.resolve_modifier_for_themes(theme_ids, modifier_name)
- return nil if !(config = self.modifiers[modifier_name])
+ return nil if !(config = modifiers[modifier_name])
all_values =
- self
- .where(theme_id: theme_ids)
+ where(theme_id: theme_ids)
.where.not(modifier_name => nil)
.map { |s| s.public_send(modifier_name) }
case config[:type]
diff --git a/app/models/theme_setting.rb b/app/models/theme_setting.rb
index 57547d9a72e..651e3a43f1e 100644
--- a/app/models/theme_setting.rb
+++ b/app/models/theme_setting.rb
@@ -12,21 +12,21 @@ class ThemeSetting < ActiveRecord::Base
validates :name, :theme, presence: true
validates :data_type, inclusion: { in: TYPES_ENUM.values }
- validate :json_value_size, if: -> { self.data_type == TYPES_ENUM[:objects] }
+ validate :json_value_size, if: -> { data_type == TYPES_ENUM[:objects] }
validates :name, length: { maximum: 255 }
after_destroy :clear_settings_cache
after_save :clear_settings_cache
after_save do
- if self.data_type == ThemeSetting.types[:upload] && saved_change_to_value?
- UploadReference.ensure_exist!(upload_ids: [self.value], target: self)
- elsif self.data_type == ThemeSetting.types[:objects] && saved_change_to_json_value? &&
- self.json_value.present?
+ if data_type == ThemeSetting.types[:upload] && saved_change_to_value?
+ UploadReference.ensure_exist!(upload_ids: [value], target: self)
+ elsif data_type == ThemeSetting.types[:objects] && saved_change_to_json_value? &&
+ json_value.present?
upload_values =
SchemaSettingsObjectValidator.property_values_of_type(
- schema: theme.settings[self.name.to_sym].schema,
- objects: self.json_value,
+ schema: theme.settings[name.to_sym].schema,
+ objects: json_value,
type: "upload",
)
@@ -45,7 +45,7 @@ class ThemeSetting < ActiveRecord::Base
end
if theme.theme_modifier_set.refresh_theme_setting_modifiers(
- target_setting_name: self.name,
+ target_setting_name: name,
target_setting_value: self.value,
)
theme.theme_modifier_set.save!
diff --git a/app/models/theme_site_setting.rb b/app/models/theme_site_setting.rb
index bfa2117000f..2f9aaf4e709 100644
--- a/app/models/theme_site_setting.rb
+++ b/app/models/theme_site_setting.rb
@@ -14,13 +14,13 @@ class ThemeSiteSetting < ActiveRecord::Base
after_save do
if saved_change_to_value?
- if self.data_type == SiteSettings::TypeSupervisor.types[:upload]
- UploadReference.ensure_exist!(upload_ids: [self.value], target: self)
- elsif self.data_type == SiteSettings::TypeSupervisor.types[:objects] && self.value.present?
+ if data_type == SiteSettings::TypeSupervisor.types[:upload]
+ UploadReference.ensure_exist!(upload_ids: [value], target: self)
+ elsif data_type == SiteSettings::TypeSupervisor.types[:objects] && value.present?
upload_ids =
SchemaSettingsObjectValidator.property_values_of_type(
- schema: SiteSetting.type_supervisor.type_hash(self.name.to_sym)[:schema],
- objects: JSON.parse(self.value),
+ schema: SiteSetting.type_supervisor.type_hash(name.to_sym)[:schema],
+ objects: JSON.parse(value),
type: "upload",
)
@@ -69,7 +69,7 @@ class ThemeSiteSetting < ActiveRecord::Base
def self.can_access_db?
!GlobalSetting.skip_redis? && !GlobalSetting.skip_db? &&
- ActiveRecord::Base.connection.table_exists?(self.table_name)
+ ActiveRecord::Base.connection.table_exists?(table_name)
end
# Generates a map of theme IDs to their site setting values. When
@@ -125,7 +125,7 @@ class ThemeSiteSetting < ActiveRecord::Base
end
def setting_rb_value
- SiteSetting.type_supervisor.to_rb_value(self.name, self.value, self.data_type)
+ SiteSetting.type_supervisor.to_rb_value(name, value, data_type)
end
end
diff --git a/app/models/topic.rb b/app/models/topic.rb
index d5b143e08b0..f564e8ec5b5 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -36,7 +36,7 @@ class Topic < ActiveRecord::Base
end
def self.thumbnail_sizes
- [self.share_thumbnail_size] + DiscoursePluginRegistry.topic_thumbnail_sizes
+ [share_thumbnail_size] + DiscoursePluginRegistry.topic_thumbnail_sizes
end
def self.visibility_reasons
@@ -150,7 +150,7 @@ class Topic < ActiveRecord::Base
if deleted_at.nil?
update_category_topic_count_by(-1) if visible?
- CategoryTagStat.topic_deleted(self) if self.tags.present?
+ CategoryTagStat.topic_deleted(self) if tags.present?
trigger_event = true
end
@@ -158,7 +158,7 @@ class Topic < ActiveRecord::Base
DiscourseEvent.trigger(:topic_trashed, self) if trigger_event
- self.topic_embed.trash! if has_topic_embed?
+ topic_embed.trash! if has_topic_embed?
end
def recover!(recovered_by = nil)
@@ -166,7 +166,7 @@ class Topic < ActiveRecord::Base
unless deleted_at.nil?
update_category_topic_count_by(1) if visible?
- CategoryTagStat.topic_recovered(self) if self.tags.present?
+ CategoryTagStat.topic_recovered(self) if tags.present?
trigger_event = true
end
@@ -244,7 +244,7 @@ class Topic < ActiveRecord::Base
self.title = TextCleaner.clean_title(TextSentinel.title_sentinel(title).text) if errors[
:title
].empty?
- self.featured_link = self.featured_link.strip.presence if self.featured_link
+ self.featured_link = featured_link.strip.presence if featured_link
end
belongs_to :category
@@ -425,7 +425,7 @@ class Topic < ActiveRecord::Base
if tags_changed || saved_change_to_attribute?(:category_id) ||
saved_change_to_attribute?(:title)
- SearchIndexer.queue_post_reindex(self.id)
+ SearchIndexer.queue_post_reindex(id)
if tags_changed
TagUser.auto_watch(topic_id: id)
@@ -438,9 +438,9 @@ class Topic < ActiveRecord::Base
end
after_update do
- if saved_changes[:category_id] && self.tags.present?
+ if saved_changes[:category_id] && tags.present?
CategoryTagStat.topic_moved(self, *saved_changes[:category_id])
- elsif saved_changes[:category_id] && self.category&.read_restricted?
+ elsif saved_changes[:category_id] && category&.read_restricted?
UserProfile.remove_featured_topic_from_all_profiles(self)
end
end
@@ -451,11 +451,11 @@ class Topic < ActiveRecord::Base
end
def advance_draft_sequence
- DraftSequence.next!(user, self.draft_key)
+ DraftSequence.next!(user, draft_key)
end
def ensure_topic_has_a_category
- if category_id.nil? && (archetype.nil? || self.regular?)
+ if category_id.nil? && (archetype.nil? || regular?)
self.category_id = category&.id || SiteSetting.uncategorized_category_id
end
end
@@ -493,7 +493,7 @@ class Topic < ActiveRecord::Base
end
def has_flags?
- self.class.has_flag_scope.exists?(topic_id: self.id)
+ self.class.has_flag_scope.exists?(topic_id: id)
end
def is_official_warning?
@@ -543,7 +543,7 @@ class Topic < ActiveRecord::Base
# by simply nulling this column
DB.exec(
"UPDATE topics SET fancy_title = :fancy_title where id = :id",
- id: self.id,
+ id: id,
fancy_title: fancy_title,
)
end
@@ -697,11 +697,11 @@ class Topic < ActiveRecord::Base
end
def private_message?
- self.archetype == Archetype.private_message
+ archetype == Archetype.private_message
end
def regular?
- self.archetype == Archetype.default
+ archetype == Archetype.default
end
# Single source of truth for "this topic renders as nested." Both
@@ -719,7 +719,7 @@ class Topic < ActiveRecord::Base
end
def open?
- !self.closed?
+ !closed?
end
MAX_SIMILAR_BODY_LENGTH = 200
@@ -869,7 +869,7 @@ class Topic < ActiveRecord::Base
group_ids = user.groups.pluck(:id)
if group_ids.present?
allowed_group_ids =
- self.allowed_groups.where("topic_allowed_groups.group_id IN (?)", group_ids).pluck(:id)
+ allowed_groups.where("topic_allowed_groups.group_id IN (?)", group_ids).pluck(:id)
allowed_group_ids.each { |id| GroupArchivedMessage.archive!(id, self) }
end
end
@@ -1093,8 +1093,8 @@ class Topic < ActiveRecord::Base
Topic.transaction do
old_category = category
- if self.category_id != new_category.id
- self.update(category_id: new_category.id)
+ if category_id != new_category.id
+ update(category_id: new_category.id)
if old_category
Category.where(id: old_category.id).update_all("topic_count = topic_count - 1")
@@ -1106,17 +1106,17 @@ class Topic < ActiveRecord::Base
-1
end
- Tag.update_counters(self.tags, { public_topic_count: count }) if count
+ Tag.update_counters(tags, { public_topic_count: count }) if count
end
# when a topic changes category we may have to start watching it
# if we happen to have read state for it
- CategoryUser.auto_watch(category_id: new_category.id, topic_id: self.id)
- CategoryUser.auto_track(category_id: new_category.id, topic_id: self.id)
+ CategoryUser.auto_watch(category_id: new_category.id, topic_id: id)
+ CategoryUser.auto_track(category_id: new_category.id, topic_id: id)
skip_alert = silent || SiteSetting.disable_category_edit_notifications
- if !skip_alert && (post = self.ordered_posts.first)
+ if !skip_alert && (post = ordered_posts.first)
notified_user_ids = [post.user_id, post.last_editor_id].uniq
DB.after_commit do
Jobs.enqueue(
@@ -1131,7 +1131,7 @@ class Topic < ActiveRecord::Base
# linked to posts secure/not secure depending on whether the
# category is private. this is only done if the category
# has actually changed to avoid noise.
- DB.after_commit { Jobs.enqueue(:update_topic_upload_security, topic_id: self.id) }
+ DB.after_commit { Jobs.enqueue(:update_topic_upload_security, topic_id: id) }
# Notify tracking state of category change so users who lost access
# have the topic removed from their tracking state
@@ -1176,7 +1176,7 @@ class Topic < ActiveRecord::Base
post_type: opts[:post_type] || Post.types[:moderator_action],
action_code: opts[:action_code],
no_bump: opts[:bump].blank?,
- topic_id: self.id,
+ topic_id: id,
silent: opts[:silent],
skip_validations: true,
skip_guardian: opts[:skip_guardian],
@@ -1261,12 +1261,12 @@ class Topic < ActiveRecord::Base
end
def invite_group(user, group, should_notify: true)
- TopicAllowedGroup.create!(topic_id: self.id, group_id: group.id)
+ TopicAllowedGroup.create!(topic_id: id, group_id: group.id)
group.update_columns(has_messages: true) unless group.has_messages
- self.allowed_groups.reload
+ allowed_groups.reload
last_post =
- self.posts.order("post_number desc").where("not hidden AND posts.deleted_at IS NULL").first
+ posts.order("post_number desc").where("not hidden AND posts.deleted_at IS NULL").first
if last_post
add_small_action(user, "invited_group", group.name)
if should_notify
@@ -1291,12 +1291,7 @@ class Topic < ActiveRecord::Base
)
SQL
User
- .where(
- [
- allowed_user_where_clause,
- { group_id: group.id, topic_id: self.id, op_user_id: self.user_id },
- ],
- )
+ .where([allowed_user_where_clause, { group_id: group.id, topic_id: id, op_user_id: user_id }])
.find_each { |allowed_user| remove_allowed_user(Discourse.system_user, allowed_user) }
true
@@ -1444,35 +1439,35 @@ class Topic < ActiveRecord::Base
self.archetype = Archetype.banner
self.bannered_until = bannered_until
- self.add_small_action(user, "banner.enabled")
- self.save
+ add_small_action(user, "banner.enabled")
+ save
MessageBus.publish("/site/banner", banner)
- Jobs.cancel_scheduled_job(:remove_banner, topic_id: self.id)
- Jobs.enqueue_at(bannered_until, :remove_banner, topic_id: self.id) if bannered_until
+ Jobs.cancel_scheduled_job(:remove_banner, topic_id: id)
+ Jobs.enqueue_at(bannered_until, :remove_banner, topic_id: id) if bannered_until
end
def remove_banner!(user)
self.archetype = Archetype.default
self.bannered_until = nil
- self.add_small_action(user, "banner.disabled")
- self.save
+ add_small_action(user, "banner.disabled")
+ save
MessageBus.publish("/site/banner", nil)
- Jobs.cancel_scheduled_job(:remove_banner, topic_id: self.id)
+ Jobs.cancel_scheduled_job(:remove_banner, topic_id: id)
end
def banner(guardian = nil)
- post = self.ordered_posts.first
+ post = ordered_posts.first
html = post.cooked
if guardian && ContentLocalization.show_translated_post?(post, guardian)
html = post.get_localization&.cooked.presence || html
end
- { html:, key: self.id, url: self.url }
+ { html:, key: id, url: url }
end
cattr_accessor :slug_computed_callbacks
@@ -1579,8 +1574,8 @@ class Topic < ActiveRecord::Base
pinned_until: pinned_until,
)
- Jobs.cancel_scheduled_job(:unpin_topic, topic_id: self.id)
- Jobs.enqueue_at(pinned_until, :unpin_topic, topic_id: self.id) if pinned_until
+ Jobs.cancel_scheduled_job(:unpin_topic, topic_id: id)
+ Jobs.enqueue_at(pinned_until, :unpin_topic, topic_id: id) if pinned_until
end
def draft_key
@@ -1608,17 +1603,17 @@ class Topic < ActiveRecord::Base
end
def inherit_slow_mode_from_category
- if self.category&.default_slow_mode_seconds
- self.slow_mode_seconds = self.category&.default_slow_mode_seconds
+ if category&.default_slow_mode_seconds
+ self.slow_mode_seconds = category&.default_slow_mode_seconds
end
end
def inherit_auto_close_from_category(timer_type: :close)
- auto_close_hours = self.category&.auto_close_hours
+ auto_close_hours = category&.auto_close_hours
- if self.open? && !@ignore_category_auto_close && auto_close_hours.present? &&
+ if open? && !@ignore_category_auto_close && auto_close_hours.present? &&
public_topic_timer&.execute_at.blank?
- based_on_last_post = self.category.auto_close_based_on_last_post
+ based_on_last_post = category.auto_close_based_on_last_post
duration_minutes = based_on_last_post ? auto_close_hours * 60 : nil
# the timer time can be a timestamp or an integer based
@@ -1628,7 +1623,7 @@ class Topic < ActiveRecord::Base
if !based_on_last_post
# set auto close to the original time it should have been
# when the topic was first created.
- start_time = self.created_at || Time.zone.now
+ start_time = created_at || Time.zone.now
auto_close_time = start_time + auto_close_hours.hours
# if we have already passed the original close time then
@@ -1639,7 +1634,7 @@ class Topic < ActiveRecord::Base
auto_close_time = auto_close_time.to_s
end
- self.set_or_create_timer(
+ set_or_create_timer(
TopicTimer.types[timer_type],
auto_close_time,
by_user: Discourse.system_user,
@@ -1660,7 +1655,7 @@ class Topic < ActiveRecord::Base
def delete_topic_timer(status_type, by_user: Discourse.system_user)
options = { status_type: status_type }
options.merge!(user: by_user) unless TopicTimer.public_types[status_type]
- self.topic_timers.find_by(options)&.trash!(by_user)
+ topic_timers.find_by(options)&.trash!(by_user)
@public_topic_timer = nil
nil
end
@@ -1708,7 +1703,7 @@ class Topic < ActiveRecord::Base
if topic_timer.based_on_last_post
if duration_minutes > 0
last_post_created_at =
- self.ordered_posts.last.present? ? self.ordered_posts.last.created_at : time_now
+ ordered_posts.last.present? ? ordered_posts.last.created_at : time_now
topic_timer.duration_minutes = duration_minutes
topic_timer.execute_at = last_post_created_at + duration_minutes.minutes
topic_timer.created_at = last_post_created_at
@@ -1716,7 +1711,7 @@ class Topic < ActiveRecord::Base
elsif topic_timer.status_type == TopicTimer.types[:delete_replies]
if duration_minutes > 0
first_reply_created_at =
- self.ordered_posts.where("post_number > 1").minimum(:created_at) || time_now
+ ordered_posts.where("post_number > 1").minimum(:created_at) || time_now
topic_timer.duration_minutes = duration_minutes
topic_timer.execute_at = first_reply_created_at + duration_minutes.minutes
topic_timer.created_at = first_reply_created_at
@@ -1749,20 +1744,20 @@ class Topic < ActiveRecord::Base
else
topic_timer.user ||=
(
- if self.user.staff? || self.user.trust_level == TrustLevel[4]
- self.user
+ if user.staff? || user.trust_level == TrustLevel[4]
+ user
else
Discourse.system_user
end
)
end
- if self.persisted?
+ if persisted?
# See TopicTimer.after_save for additional context; the topic
# status may be changed by saving.
topic_timer.save!
else
- self.topic_timers << topic_timer
+ topic_timers << topic_timer
end
topic_timer
@@ -1786,8 +1781,7 @@ class Topic < ActiveRecord::Base
end
def secure_group_ids
- @secure_group_ids ||=
- (self.category.secure_group_ids if self.category && self.category.read_restricted?)
+ @secure_group_ids ||= (category.secure_group_ids if category && category.read_restricted?)
end
def has_topic_embed?
@@ -1978,12 +1972,12 @@ class Topic < ActiveRecord::Base
) = 1
SQL
- result = DB.exec(sql, private_message: Archetype.private_message, topic_id: self.id)
+ result = DB.exec(sql, private_message: Archetype.private_message, topic_id: id)
result != 0
end
def featured_link_root_domain
- MiniSuffix.domain(UrlHelper.encode_and_parse(self.featured_link).hostname)
+ MiniSuffix.domain(UrlHelper.encode_and_parse(featured_link).hostname)
end
def self.private_message_topics_count_per_day(start_date, end_date, topic_subtype)
@@ -1996,7 +1990,7 @@ class Topic < ActiveRecord::Base
end
def is_category_topic?
- @is_category_topic ||= Category.exists?(topic_id: self.id.to_i)
+ @is_category_topic ||= Category.exists?(topic_id: id.to_i)
end
def reset_bumped_at(post_or_post_id = nil)
@@ -2018,7 +2012,7 @@ class Topic < ActiveRecord::Base
return if !post
self.bumped_at = post.created_at
- self.save(validate: false)
+ save(validate: false)
end
def auto_close_threshold_reached?
@@ -2029,7 +2023,7 @@ class Topic < ActiveRecord::Base
.pending
.joins(:reviewable)
.where("reviewable_scores.score >= ?", Reviewable.min_score_for_priority)
- .where("reviewables.topic_id = ?", self.id)
+ .where("reviewables.topic_id = ?", id)
.pluck(
"COUNT(DISTINCT reviewable_scores.user_id), COALESCE(SUM(reviewable_scores.score), 0.0)",
)
@@ -2043,7 +2037,7 @@ class Topic < ActiveRecord::Base
if category_id.present?
Category
.where("id = ?", category_id)
- .where("topic_id != ? OR topic_id IS NULL", self.id)
+ .where("topic_id != ? OR topic_id IS NULL", id)
.update_all("topic_count = topic_count + #{num.to_i}")
end
end
@@ -2051,7 +2045,7 @@ class Topic < ActiveRecord::Base
def access_topic_via_group
Group
.joins(:category_groups)
- .where("category_groups.category_id = ?", self.category_id)
+ .where("category_groups.category_id = ?", category_id)
.where("groups.public_admission OR groups.allow_membership_requests")
.order(:allow_membership_requests)
.first
@@ -2060,8 +2054,7 @@ class Topic < ActiveRecord::Base
def incoming_email_addresses(group: nil, received_before: Time.zone.now)
email_addresses = Set.new
- self
- .incoming_email
+ incoming_email
.where("created_at <= ?", received_before)
.each do |incoming_email|
to_addresses = incoming_email.to_addresses_split
@@ -2105,10 +2098,10 @@ class Topic < ActiveRecord::Base
target_user.notifications.create!(
notification_type: notification_type,
- topic_id: self.id,
+ topic_id: id,
post_number: post_number,
data: {
- topic_title: self.title,
+ topic_title: title,
display_username: invited_by.username,
original_user_id: user.id,
original_username: user.username,
@@ -2133,24 +2126,24 @@ class Topic < ActiveRecord::Base
end
def deletable_posts_count
- Post.with_deleted.where(topic_id: self.id).where.not(post_type: Post.types[:small_action]).count
+ Post.with_deleted.where(topic_id: id).where.not(post_type: Post.types[:small_action]).count
end
def cannot_permanently_delete_reason(user)
remaining = deletable_posts_count - 1
if posts_count > 0 || remaining > 0
I18n.t("post.cannot_permanently_delete.many_posts", count: remaining)
- elsif self.deleted_by_id == user&.id && self.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
+ elsif deleted_by_id == user&.id && deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
time_left =
RateLimiter.time_left(
- Post::PERMANENT_DELETE_TIMER.to_i - Time.zone.now.to_i + self.deleted_at.to_i,
+ Post::PERMANENT_DELETE_TIMER.to_i - Time.zone.now.to_i + deleted_at.to_i,
)
I18n.t("post.cannot_permanently_delete.wait_or_different_admin", time_left: time_left)
end
end
def first_smtp_enabled_group
- self.allowed_groups.where(smtp_enabled: true).first
+ allowed_groups.where(smtp_enabled: true).first
end
def secure_audience_publish_messages
@@ -2248,7 +2241,7 @@ class Topic < ActiveRecord::Base
if group_ids.present?
(
- self.category.groups.where(id: group_ids).where(automatic: false) -
+ category.groups.where(id: group_ids).where(automatic: false) -
target_user.groups.where(automatic: false)
).each do |group|
if guardian.can_edit_group?(group)
diff --git a/app/models/topic_link.rb b/app/models/topic_link.rb
index 83086cfb883..c10f7211fde 100644
--- a/app/models/topic_link.rb
+++ b/app/models/topic_link.rb
@@ -155,7 +155,7 @@ class TopicLink < ActiveRecord::Base
.uniq { |_, p| p }
.each do |link, parsed|
TopicLink.transaction do
- url, reflected_id = self.ensure_entry_for(post, link, parsed)
+ url, reflected_id = ensure_entry_for(post, link, parsed)
current_urls << url unless url.nil?
reflected_ids << reflected_id unless reflected_id.nil?
rescue URI::Error
@@ -165,7 +165,7 @@ class TopicLink < ActiveRecord::Base
end
end
- self.cleanup_entries(post, current_urls, reflected_ids)
+ cleanup_entries(post, current_urls, reflected_ids)
end
def self.crawl_link_title(topic_link_id)
diff --git a/app/models/topic_timer.rb b/app/models/topic_timer.rb
index 1f15469b2d8..0133defb33b 100644
--- a/app/models/topic_timer.rb
+++ b/app/models/topic_timer.rb
@@ -26,7 +26,7 @@ class TopicTimer < BaseTimer
before_save do
self.created_at ||= Time.zone.now if execute_at
- self.public_type = self.public_type?
+ self.public_type = public_type?
end
# These actions are in place to make sure the topic is in the correct
diff --git a/app/models/topic_tracking_state.rb b/app/models/topic_tracking_state.rb
index b2f5f6664bf..1eb8285ac3e 100644
--- a/app/models/topic_tracking_state.rb
+++ b/app/models/topic_tracking_state.rb
@@ -227,9 +227,9 @@ class TopicTrackingState
end
def self.publish_read(topic_id, last_read_post_number, user, notification_level = nil)
- self.publish_read_message(
+ publish_read_message(
message_type: READ_MESSAGE_TYPE,
- channel_name: self.unread_channel_key(user.id),
+ channel_name: unread_channel_key(user.id),
topic_id: topic_id,
user: user,
last_read_post_number: last_read_post_number,
@@ -239,12 +239,12 @@ class TopicTrackingState
def self.publish_dismiss_new(user_id, topic_ids: [])
message = { message_type: DISMISS_NEW_MESSAGE_TYPE, payload: { topic_ids: topic_ids } }
- MessageBus.publish(self.unread_channel_key(user_id), message.as_json, user_ids: [user_id])
+ MessageBus.publish(unread_channel_key(user_id), message.as_json, user_ids: [user_id])
end
def self.publish_dismiss_new_posts(user_id, topic_ids: [])
message = { message_type: DISMISS_NEW_POSTS_MESSAGE_TYPE, payload: { topic_ids: topic_ids } }
- MessageBus.publish(self.unread_channel_key(user_id), message.as_json, user_ids: [user_id])
+ MessageBus.publish(unread_channel_key(user_id), message.as_json, user_ids: [user_id])
end
def self.new_filter_sql
diff --git a/app/models/translation_override.rb b/app/models/translation_override.rb
index 6b0e1c62b97..c61c93dedc4 100644
--- a/app/models/translation_override.rb
+++ b/app/models/translation_override.rb
@@ -190,7 +190,7 @@ class TranslationOverride < ActiveRecord::Base
return if invalid_keys.blank?
- self.errors.add(
+ errors.add(
:base,
I18n.t(
"activerecord.errors.models.translation_overrides.attributes.value.invalid_interpolation_keys",
diff --git a/app/models/upload.rb b/app/models/upload.rb
index 83446d5fb6c..559332d7025 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -51,16 +51,16 @@ class Upload < ActiveRecord::Base
validates_with UploadValidator
before_destroy do
- UserProfile.where(card_background_upload_id: self.id).update_all(card_background_upload_id: nil)
- UserProfile.where(profile_background_upload_id: self.id).update_all(
+ UserProfile.where(card_background_upload_id: id).update_all(card_background_upload_id: nil)
+ UserProfile.where(profile_background_upload_id: id).update_all(
profile_background_upload_id: nil,
)
end
after_destroy do
- User.where(uploaded_avatar_id: self.id).update_all(uploaded_avatar_id: nil)
- UserAvatar.where(gravatar_upload_id: self.id).update_all(gravatar_upload_id: nil)
- UserAvatar.where(custom_upload_id: self.id).update_all(custom_upload_id: nil)
+ User.where(uploaded_avatar_id: id).update_all(uploaded_avatar_id: nil)
+ UserAvatar.where(gravatar_upload_id: id).update_all(gravatar_upload_id: nil)
+ UserAvatar.where(custom_upload_id: id).update_all(custom_upload_id: nil)
end
scope :by_users, -> { where("uploads.id > ?", SEEDED_ID_THRESHOLD) }
@@ -118,7 +118,7 @@ class Upload < ActiveRecord::Base
end
def self.with_no_non_post_relations
- self.joins(
+ joins(
"LEFT JOIN upload_references ur ON ur.upload_id = uploads.id AND ur.target_type != 'Post'",
).where("ur.upload_id IS NULL")
end
@@ -129,14 +129,14 @@ class Upload < ActiveRecord::Base
end
def to_s
- self.url
+ url
end
def to_markdown
UploadMarkdown.new(self).to_markdown
end
- def thumbnail(width = self.thumbnail_width, height = self.thumbnail_height)
+ def thumbnail(width = thumbnail_width, height = thumbnail_height)
optimized_images.find_by(width: width, height: height)
end
@@ -199,12 +199,12 @@ class Upload < ActiveRecord::Base
end
new_extension = image_info&.type&.to_s || "unknown"
- if new_extension != self.extension
- self.update_columns(extension: new_extension)
+ if new_extension != extension
+ update_columns(extension: new_extension)
true
end
rescue StandardError
- self.update_columns(extension: "unknown")
+ update_columns(extension: "unknown")
true
end
end
@@ -234,7 +234,7 @@ class Upload < ActiveRecord::Base
end
def short_path
- self.class.short_path(sha1: self.sha1, extension: self.extension)
+ self.class.short_path(sha1: sha1, extension: extension)
end
def self.consider_for_reuse(upload, post)
@@ -277,7 +277,7 @@ class Upload < ActiveRecord::Base
def self.short_path(sha1:, extension:)
@url_helpers ||= Rails.application.routes.url_helpers
- @url_helpers.upload_short_path(base62: self.base62_sha1(sha1), extension: extension)
+ @url_helpers.upload_short_path(base62: base62_sha1(sha1), extension: extension)
end
def self.base62_sha1(sha1)
@@ -285,7 +285,7 @@ class Upload < ActiveRecord::Base
end
def base62_sha1
- Upload.base62_sha1(self.sha1)
+ Upload.base62_sha1(sha1)
end
def local?
@@ -326,7 +326,7 @@ class Upload < ActiveRecord::Base
self.thumbnail_width, self.thumbnail_height = ImageSizer.resize(w, h)
- self.update_columns(
+ update_columns(
width: width,
height: height,
thumbnail_width: thumbnail_width,
@@ -430,7 +430,7 @@ class Upload < ActiveRecord::Base
end
if persisted?
- self.update_column(:dominant_color, color)
+ update_column(:dominant_color, color)
else
self.dominant_color = color
end
@@ -455,11 +455,11 @@ class Upload < ActiveRecord::Base
end
def self.sha1_from_short_path(path)
- self.sha1_from_base62_encoded($2) if path =~ %r{(/uploads/short-url/)([a-zA-Z0-9]+)(\..*)?}
+ sha1_from_base62_encoded($2) if path =~ %r{(/uploads/short-url/)([a-zA-Z0-9]+)(\..*)?}
end
def self.sha1_from_short_url(url)
- self.sha1_from_base62_encoded($2) if url =~ %r{(upload://)?([a-zA-Z0-9]+)(\..*)?}
+ sha1_from_base62_encoded($2) if url =~ %r{(upload://)?([a-zA-Z0-9]+)(\..*)?}
end
def self.sha1_from_long_url(url)
@@ -482,11 +482,11 @@ class Upload < ActiveRecord::Base
end
def human_filesize
- number_to_human_size(self.filesize)
+ number_to_human_size(filesize)
end
def rebake_posts_on_old_scheme
- self.posts.where("cooked LIKE '%/_optimized/%'").find_each(&:rebake!)
+ posts.where("cooked LIKE '%/_optimized/%'").find_each(&:rebake!)
end
def update_secure_status(source: "unknown", override: nil)
@@ -497,8 +497,8 @@ class Upload < ActiveRecord::Base
reason = "manually overridden"
end
- secure_status_did_change = self.secure? != mark_secure
- self.update(secure_params(mark_secure, reason, source))
+ secure_status_did_change = secure? != mark_secure
+ update(secure_params(mark_secure, reason, source))
if secure_status_did_change && Discourse.store.external?
Discourse.store.update_upload_access_control(self)
diff --git a/app/models/user.rb b/app/models/user.rb
index 7b2daf1f646..6b9f26dc338 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -181,10 +181,10 @@ class User < ActiveRecord::Base
after_create :set_default_categories_preferences
after_create :set_default_tags_preferences
after_create :set_default_sidebar_section_links
- after_update :set_default_sidebar_section_links, if: Proc.new { self.saved_change_to_staged? }
+ after_update :set_default_sidebar_section_links, if: Proc.new { saved_change_to_staged? }
after_update :trigger_user_updated_event,
- if: Proc.new { self.human? && self.saved_change_to_uploaded_avatar_id? }
+ if: Proc.new { human? && saved_change_to_uploaded_avatar_id? }
after_update :trigger_user_automatic_group_refresh, if: :saved_change_to_staged?
after_update :change_display_name, if: :saved_change_to_name?
@@ -198,7 +198,7 @@ class User < ActiveRecord::Base
after_save do
if saved_change_to_uploaded_avatar_id?
- UploadReference.ensure_exist!(upload_ids: [self.uploaded_avatar_id], target: self)
+ UploadReference.ensure_exist!(upload_ids: [uploaded_avatar_id], target: self)
end
end
@@ -207,33 +207,33 @@ class User < ActiveRecord::Base
before_destroy do
# These tables don't have primary keys, so destroying them with activerecord is tricky:
- PostTiming.where(user_id: self.id).delete_all
- TopicViewItem.where(user_id: self.id).delete_all
+ PostTiming.where(user_id: id).delete_all
+ TopicViewItem.where(user_id: id).delete_all
UserAction.where(
"user_id = :user_id OR target_user_id = :user_id OR acting_user_id = :user_id",
- user_id: self.id,
+ user_id: id,
).delete_all
# we need to bypass the default scope here, which appears not bypassed for :delete_all
# however :destroy it is bypassed
- PostAction.with_deleted.where(user_id: self.id).delete_all
+ PostAction.with_deleted.where(user_id: id).delete_all
# This is a perf optimisation to ensure we hit the index
# without this we need to scan a much larger number of rows
DirectoryItem
- .where(user_id: self.id)
+ .where(user_id: id)
.where("period_type in (?)", DirectoryItem.period_types.values)
.delete_all
# our relationship filters on enabled, this makes sure everything is deleted
- UserSecurityKey.where(user_id: self.id).delete_all
+ UserSecurityKey.where(user_id: id).delete_all
- Developer.where(user_id: self.id).delete_all
- DraftSequence.where(user_id: self.id).delete_all
- GivenDailyLike.where(user_id: self.id).delete_all
- MutedUser.where(user_id: self.id).or(MutedUser.where(muted_user_id: self.id)).delete_all
- IgnoredUser.where(user_id: self.id).or(IgnoredUser.where(ignored_user_id: self.id)).delete_all
- UserAvatar.where(user_id: self.id).delete_all
+ Developer.where(user_id: id).delete_all
+ DraftSequence.where(user_id: id).delete_all
+ GivenDailyLike.where(user_id: id).delete_all
+ MutedUser.where(user_id: id).or(MutedUser.where(muted_user_id: id)).delete_all
+ IgnoredUser.where(user_id: id).or(IgnoredUser.where(ignored_user_id: id)).delete_all
+ UserAvatar.where(user_id: id).delete_all
end
# Skip validating email, for example from a particular auth provider plugin
@@ -388,7 +388,7 @@ class User < ActiveRecord::Base
def secured_sidebar_category_ids(user_guardian = nil)
user_guardian ||= guardian
- SidebarSectionLink.where(user_id: self.id, linkable_type: "Category").pluck(:linkable_id) &
+ SidebarSectionLink.where(user_id: id, linkable_type: "Category").pluck(:linkable_id) &
user_guardian.allowed_category_ids
end
@@ -397,7 +397,7 @@ class User < ActiveRecord::Base
DiscourseTagging.filter_visible(
Tag.where(
- id: SidebarSectionLink.where(user_id: self.id, linkable_type: "Tag").select(:linkable_id),
+ id: SidebarSectionLink.where(user_id: id, linkable_type: "Tag").select(:linkable_id),
),
user_guardian,
)
@@ -475,16 +475,16 @@ class User < ActiveRecord::Base
end
def human?
- User.human_user_id?(self.id)
+ User.human_user_id?(id)
end
def bot?
- !self.human?
+ !human?
end
def effective_locale
- if SiteSetting.allow_user_locale && self.locale.present? && I18n.locale_available?(self.locale)
- self.locale
+ if SiteSetting.allow_user_locale && locale.present? && I18n.locale_available?(locale)
+ locale
else
SiteSetting.default_locale
end
@@ -507,11 +507,11 @@ class User < ActiveRecord::Base
end
def unstage!
- if self.staged
+ if staged
ActiveRecord::Base.transaction do
self.staged = false
- self.custom_fields[FROM_STAGED] = true
- self.notifications.destroy_all
+ custom_fields[FROM_STAGED] = true
+ notifications.destroy_all
save!
end
@@ -534,9 +534,9 @@ class User < ActiveRecord::Base
def self.find_by_email(email, primary: false)
if primary
- self.with_primary_email(Email.downcase(email)).first
+ with_primary_email(Email.downcase(email)).first
else
- self.with_email(Email.downcase(email)).first
+ with_email(Email.downcase(email)).first
end
end
@@ -638,8 +638,8 @@ class User < ActiveRecord::Base
.joins(:invited_users)
.where(
"invited_users.user_id = ? AND invited_users.redeemed_at <= ?",
- self.id,
- self.created_at + invite_redemption_delay,
+ id,
+ created_at + invite_redemption_delay,
)
.first
used_invite.try(:invited_by)
@@ -713,7 +713,7 @@ class User < ActiveRecord::Base
MAX_UNREAD_BACKLOG = 400
def grouped_unread_notifications
- results = DB.query(<<~SQL, user_id: self.id, limit: MAX_UNREAD_BACKLOG)
+ results = DB.query(<<~SQL, user_id: id, limit: MAX_UNREAD_BACKLOG)
SELECT X.notification_type AS type, COUNT(*) FROM (
SELECT n.notification_type
FROM notifications n
@@ -735,8 +735,8 @@ class User < ActiveRecord::Base
def new_personal_messages_notifications_count
args = {
- user_id: self.id,
- seen_notification_id: self.seen_notification_id,
+ user_id: id,
+ seen_notification_id: seen_notification_id,
private_message: Notification.types[:private_message],
}
@@ -828,7 +828,7 @@ class User < ActiveRecord::Base
end
def bump_last_seen_notification!
- query = self.notifications.visible
+ query = notifications.visible
query = query.where("notifications.id > ?", seen_notification_id) if seen_notification_id
if max_notification_id = query.maximum(:id)
update!(seen_notification_id: max_notification_id)
@@ -852,19 +852,19 @@ class User < ActiveRecord::Base
def publish_reviewable_counts(extra_data = nil)
data = {
- reviewable_count: self.reviewable_count,
+ reviewable_count: reviewable_count,
unseen_reviewable_count: Reviewable.unseen_reviewable_count(self),
}
data.merge!(extra_data) if extra_data.present?
- MessageBus.publish("/reviewable_counts/#{self.id}", data, user_ids: [self.id])
+ MessageBus.publish("/reviewable_counts/#{id}", data, user_ids: [id])
end
def read_first_notification?
- self.seen_notification_id != 0 || user_option.skip_new_user_tips
+ seen_notification_id != 0 || user_option.skip_new_user_tips
end
def publish_notifications_state
- return if !self.allow_live_notifications?
+ return if !allow_live_notifications?
# publish last notification json with the message so we can apply an update
notification = notifications.visible.order("notifications.created_at desc").first
@@ -1033,9 +1033,7 @@ class User < ActiveRecord::Base
def new_user_posting_on_first_day?
return false if staff?
return false if trust_level >= TrustLevel[2]
- if self.first_post_created_at.present? && self.first_post_created_at <= 24.hours.ago
- return false
- end
+ return false if first_post_created_at.present? && first_post_created_at <= 24.hours.ago
true
end
@@ -1077,7 +1075,7 @@ class User < ActiveRecord::Base
return if timezone.blank? || !TimezoneValidator.valid?(timezone)
# we only want to update the user's timezone if they have not set it themselves
- UserOption.where(user_id: self.id, timezone: nil).update_all(timezone: timezone)
+ UserOption.where(user_id: id, timezone: nil).update_all(timezone: timezone)
end
def update_posts_read!(num_posts, opts = {})
@@ -1168,19 +1166,19 @@ class User < ActiveRecord::Base
def update_last_seen!(now = Time.zone.now, force: false)
if !force
- return if !User.should_update_last_seen?(self.id, now)
+ return if !User.should_update_last_seen?(id, now)
end
update_previous_visit(now)
# using update_column to avoid the AR transaction
update_column(:last_seen_at, now)
- update_column(:first_seen_at, now) unless self.first_seen_at
+ update_column(:first_seen_at, now) unless first_seen_at
DiscourseEvent.trigger(:user_seen, self)
end
def self.gravatar_template(email)
- "//#{SiteSetting.gravatar_base_url}/avatar/#{self.email_hash(email)}.png?s={size}&r=pg&d=identicon"
+ "//#{SiteSetting.gravatar_base_url}/avatar/#{email_hash(email)}.png?s={size}&r=pg&d=identicon"
end
# Don't pass this up to the client - it's meant for server side use
@@ -1328,7 +1326,7 @@ class User < ActiveRecord::Base
return false if staff? || (trust_level != TrustLevel[0])
# ... your own topics or in private messages
topic = Topic.where(id: topic_id).first
- return false if topic.try(:private_message?) || (topic.try(:user_id) == self.id)
+ return false if topic.try(:private_message?) || (topic.try(:user_id) == id)
last_action_in_topic = UserAction.last_action_in_topic(id, topic_id)
since_reply = Post.where(user_id: id, topic_id: topic_id)
@@ -1462,13 +1460,13 @@ class User < ActiveRecord::Base
end
def activate
- email_token = self.email_tokens.create!(email: self.email, scope: EmailToken.scopes[:signup])
+ email_token = email_tokens.create!(email: email, scope: EmailToken.scopes[:signup])
EmailToken.confirm(email_token.token, scope: EmailToken.scopes[:signup])
reload
end
def deactivate(performed_by)
- self.update!(active: false)
+ update!(active: false)
if reviewable = ReviewableUser.pending.find_by(target: self)
reviewable.perform(performed_by, :delete_user)
@@ -1531,7 +1529,7 @@ class User < ActiveRecord::Base
def secure_category_ids
cats =
- if self.admin? && !SiteSetting.suppress_secured_categories_from_admin
+ if admin? && !SiteSetting.suppress_secured_categories_from_admin
Category.unscoped.where(read_restricted: true)
else
secure_categories.references(:categories)
@@ -1599,14 +1597,14 @@ class User < ActiveRecord::Base
avatar = user_avatar || create_user_avatar
- if self.primary_email.present? && SiteSetting.automatically_download_gravatars? &&
+ if primary_email.present? && SiteSetting.automatically_download_gravatars? &&
!avatar.last_gravatar_download_attempt
- Jobs.cancel_scheduled_job(:update_gravatar, user_id: self.id, avatar_id: avatar.id)
- Jobs.enqueue_in(1.second, :update_gravatar, user_id: self.id, avatar_id: avatar.id)
+ Jobs.cancel_scheduled_job(:update_gravatar, user_id: id, avatar_id: avatar.id)
+ Jobs.enqueue_in(1.second, :update_gravatar, user_id: id, avatar_id: avatar.id)
end
# mark all the user's quoted posts as "needing a rebake"
- Post.rebake_all_quoted_posts(self.id) if saved_change_to_uploaded_avatar_id?
+ Post.rebake_all_quoted_posts(id) if saved_change_to_uploaded_avatar_id?
end
def first_post_created_at
@@ -1674,7 +1672,7 @@ class User < ActiveRecord::Base
end
def number_of_deleted_posts
- Post.with_deleted.where(user_id: self.id).where.not(deleted_at: nil).count
+ Post.with_deleted.where(user_id: id).where.not(deleted_at: nil).count
end
def number_of_flags
@@ -1692,7 +1690,7 @@ class User < ActiveRecord::Base
def number_of_flags_given
PostAction
- .where(user_id: self.id)
+ .where(user_id: id)
.where(disagreed_at: nil)
.where(post_action_type_id: post_action_type_view.notify_flag_type_ids)
.count
@@ -1738,14 +1736,14 @@ class User < ActiveRecord::Base
end
def logged_out
- MessageBus.publish "/logout/#{self.id}", self.id, user_ids: [self.id]
+ MessageBus.publish "/logout/#{id}", id, user_ids: [id]
DiscourseEvent.trigger(:user_logged_out, self)
end
def logged_in
DiscourseEvent.trigger(:user_logged_in, self)
- DiscourseEvent.trigger(:user_first_logged_in, self) if !self.seen_before?
+ DiscourseEvent.trigger(:user_first_logged_in, self) if !seen_before?
end
def set_automatic_groups
@@ -1789,16 +1787,15 @@ class User < ActiveRecord::Base
end
def emails
- self.user_emails.order("user_emails.primary DESC NULLS LAST").pluck(:email)
+ user_emails.order("user_emails.primary DESC NULLS LAST").pluck(:email)
end
def secondary_emails
- self.user_emails.secondary.pluck(:email)
+ user_emails.secondary.pluck(:email)
end
def unconfirmed_emails
- self
- .email_change_requests
+ email_change_requests
.where.not(change_state: EmailChangeRequest.states[:complete])
.pluck(:new_email)
end
@@ -1821,7 +1818,7 @@ class User < ActiveRecord::Base
def recent_time_read
@recent_time_read ||=
- self.user_visits.where("visited_at >= ?", RECENT_TIME_READ_THRESHOLD.ago).sum(:time_read)
+ user_visits.where("visited_at >= ?", RECENT_TIME_READ_THRESHOLD.ago).sum(:time_read)
end
def from_staged?
@@ -1829,7 +1826,7 @@ class User < ActiveRecord::Base
end
def mature_staged?
- from_staged? && self.created_at && self.created_at < 1.day.ago
+ from_staged? && created_at && created_at < 1.day.ago
end
def next_best_title
@@ -1850,14 +1847,14 @@ class User < ActiveRecord::Base
return unless SiteSetting.must_approve_users? || SiteSetting.invite_only?
return if approved?
- Jobs.enqueue(:create_user_reviewable, user_id: self.id)
+ Jobs.enqueue(:create_user_reviewable, user_id: id)
end
def has_more_posts_than?(max_post_count)
return true if user_stat && (user_stat.topic_count + user_stat.post_count) > max_post_count
return true if max_post_count < 0
- DB.query_single(<<~SQL, user_id: self.id).first > max_post_count
+ DB.query_single(<<~SQL, user_id: id).first > max_post_count
SELECT COUNT(1)
FROM (
SELECT 1
@@ -1887,7 +1884,7 @@ class User < ActiveRecord::Base
def create_or_fetch_secure_identifier
return secure_identifier if secure_identifier.present?
new_secure_identifier = SecureRandom.hex(20)
- self.update(secure_identifier: new_secure_identifier)
+ update(secure_identifier: new_secure_identifier)
new_secure_identifier
end
@@ -1923,7 +1920,7 @@ class User < ActiveRecord::Base
end
def shelved_notifications
- ShelvedNotification.joins(:notification).where("notifications.user_id = ?", self.id)
+ ShelvedNotification.joins(:notification).where("notifications.user_id = ?", id)
end
def allow_live_notifications?
@@ -1994,12 +1991,9 @@ class User < ActiveRecord::Base
end
def similar_users
- return User.none if self.ip_address.blank?
+ return User.none if ip_address.blank?
- User
- .real
- .where.not(id: self.id)
- .where(ip_address: self.ip_address, admin: false, moderator: false)
+ User.real.where.not(id: id).where(ip_address: ip_address, admin: false, moderator: false)
end
def upcoming_change_enabled?(upcoming_change)
@@ -2073,7 +2067,7 @@ class User < ActiveRecord::Base
end
def update_usernames
- self.username.unicode_normalize!
+ username.unicode_normalize!
self.username_lower = username.downcase
end
@@ -2100,7 +2094,7 @@ class User < ActiveRecord::Base
DB.query(USERNAME_EXISTS_SQL, username: self.class.normalize_username(username))
user_id = existing.select { |u| u.is_user }.first&.id
- same_user = user_id && user_id == self.id
+ same_user = user_id && user_id == id
errors.add(:username, I18n.t(:"user.username.unique")) if existing.present? && !same_user
@@ -2121,7 +2115,7 @@ class User < ActiveRecord::Base
end
def set_default_categories_preferences
- return if self.staged?
+ return if staged?
values = []
@@ -2138,7 +2132,7 @@ class User < ActiveRecord::Base
category_ids.each do |category_id|
next if category_id == 0
values << {
- user_id: self.id,
+ user_id: id,
category_id: category_id,
notification_level: CategoryUser.notification_levels[setting.to_sym],
}
@@ -2149,7 +2143,7 @@ class User < ActiveRecord::Base
end
def set_default_tags_preferences
- return if self.staged?
+ return if staged?
values = []
@@ -2169,7 +2163,7 @@ class User < ActiveRecord::Base
.pluck(:id)
.each do |tag_id|
values << {
- user_id: self.id,
+ user_id: id,
tag_id: tag_id,
notification_level: TagUser.notification_levels[setting.to_sym],
created_at: now,
@@ -2310,14 +2304,14 @@ class User < ActiveRecord::Base
end
def set_skip_validate_email
- self.primary_email.skip_validate_email = !should_validate_email_address? if self.primary_email
+ primary_email.skip_validate_email = !should_validate_email_address? if primary_email
true
end
def check_site_contact_username
if (saved_change_to_admin? || saved_change_to_moderator?) &&
- self.username == SiteSetting.site_contact_username && !staff?
+ username == SiteSetting.site_contact_username && !staff?
SiteSetting.set_and_log(:site_contact_username, SiteSetting.defaults[:site_contact_username])
end
end
diff --git a/app/models/user_action.rb b/app/models/user_action.rb
index 90714e8ce0d..7ec0ae87d67 100644
--- a/app/models/user_action.rb
+++ b/app/models/user_action.rb
@@ -277,10 +277,10 @@ class UserAction < ActiveRecord::Base
# TODO there are conditions when this is called and user_id was already rolled back and is invalid.
# protect against dupes, for some reason this is failing in some cases
- action = self.find_by(hash.select { |k, _| required_parameters.include?(k) })
+ action = find_by(hash.select { |k, _| required_parameters.include?(k) })
return action if action
- action = self.new(hash)
+ action = new(hash)
action.created_at = hash[:created_at] if hash[:created_at]
action.save!
@@ -382,7 +382,7 @@ class UserAction < ActiveRecord::Base
end
def self.ensure_consistency!(limit = nil)
- self.synchronize_target_topic_ids(nil, limit: limit)
+ synchronize_target_topic_ids(nil, limit: limit)
end
def self.update_like_count(user_id, action_type, delta)
diff --git a/app/models/user_api_key.rb b/app/models/user_api_key.rb
index 868ea60bc87..67d39d52b03 100644
--- a/app/models/user_api_key.rb
+++ b/app/models/user_api_key.rb
@@ -18,7 +18,7 @@ class UserApiKey < ActiveRecord::Base
after_initialize :generate_key
def generate_key
- if !self.key_hash
+ if !key_hash
@key ||= SecureRandom.hex
self.key_hash = ApiKey.hash_key(@key)
end
@@ -41,15 +41,12 @@ class UserApiKey < ActiveRecord::Base
def update_last_used(client_id)
update_args = { last_used_at: Time.zone.now }
- if client_id.present? && client_id != self.client.client_id
+ if client_id.present? && client_id != client.client_id
new_client =
- UserApiKeyClient.create!(
- client_id: client_id,
- application_name: self.client.application_name,
- )
+ UserApiKeyClient.create!(client_id: client_id, application_name: client.application_name)
update_args[:user_api_key_client_id] = new_client.id
end
- self.update_columns(**update_args)
+ update_columns(**update_args)
end
# Scopes allowed to be requested by external services
diff --git a/app/models/user_associated_account.rb b/app/models/user_associated_account.rb
index edee848feb0..700bbe09fa7 100644
--- a/app/models/user_associated_account.rb
+++ b/app/models/user_associated_account.rb
@@ -6,7 +6,7 @@ class UserAssociatedAccount < ActiveRecord::Base
def self.cleanup!
# This happens when a user starts the registration flow, but doesn't complete it
# Keeping the rows doesn't cause any technical issue, but we shouldn't store PII unless it's attached to a user
- self.where("user_id IS NULL AND updated_at < ?", 1.day.ago).delete_all
+ where("user_id IS NULL AND updated_at < ?", 1.day.ago).delete_all
end
end
diff --git a/app/models/user_auth_token.rb b/app/models/user_auth_token.rb
index d77e400224d..6d5f6bb594d 100644
--- a/app/models/user_auth_token.rb
+++ b/app/models/user_auth_token.rb
@@ -22,11 +22,11 @@ class UserAuthToken < ActiveRecord::Base
before_destroy do
UserAuthToken.log_verbose(
action: "destroy",
- user_auth_token_id: self.id,
- user_id: self.user_id,
- user_agent: self.user_agent,
- client_ip: self.client_ip,
- auth_token: self.auth_token,
+ user_auth_token_id: id,
+ user_id: user_id,
+ user_agent: user_agent,
+ client_ip: client_ip,
+ auth_token: auth_token,
)
end
@@ -259,7 +259,7 @@ class UserAuthToken < ActiveRecord::Base
rotated_at = :now
WHERE id = :id AND (auth_token_seen or rotated_at < :safeguard_time)
",
- id: self.id,
+ id: id,
user_agent: user_agent,
client_ip: client_ip&.to_s,
now: Time.zone.now,
diff --git a/app/models/user_avatar.rb b/app/models/user_avatar.rb
index 2b40ef99272..6491f2465fe 100644
--- a/app/models/user_avatar.rb
+++ b/app/models/user_avatar.rb
@@ -8,7 +8,7 @@ class UserAvatar < ActiveRecord::Base
after_save do
if saved_change_to_custom_upload_id? || saved_change_to_gravatar_upload_id?
- upload_ids = [self.custom_upload_id, self.gravatar_upload_id]
+ upload_ids = [custom_upload_id, gravatar_upload_id]
UploadReference.ensure_exist!(upload_ids: upload_ids, target: self)
end
end
@@ -27,7 +27,7 @@ class UserAvatar < ActiveRecord::Base
def update_gravatar!
DistributedMutex.synchronize("update_gravatar_#{user_id}") do
- self.update!(last_gravatar_download_attempt: Time.zone.now)
+ update!(last_gravatar_download_attempt: Time.zone.now)
max = Discourse.avatar_sizes.max
@@ -72,7 +72,7 @@ class UserAvatar < ActiveRecord::Base
user.update!(uploaded_avatar_id: upload.id)
end
- self.update!(gravatar_upload: upload)
+ update!(gravatar_upload: upload)
end
end
end
@@ -84,7 +84,7 @@ class UserAvatar < ActiveRecord::Base
end
def self.local_avatar_url(hostname, username, upload_id, size)
- self.local_avatar_template(hostname, username, upload_id).gsub("{size}", size.to_s)
+ local_avatar_template(hostname, username, upload_id).gsub("{size}", size.to_s)
end
def self.local_avatar_template(hostname, username, upload_id)
@@ -93,7 +93,7 @@ class UserAvatar < ActiveRecord::Base
end
def self.external_avatar_url(user_id, upload_id, size)
- self.external_avatar_template(user_id, upload_id).gsub("{size}", size.to_s)
+ external_avatar_template(user_id, upload_id).gsub("{size}", size.to_s)
end
def self.external_avatar_template(user_id, upload_id)
diff --git a/app/models/user_badge.rb b/app/models/user_badge.rb
index a116f37caa3..e50aa6d3dc2 100644
--- a/app/models/user_badge.rb
+++ b/app/models/user_badge.rb
@@ -51,25 +51,25 @@ class UserBadge < ActiveRecord::Base
validates :granted_by, presence: true
after_create do
- Badge.increment_counter "grant_count", self.badge_id
- user_ids = [self.user_id]
+ Badge.increment_counter "grant_count", badge_id
+ user_ids = [user_id]
UserStat.update_distinct_badge_count(user_ids)
UserBadge.update_featured_ranks!(user_ids)
- self.trigger_user_badge_granted_event
+ trigger_user_badge_granted_event
end
after_destroy do
- Badge.decrement_counter "grant_count", self.badge_id
- user_ids = [self.user_id]
+ Badge.decrement_counter "grant_count", badge_id
+ user_ids = [user_id]
UserStat.update_distinct_badge_count(user_ids)
UserBadge.update_featured_ranks!(user_ids)
- DiscourseEvent.trigger(:user_badge_removed, self.badge_id, self.user_id)
+ DiscourseEvent.trigger(:user_badge_removed, badge_id, user_id)
DiscourseEvent.trigger(:user_badge_revoked, user_badge: self)
end
def self.ensure_consistency!(user_ids = [])
- self.update_featured_ranks!(user_ids)
+ update_featured_ranks!(user_ids)
end
def self.update_featured_ranks!(user_ids = [])
@@ -120,11 +120,11 @@ class UserBadge < ActiveRecord::Base
private
def trigger_user_badge_granted_event
- self.class.trigger_user_badge_granted_event(self.badge_id, self.user_id)
+ self.class.trigger_user_badge_granted_event(badge_id, user_id)
end
def single_grant_badge?
- self.badge ? self.badge.single_grant? : true
+ badge ? badge.single_grant? : true
end
end
diff --git a/app/models/user_email.rb b/app/models/user_email.rb
index ff07c634c6b..19810374e6b 100644
--- a/app/models/user_email.rb
+++ b/app/models/user_email.rb
@@ -19,9 +19,9 @@ class UserEmail < ActiveRecord::Base
scope :secondary, -> { where(primary: false) }
- before_save -> { destroy_email_tokens(self.email_was) }, if: :will_save_change_to_email?
+ before_save -> { destroy_email_tokens(email_was) }, if: :will_save_change_to_email?
- after_destroy { destroy_email_tokens(self.email) }
+ after_destroy { destroy_email_tokens(email) }
def self.ensure_consistency!
user_ids_without_primary_email = DB.query_single <<~SQL
SELECT u.id
@@ -42,8 +42,8 @@ class UserEmail < ActiveRecord::Base
def normalize_email
self.normalized_email =
- if self.email.present?
- username, domain = self.email.split("@", 2)
+ if email.present?
+ username, domain = email.split("@", 2)
username = username.gsub(".", "").gsub(/\+.*/, "")
"#{username}@#{domain}"
end
@@ -52,24 +52,24 @@ class UserEmail < ActiveRecord::Base
private
def strip_downcase_email
- if self.email
- self.email = self.email.strip
- self.email = self.email.downcase
+ if email
+ self.email = email.strip
+ self.email = email.downcase
end
end
def validate_email?
- return false if self.skip_validate_email
+ return false if skip_validate_email
email_changed?
end
def validate_unique_email?
- return false if self.skip_validate_unique_email
+ return false if skip_validate_unique_email
will_save_change_to_email?
end
def normalize_emails?
- return false if self.skip_normalize_email
+ return false if skip_normalize_email
SiteSetting.normalize_emails?
end
@@ -79,7 +79,7 @@ class UserEmail < ActiveRecord::Base
scope = scope.where.not(id: id) if persisted?
email_exists =
- if self.normalize_emails?
+ if normalize_emails?
scope.where(
"lower(email) = ? OR lower(normalized_email) = ?",
email,
@@ -89,12 +89,12 @@ class UserEmail < ActiveRecord::Base
scope.where("lower(email) = ?", email).exists?
end
- self.errors.add(:email, :taken) if email_exists
+ errors.add(:email, :taken) if email_exists
end
def user_id_not_changed
- if self.will_save_change_to_user_id? && self.persisted?
- self.errors.add(
+ if will_save_change_to_user_id? && persisted?
+ errors.add(
:user_id,
I18n.t(
"activerecord.errors.models.user_email.attributes.user_id.reassigning_primary_email",
diff --git a/app/models/user_export.rb b/app/models/user_export.rb
index 66ab3b80af8..1d14b03f038 100644
--- a/app/models/user_export.rb
+++ b/app/models/user_export.rb
@@ -9,7 +9,7 @@ class UserExport < ActiveRecord::Base
after_save do
if saved_change_to_upload_id?
- UploadReference.ensure_exist!(upload_ids: [self.upload_id], target: self)
+ UploadReference.ensure_exist!(upload_ids: [upload_id], target: self)
end
end
diff --git a/app/models/user_field.rb b/app/models/user_field.rb
index ffca053d5ac..4041aa15d87 100644
--- a/app/models/user_field.rb
+++ b/app/models/user_field.rb
@@ -39,7 +39,7 @@ class UserField < ActiveRecord::Base
end
def queue_index_search
- Jobs.enqueue(:index_user_fields_for_search, user_field_id: self.id)
+ Jobs.enqueue(:index_user_fields_for_search, user_field_id: id)
end
private
@@ -53,7 +53,7 @@ class UserField < ActiveRecord::Base
def sanitize_description
if description_changed?
- self.description = sanitize_field(self.description, additional_attributes: ["target"])
+ self.description = sanitize_field(description, additional_attributes: ["target"])
end
end
end
diff --git a/app/models/user_history.rb b/app/models/user_history.rb
index 6885bb42c39..b63bfb4b5a3 100644
--- a/app/models/user_history.rb
+++ b/app/models/user_history.rb
@@ -410,12 +410,12 @@ class UserHistory < ActiveRecord::Base
end
def self.for(user, action_type)
- self.where(target_user_id: user.id, action: UserHistory.actions[action_type])
+ where(target_user_id: user.id, action: UserHistory.actions[action_type])
end
def self.exists_for_user?(user, action_type, opts = nil)
opts = opts || {}
- result = self.where(target_user_id: user.id, action: UserHistory.actions[action_type])
+ result = where(target_user_id: user.id, action: UserHistory.actions[action_type])
result = result.where(topic_id: opts[:topic_id]) if opts[:topic_id]
result.exists?
end
@@ -431,12 +431,11 @@ class UserHistory < ActiveRecord::Base
if custom_staff
opts[:custom_type] = opts[:action_name]
else
- opts[:action_id] = self.actions[opts[:action_name].to_sym] if opts[:action_name]
+ opts[:action_id] = actions[opts[:action_name].to_sym] if opts[:action_name]
end
query =
- self
- .with_filters(opts.slice(*staff_filters))
+ with_filters(opts.slice(*staff_filters))
.only_staff_actions
.order("id DESC")
.includes(:acting_user, :target_user, :topic, :post, :category)
@@ -450,7 +449,7 @@ class UserHistory < ActiveRecord::Base
end
def set_admin_only
- self.admin_only = UserHistory.admin_only_action_ids.include?(self.action)
+ self.admin_only = UserHistory.admin_only_action_ids.include?(action)
self
end
diff --git a/app/models/user_option.rb b/app/models/user_option.rb
index b0ec5189d51..e8e2cff0787 100644
--- a/app/models/user_option.rb
+++ b/app/models/user_option.rb
@@ -142,7 +142,7 @@ class UserOption < ActiveRecord::Base
Jobs.enqueue_in(
delay / 2,
:update_top_redirection,
- user_id: self.user_id,
+ user_id: user_id,
redirected_at: Time.zone.now.to_s,
)
end
diff --git a/app/models/user_password.rb b/app/models/user_password.rb
index 77e10635f53..8471a121d19 100644
--- a/app/models/user_password.rb
+++ b/app/models/user_password.rb
@@ -21,7 +21,7 @@ class UserPassword < ActiveRecord::Base
def password=(pw)
return if pw.blank?
- self.password_hash_will_change!
+ password_hash_will_change!
@raw_password = pw
end
diff --git a/app/models/user_profile.rb b/app/models/user_profile.rb
index fffd274d881..8a7a2ab1c1a 100644
--- a/app/models/user_profile.rb
+++ b/app/models/user_profile.rb
@@ -35,8 +35,8 @@ class UserProfile < ActiveRecord::Base
if saved_change_to_profile_background_upload_id? ||
saved_change_to_card_background_upload_id? || saved_change_to_bio_raw?
upload_ids =
- [self.profile_background_upload_id, self.card_background_upload_id] +
- Upload.extract_upload_ids(self.bio_raw)
+ [profile_background_upload_id, card_background_upload_id] +
+ Upload.extract_upload_ids(bio_raw)
UploadReference.ensure_exist!(upload_ids: upload_ids, target: self)
end
end
@@ -62,24 +62,24 @@ class UserProfile < ActiveRecord::Base
end
def recook_bio
- self.bio_raw_will_change!
+ bio_raw_will_change!
cook
end
def upload_card_background(upload)
- self.update!(card_background_upload: upload)
+ update!(card_background_upload: upload)
end
def clear_card_background
- self.update!(card_background_upload: nil)
+ update!(card_background_upload: nil)
end
def upload_profile_background(upload)
- self.update!(profile_background_upload: upload)
+ update!(profile_background_upload: upload)
end
def clear_profile_background
- self.update!(profile_background_upload: nil)
+ update!(profile_background_upload: nil)
end
def self.rebake_old(limit)
@@ -153,7 +153,7 @@ class UserProfile < ActiveRecord::Base
Jobs.enqueue_in(
SiteSetting.editing_grace_period,
:pull_user_profile_hotlinked_images,
- user_id: self.user_id,
+ user_id: user_id,
)
end
end
@@ -165,9 +165,9 @@ class UserProfile < ActiveRecord::Base
end
def cooked
- if self.bio_raw.present?
+ if bio_raw.present?
PrettyText.cook(
- self.bio_raw,
+ bio_raw,
omit_nofollow: user.has_trust_level?(TrustLevel[3]) && !SiteSetting.tl3_links_no_follow,
)
else
@@ -176,7 +176,7 @@ class UserProfile < ActiveRecord::Base
end
def cook
- if self.bio_raw.present?
+ if bio_raw.present?
if bio_raw_changed?
self.bio_cooked = cooked
self.bio_cooked_version = BAKED_VERSION
@@ -192,19 +192,19 @@ class UserProfile < ActiveRecord::Base
def website_domain_validator
allowed_domains = SiteSetting.allowed_user_website_domains
- return if allowed_domains.blank? || self.website.blank?
+ return if allowed_domains.blank? || website.blank?
domain =
begin
- URI.parse(self.website).host
+ URI.parse(website).host
rescue URI::Error
end
if allowed_domains.split("|").exclude?(domain)
- self.errors.add :base,
- I18n.t(
- "user.website.domain_not_allowed",
- domains: allowed_domains.split("|").join(", "),
- )
+ errors.add :base,
+ I18n.t(
+ "user.website.domain_not_allowed",
+ domains: allowed_domains.split("|").join(", "),
+ )
end
end
diff --git a/app/models/user_profile_view.rb b/app/models/user_profile_view.rb
index 0acbc244849..389d547286f 100644
--- a/app/models/user_profile_view.rb
+++ b/app/models/user_profile_view.rb
@@ -20,7 +20,7 @@ class UserProfileView < ActiveRecord::Base
skip_redis ||
Discourse.redis.expire(redis_key, SiteSetting.user_profile_view_duration_hours.hours)
- self.transaction do
+ transaction do
sql =
"INSERT INTO user_profile_views (user_profile_id, ip_address, viewed_at, user_id)
SELECT :user_profile_id, :ip_address, :viewed_at, :user_id
@@ -55,7 +55,7 @@ class UserProfileView < ActiveRecord::Base
end
def self.profile_views_by_day(start_date, end_date, group_id = nil)
- profile_views = self.where("viewed_at >= ? AND viewed_at < ?", start_date, end_date + 1.day)
+ profile_views = where("viewed_at >= ? AND viewed_at < ?", start_date, end_date + 1.day)
if group_id
profile_views =
profile_views.joins("INNER JOIN users ON users.id = user_profile_views.user_id")
diff --git a/app/models/user_second_factor.rb b/app/models/user_second_factor.rb
index 7223ec0aa30..854b0e143f3 100644
--- a/app/models/user_second_factor.rb
+++ b/app/models/user_second_factor.rb
@@ -23,7 +23,7 @@ class UserSecondFactor < ActiveRecord::Base
end
def totp_object
- get_totp_object(self.data)
+ get_totp_object(data)
end
def totp_provisioning_uri
@@ -33,8 +33,8 @@ class UserSecondFactor < ActiveRecord::Base
private
def count_per_user_does_not_exceed_limit
- if self.method == UserSecondFactor.methods[:totp]
- if self.class.where(method: self.method, user_id: self.user_id).count >= MAX_TOTPS_PER_USER
+ if method == UserSecondFactor.methods[:totp]
+ if self.class.where(method: method, user_id: user_id).count >= MAX_TOTPS_PER_USER
errors.add(:base, I18n.t("login.too_many_authenticators"))
end
end
diff --git a/app/models/user_security_key.rb b/app/models/user_security_key.rb
index 5e45cb0b4a6..75e03c65aa9 100644
--- a/app/models/user_security_key.rb
+++ b/app/models/user_security_key.rb
@@ -22,7 +22,7 @@ class UserSecurityKey < ActiveRecord::Base
private
def count_per_user_does_not_exceed_limit
- if UserSecurityKey.where(user_id: self.user_id).count >= MAX_KEYS_PER_USER
+ if UserSecurityKey.where(user_id: user_id).count >= MAX_KEYS_PER_USER
errors.add(:base, I18n.t("login.too_many_security_keys"))
end
end
diff --git a/app/models/user_stat.rb b/app/models/user_stat.rb
index 3023eb2adfa..091ac61dbb6 100644
--- a/app/models/user_stat.rb
+++ b/app/models/user_stat.rb
@@ -211,7 +211,7 @@ class UserStat < ActiveRecord::Base
end
def update_distinct_badge_count
- self.class.update_distinct_badge_count([self.user_id])
+ self.class.update_distinct_badge_count([user_id])
end
def self.update_draft_count(user_id = nil)
@@ -255,9 +255,9 @@ class UserStat < ActiveRecord::Base
#{start_time.nil? ? "" : "AND posts.created_at > ?"}
SQL
if start_time.nil?
- DB.query_single(sql, self.user_id).first
+ DB.query_single(sql, user_id).first
else
- DB.query_single(sql, self.user_id, start_time).first
+ DB.query_single(sql, user_id, start_time).first
end
end
@@ -313,7 +313,7 @@ class UserStat < ActiveRecord::Base
protected
def trigger_badges
- BadgeGranter.queue_badge_grant(Badge::Trigger::UserChange, user: self.user)
+ BadgeGranter.queue_badge_grant(Badge::Trigger::UserChange, user: user)
end
end
diff --git a/app/models/username_validator.rb b/app/models/username_validator.rb
index 08380e99e81..9f96703c780 100644
--- a/app/models/username_validator.rb
+++ b/app/models/username_validator.rb
@@ -82,14 +82,14 @@ class UsernameValidator
def username_present?
return unless errors.empty?
- self.errors << I18n.t(:"user.username.blank") if username.blank?
+ errors << I18n.t(:"user.username.blank") if username.blank?
end
def username_length_min?
return unless errors.empty?
if username_grapheme_clusters.size < User.username_length.begin
- self.errors << I18n.t(:"user.username.short", count: User.username_length.begin)
+ errors << I18n.t(:"user.username.short", count: User.username_length.begin)
end
end
@@ -97,9 +97,9 @@ class UsernameValidator
return unless errors.empty?
if username_grapheme_clusters.size > User.username_length.end
- self.errors << I18n.t(:"user.username.long", count: User.username_length.end)
+ errors << I18n.t(:"user.username.long", count: User.username_length.end)
elsif username.length > MAX_CHARS
- self.errors << I18n.t(:"user.username.too_long")
+ errors << I18n.t(:"user.username.too_long")
end
end
@@ -107,7 +107,7 @@ class UsernameValidator
return unless errors.empty?
if self.class.invalid_char_pattern.match?(username)
- self.errors << I18n.t(:"user.username.characters")
+ errors << I18n.t(:"user.username.characters")
end
end
@@ -115,7 +115,7 @@ class UsernameValidator
return unless errors.empty? && self.class.char_allowlist_exists?
if username.chars.any? { |c| !self.class.allowed_char?(c) }
- self.errors << I18n.t(:"user.username.characters")
+ errors << I18n.t(:"user.username.characters")
end
end
@@ -123,7 +123,7 @@ class UsernameValidator
return unless errors.empty?
if INVALID_LEADING_CHAR_PATTERN.match?(username_grapheme_clusters.first)
- self.errors << I18n.t(:"user.username.must_begin_with_alphanumeric_or_underscore")
+ errors << I18n.t(:"user.username.must_begin_with_alphanumeric_or_underscore")
end
end
@@ -131,7 +131,7 @@ class UsernameValidator
return unless errors.empty?
if INVALID_TRAILING_CHAR_PATTERN.match?(username_grapheme_clusters.last)
- self.errors << I18n.t(:"user.username.must_end_with_alphanumeric")
+ errors << I18n.t(:"user.username.must_end_with_alphanumeric")
end
end
@@ -139,7 +139,7 @@ class UsernameValidator
return unless errors.empty?
if REPEATED_SPECIAL_CHAR_PATTERN.match?(username)
- self.errors << I18n.t(:"user.username.must_not_contain_two_special_chars_in_seq")
+ errors << I18n.t(:"user.username.must_not_contain_two_special_chars_in_seq")
end
end
@@ -147,14 +147,14 @@ class UsernameValidator
return unless errors.empty?
if CONFUSING_EXTENSIONS.match?(username)
- self.errors << I18n.t(:"user.username.must_not_end_with_confusing_suffix")
+ errors << I18n.t(:"user.username.must_not_end_with_confusing_suffix")
end
end
def username_plugin_validation
return unless errors.empty?
- DiscoursePluginRegistry.apply_modifier(:username_validation, self.errors, self)
+ DiscoursePluginRegistry.apply_modifier(:username_validation, errors, self)
end
def username_grapheme_clusters
diff --git a/app/models/watched_word.rb b/app/models/watched_word.rb
index b403b85c79f..10329fd98ae 100644
--- a/app/models/watched_word.rb
+++ b/app/models/watched_word.rb
@@ -4,14 +4,14 @@ class WatchedWord < ActiveRecord::Base
MAX_WORDS_PER_ACTION = 2000
before_validation do
- self.word = WatchedWord.normalize_word(self.word)
- self.replacement = WatchedWord.normalize_word(self.replacement) if self.replacement.present?
+ self.word = WatchedWord.normalize_word(word)
+ self.replacement = WatchedWord.normalize_word(replacement) if replacement.present?
end
before_validation do
- if self.action == WatchedWord.actions[:link] && self.replacement !~ %r{\Ahttps?://}
+ if action == WatchedWord.actions[:link] && replacement !~ %r{\Ahttps?://}
self.replacement =
- "#{Discourse.base_url}#{self.replacement&.starts_with?("/") ? "" : "/"}#{self.replacement}"
+ "#{Discourse.base_url}#{replacement&.starts_with?("/") ? "" : "/"}#{replacement}"
end
end
diff --git a/app/models/watched_word_group.rb b/app/models/watched_word_group.rb
index d65ff39efb3..e91c40a0e09 100644
--- a/app/models/watched_word_group.rb
+++ b/app/models/watched_word_group.rb
@@ -17,15 +17,15 @@ class WatchedWordGroup < ActiveRecord::Base
words.each do |word|
watched_word = WatchedWord.create_or_update_word(params.merge(word: word))
- self.watched_words << watched_word
+ watched_words << watched_word
end
- self.save!
+ save!
end
end
def action_log_details
- "#{WatchedWord.actions.key(self.action)} → #{watched_words.pluck(:word).join(", ")}"
+ "#{WatchedWord.actions.key(action)} → #{watched_words.pluck(:word).join(", ")}"
end
end
diff --git a/app/models/web_hook.rb b/app/models/web_hook.rb
index 3e7491e177d..e1ea6b8e3f6 100644
--- a/app/models/web_hook.rb
+++ b/app/models/web_hook.rb
@@ -137,7 +137,7 @@ class WebHook < ActiveRecord::Base
serializer ||= TagSerializer if type == :tag
serializer ||= "WebHook#{type.capitalize}Serializer".constantize
- serializer.new(object, scope: self.guardian, root: false).to_json
+ serializer.new(object, scope: guardian, root: false).to_json
end
private
@@ -159,7 +159,7 @@ class WebHook < ActiveRecord::Base
false
end
- self.errors.add(:base, I18n.t("webhooks.payload_url.blocked_or_internal")) if !allowed
+ errors.add(:base, I18n.t("webhooks.payload_url.blocked_or_internal")) if !allowed
end
end
diff --git a/app/models/web_hook_event_type.rb b/app/models/web_hook_event_type.rb
index 336040820af..4c52ce1da7d 100644
--- a/app/models/web_hook_event_type.rb
+++ b/app/models/web_hook_event_type.rb
@@ -134,7 +134,7 @@ class WebHookEventType < ActiveRecord::Base
],
)
end
- self.where.not(id: ids_to_exclude)
+ where.not(id: ids_to_exclude)
end
end
diff --git a/app/models/web_hook_events_daily_aggregate.rb b/app/models/web_hook_events_daily_aggregate.rb
index 5f3d406767d..86bf4e149c1 100644
--- a/app/models/web_hook_events_daily_aggregate.rb
+++ b/app/models/web_hook_events_daily_aggregate.rb
@@ -20,9 +20,9 @@ class WebHookEventsDailyAggregate < ActiveRecord::Base
events =
WebHookEvent.where(
"created_at >= ? AND created_at < ? AND web_hook_id = ?",
- self.date,
- self.date + 1.day,
- self.web_hook_id,
+ date,
+ date + 1.day,
+ web_hook_id,
)
if events.empty?
diff --git a/app/serializers/post_revision_serializer.rb b/app/serializers/post_revision_serializer.rb
index 9247908cc62..c42e3a69342 100644
--- a/app/serializers/post_revision_serializer.rb
+++ b/app/serializers/post_revision_serializer.rb
@@ -36,7 +36,7 @@ class PostRevisionSerializer < ApplicationSerializer
def self.add_compared_field(field)
changes_name = :"#{field}_changes"
- self.attributes changes_name
+ attributes changes_name
define_method(changes_name) { { previous: previous[field], current: current[field] } }
define_method("include_#{changes_name}?") { previous[field] != current[field] }
diff --git a/app/serializers/post_serializer.rb b/app/serializers/post_serializer.rb
index 76b4d731e3b..7a41f2e6d89 100644
--- a/app/serializers/post_serializer.rb
+++ b/app/serializers/post_serializer.rb
@@ -15,7 +15,7 @@ class PostSerializer < BasicPostSerializer
ignored_user_like_counts
]
- INSTANCE_VARS.each { |v| self.public_send(:attr_accessor, v) }
+ INSTANCE_VARS.each { |v| public_send(:attr_accessor, v) }
attributes :post_number,
:post_type,
@@ -107,7 +107,7 @@ class PostSerializer < BasicPostSerializer
super(object, opts)
PostSerializer::INSTANCE_VARS.each do |name|
- self.public_send("#{name}=", opts[name]) if opts.include? name
+ public_send("#{name}=", opts[name]) if opts.include? name
end
end
diff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rb
index 632358bcc80..bc66ac586ba 100644
--- a/app/serializers/site_serializer.rb
+++ b/app/serializers/site_serializer.rb
@@ -164,7 +164,7 @@ class SiteSerializer < ApplicationSerializer
flags,
each_serializer: FlagSerializer,
target: :post_action,
- used_flag_ids: self.used_flag_ids(flags.map(&:id)),
+ used_flag_ids: used_flag_ids(flags.map(&:id)),
).as_json
end
end
@@ -190,7 +190,7 @@ class SiteSerializer < ApplicationSerializer
flags,
each_serializer: FlagSerializer,
target: :topic_flag,
- used_flag_ids: self.used_flag_ids(flags.map(&:id)),
+ used_flag_ids: used_flag_ids(flags.map(&:id)),
).as_json
end
end
diff --git a/app/services/categories/type_registry.rb b/app/services/categories/type_registry.rb
index 7bf5637aac0..5d214676463 100644
--- a/app/services/categories/type_registry.rb
+++ b/app/services/categories/type_registry.rb
@@ -45,7 +45,7 @@ module Categories
# Always need to re-register the core Discussion type, the system doesn't work
# without it.
- self.register(Categories::Types::Discussion)
+ register(Categories::Types::Discussion)
end
# Returns all the category type counts in a hash with the type
diff --git a/app/services/color_scheme_revisor.rb b/app/services/color_scheme_revisor.rb
index 91696ae74af..7e85998864b 100644
--- a/app/services/color_scheme_revisor.rb
+++ b/app/services/color_scheme_revisor.rb
@@ -7,7 +7,7 @@ class ColorSchemeRevisor
end
def self.revise(color_scheme, params)
- self.new(color_scheme, params).revise
+ new(color_scheme, params).revise
end
def revise
diff --git a/app/services/email_settings_validator.rb b/app/services/email_settings_validator.rb
index 92df9e37b30..39b008a0417 100644
--- a/app/services/email_settings_validator.rb
+++ b/app/services/email_settings_validator.rb
@@ -6,7 +6,7 @@ require "net/pop"
class EmailSettingsValidator
def self.validate_as_user(user, protocol, **kwargs)
DistributedMutex.synchronize("validate_#{protocol}_#{user.id}", validity: 10) do
- self.public_send("validate_#{protocol}", **kwargs)
+ public_send("validate_#{protocol}", **kwargs)
end
end
diff --git a/app/services/hashtag_autocomplete_service.rb b/app/services/hashtag_autocomplete_service.rb
index 09867194490..6d39d646da2 100644
--- a/app/services/hashtag_autocomplete_service.rb
+++ b/app/services/hashtag_autocomplete_service.rb
@@ -33,19 +33,19 @@ class HashtagAutocompleteService
end
def self.enabled_data_sources
- self.data_sources.filter(&:enabled?)
+ data_sources.filter(&:enabled?)
end
def self.data_source_types
- self.enabled_data_sources.map(&:type)
+ enabled_data_sources.map(&:type)
end
def self.data_source_icon_map
- self.enabled_data_sources.map { |ds| [ds.type, ds.icon] }.to_h
+ enabled_data_sources.map { |ds| [ds.type, ds.icon] }.to_h
end
def self.data_source_from_type(type)
- self.enabled_data_sources.find { |ds| ds.type == type }
+ enabled_data_sources.find { |ds| ds.type == type }
end
def self.find_priorities_for_context(context)
@@ -126,20 +126,20 @@ class HashtagAutocompleteService
def to_h
opts = {
- relative_url: self.relative_url,
- text: self.text,
- description: self.description,
- icon: self.icon,
- colors: self.colors,
- type: self.type,
- ref: self.ref,
- slug: self.slug,
- id: self.id,
+ relative_url: relative_url,
+ text: text,
+ description: description,
+ icon: icon,
+ colors: colors,
+ type: type,
+ ref: ref,
+ slug: slug,
+ id: id,
}
- if self.style_type.present?
- opts[:style_type] = self.style_type
- opts[:emoji] = self.emoji
+ if style_type.present?
+ opts[:style_type] = style_type
+ opts[:emoji] = emoji
end
opts
diff --git a/app/services/post_bookmarkable.rb b/app/services/post_bookmarkable.rb
index 82230fa542d..b01e8b3e621 100644
--- a/app/services/post_bookmarkable.rb
+++ b/app/services/post_bookmarkable.rb
@@ -55,7 +55,7 @@ class PostBookmarkable < BaseBookmarkable
def self.reminder_conditions(bookmark)
bookmark.bookmarkable.present? && bookmark.bookmarkable.topic.present? &&
- self.can_see?(bookmark.user.guardian, bookmark)
+ can_see?(bookmark.user.guardian, bookmark)
end
def self.can_see?(guardian, bookmark)
diff --git a/app/services/post_owner_changer.rb b/app/services/post_owner_changer.rb
index 3ebcbf77c6a..442de2bbe70 100644
--- a/app/services/post_owner_changer.rb
+++ b/app/services/post_owner_changer.rb
@@ -9,7 +9,7 @@ class PostOwnerChanger
@skip_revision = params[:skip_revision] || false
%i[post_ids topic new_owner acting_user].each do |arg|
- raise ArgumentError.new(arg) if self.instance_variable_get("@#{arg}").blank?
+ raise ArgumentError.new(arg) if instance_variable_get("@#{arg}").blank?
end
end
diff --git a/app/services/site_setting/update.rb b/app/services/site_setting/update.rb
index 618e51b7f95..900b8845fbd 100644
--- a/app/services/site_setting/update.rb
+++ b/app/services/site_setting/update.rb
@@ -19,8 +19,7 @@ class SiteSetting::Update
dependent_order = SiteSetting.type_supervisor.dependencies.order
self.settings =
- self
- .settings
+ settings
.to_a
.map do |setting|
Setting.new(
@@ -37,7 +36,7 @@ class SiteSetting::Update
after_validation do
self.settings =
- self.settings.map do |setting|
+ settings.map do |setting|
raw_value = setting.value
setting.value =
diff --git a/app/services/site_setting/upsert_groups.rb b/app/services/site_setting/upsert_groups.rb
index c586fba5b6a..cb9bb1cf8e0 100644
--- a/app/services/site_setting/upsert_groups.rb
+++ b/app/services/site_setting/upsert_groups.rb
@@ -4,7 +4,7 @@ class SiteSetting::UpsertGroups
include Service::Base
params do
- before_validation { self.group_names = Array.wrap(self.group_names).delete_if(&:empty?) }
+ before_validation { self.group_names = Array.wrap(group_names).delete_if(&:empty?) }
attribute :group_names, :array
attribute :setting, :string
diff --git a/app/services/site_setting_update_existing_users.rb b/app/services/site_setting_update_existing_users.rb
index 5e61d2d88bc..a98c19271af 100644
--- a/app/services/site_setting_update_existing_users.rb
+++ b/app/services/site_setting_update_existing_users.rb
@@ -4,7 +4,7 @@ class SiteSettingUpdateExistingUsers
def self.call(id, value, previous_value)
new_value = value.nil? ? "" : value
- if (user_option = self.user_options[id.to_sym]).present?
+ if (user_option = user_options[id.to_sym]).present?
if user_option == "text_size_key"
previous_value = UserOption.text_sizes[previous_value.to_sym]
new_value = UserOption.text_sizes[new_value.to_sym]
@@ -37,7 +37,7 @@ class SiteSettingUpdateExistingUsers
status: "enqueued",
group_ids: [Group::AUTO_GROUPS[:admins]],
)
- elsif self.is_sidebar_default_setting?(id)
+ elsif is_sidebar_default_setting?(id)
Jobs.enqueue(
:backfill_sidebar_site_settings,
setting_name: id,
diff --git a/app/services/themes/theme_site_setting_manager.rb b/app/services/themes/theme_site_setting_manager.rb
index 2588c8ffc5e..82385849f91 100644
--- a/app/services/themes/theme_site_setting_manager.rb
+++ b/app/services/themes/theme_site_setting_manager.rb
@@ -20,7 +20,7 @@ class Themes::ThemeSiteSettingManager
validates :theme_id, presence: true
validates :name, presence: true
- after_validation { self.name = self.name.to_sym if self.name.present? }
+ after_validation { self.name = name.to_sym if name.present? }
end
policy :current_user_is_admin
diff --git a/app/services/topic_bookmarkable.rb b/app/services/topic_bookmarkable.rb
index 5f7b7aee44e..8ac89a77cf7 100644
--- a/app/services/topic_bookmarkable.rb
+++ b/app/services/topic_bookmarkable.rb
@@ -58,7 +58,7 @@ class TopicBookmarkable < BaseBookmarkable
end
def self.reminder_conditions(bookmark)
- bookmark.bookmarkable.present? && self.can_see?(bookmark.user.guardian, bookmark)
+ bookmark.bookmarkable.present? && can_see?(bookmark.user.guardian, bookmark)
end
def self.can_see?(guardian, bookmark)
diff --git a/app/services/user_action_manager.rb b/app/services/user_action_manager.rb
index 23d357a8ff2..6d7cf03c72f 100644
--- a/app/services/user_action_manager.rb
+++ b/app/services/user_action_manager.rb
@@ -9,7 +9,7 @@ class UserActionManager
@disabled = false
end
- %i[notification post topic post_action].each { |type| self.class_eval(<<~RUBY) }
+ %i[notification post topic post_action].each { |type| class_eval(<<~RUBY) }
def self.#{type}_created(*args)
return if @disabled
#{type}_rows(*args).each { |row| UserAction.log_action!(row) }
diff --git a/app/services/user_anonymizer.rb b/app/services/user_anonymizer.rb
index 9e78e521ef9..248109dedd5 100644
--- a/app/services/user_anonymizer.rb
+++ b/app/services/user_anonymizer.rb
@@ -15,7 +15,7 @@ class UserAnonymizer
end
def self.make_anonymous(user, actor = nil, opts = nil)
- self.new(user, actor, opts).make_anonymous
+ new(user, actor, opts).make_anonymous
end
def make_anonymous
diff --git a/app/services/username_changer.rb b/app/services/username_changer.rb
index 10f7d66c22c..0c6c119cda1 100644
--- a/app/services/username_changer.rb
+++ b/app/services/username_changer.rb
@@ -9,7 +9,7 @@ class UsernameChanger
end
def self.change(user, new_username, actor = nil)
- self.new(user, new_username, actor).change
+ new(user, new_username, actor).change
end
def self.override(user, new_username)
diff --git a/config/initializers/000-trace_pg_connections.rb b/config/initializers/000-trace_pg_connections.rb
index 0b91e336b1e..6bba173676a 100644
--- a/config/initializers/000-trace_pg_connections.rb
+++ b/config/initializers/000-trace_pg_connections.rb
@@ -23,7 +23,7 @@ if ENV["TRACE_PG_CONNECTIONS"]
super(*args).tap do
next if ENV["TRACE_PG_CONNECTIONS"] == "SIDEKIQ" && !Sidekiq.server?
FileUtils.mkdir_p(TRACE_DIR)
- @trace_filename = "#{TRACE_DIR}/#{Process.pid}_#{self.object_id}.txt"
+ @trace_filename = "#{TRACE_DIR}/#{Process.pid}_#{object_id}.txt"
trace File.new(@trace_filename, "w")
end
@access_log_mutex = Mutex.new
diff --git a/lib/autospec/manager.rb b/lib/autospec/manager.rb
index 5ee9f97f422..e5e3c563d8b 100644
--- a/lib/autospec/manager.rb
+++ b/lib/autospec/manager.rb
@@ -11,7 +11,7 @@ end
class Autospec::Manager
def self.run(opts = {})
- self.new(opts).run
+ new(opts).run
end
def initialize(opts = {})
diff --git a/lib/discourse.rb b/lib/discourse.rb
index a87ffea1c55..5c021429be8 100644
--- a/lib/discourse.rb
+++ b/lib/discourse.rb
@@ -430,7 +430,7 @@ module Discourse
end
def self.find_plugin_css_assets(args)
- plugins = apply_asset_filters(self.find_plugins(args), :css, args[:request])
+ plugins = apply_asset_filters(find_plugins(args), :css, args[:request])
assets = []
@@ -453,11 +453,9 @@ module Discourse
def self.find_plugin_js_assets(args)
plugins =
- self
- .find_plugins(args)
- .select do |plugin|
- plugin.js_asset_exists? || plugin.extra_js_asset_exists? || plugin.admin_js_asset_exists?
- end
+ find_plugins(args).select do |plugin|
+ plugin.js_asset_exists? || plugin.extra_js_asset_exists? || plugin.admin_js_asset_exists?
+ end
plugins = apply_asset_filters(plugins, :js, args[:request])
diff --git a/lib/discourse_connect_base.rb b/lib/discourse_connect_base.rb
index 1e91ecd6523..8e0cc20ba77 100644
--- a/lib/discourse_connect_base.rb
+++ b/lib/discourse_connect_base.rb
@@ -150,7 +150,7 @@ class DiscourseConnectBase
end
def to_json
- self.to_h.to_json
+ to_h.to_json
end
def to_url(base_url = nil)
@@ -164,7 +164,7 @@ class DiscourseConnectBase
end
def unsigned_payload
- Rack::Utils.build_query(self.to_h)
+ Rack::Utils.build_query(to_h)
end
def to_h
diff --git a/lib/discourse_dev/record.rb b/lib/discourse_dev/record.rb
index 7da22cf060b..0624c39559f 100644
--- a/lib/discourse_dev/record.rb
+++ b/lib/discourse_dev/record.rb
@@ -69,7 +69,7 @@ module DiscourseDev
end
def self.populate!(**args)
- self.new(**args).populate!
+ new(**args).populate!
end
def self.random(model, use_existing_records: true)
diff --git a/lib/discourse_logstash_logger.rb b/lib/discourse_logstash_logger.rb
index 3e0b9cbe300..8a0ffb2b1dd 100644
--- a/lib/discourse_logstash_logger.rb
+++ b/lib/discourse_logstash_logger.rb
@@ -23,7 +23,7 @@ class DiscourseLogstashLogger < Logger
#
# @return [Logger] A new logger instance with the specified log device and type.
def self.logger(logdev:, type:, customize_event: nil, level: Logger::INFO)
- logger = self.new(logdev)
+ logger = new(logdev)
logger.type = type
logger.customize_event = customize_event if customize_event
logger.level = level
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index 9a78fc31990..967048ad612 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -145,11 +145,11 @@ class DiscoursePluginRegistry
end
def self.register_auth_provider(auth_provider)
- self.auth_providers << auth_provider
+ auth_providers << auth_provider
end
def self.register_mail_poller(mail_poller)
- self.mail_pollers << mail_poller
+ mail_pollers << mail_poller
end
def register_js(filename, options = {})
@@ -158,11 +158,11 @@ class DiscoursePluginRegistry
end
def self.register_service_worker(filename, options = {})
- self.service_workers << filename
+ service_workers << filename
end
def self.register_svg_icon(icon)
- self.svg_icons << icon.strip
+ svg_icons << icon.strip
end
def register_css(filename, plugin_directory_name)
@@ -171,13 +171,13 @@ class DiscoursePluginRegistry
end
def self.register_locale(locale, options = {})
- self.locales[locale] = options
+ locales[locale] = options
end
def self.unregister_locale(locale)
raise "unregister_locale can only be used in tests" if !Rails.env.test?
- self.locales.delete(locale)
+ locales.delete(locale)
end
def register_archetype(name, options = {})
@@ -189,24 +189,24 @@ class DiscoursePluginRegistry
def self.register_asset(asset, opts = nil, plugin_directory_name = nil)
if asset =~ JS_REGEX
if opts == :vendored_pretty_text
- self.vendored_pretty_text << asset
+ vendored_pretty_text << asset
elsif opts == :vendored_core_pretty_text
- self.vendored_core_pretty_text << asset
+ vendored_core_pretty_text << asset
else
- self.javascripts << asset
+ javascripts << asset
end
elsif asset =~ /\.css$|\.scss\z/
if opts == :mobile
- self.mobile_stylesheets[plugin_directory_name] ||= Set.new
- self.mobile_stylesheets[plugin_directory_name] << asset
+ mobile_stylesheets[plugin_directory_name] ||= Set.new
+ mobile_stylesheets[plugin_directory_name] << asset
elsif opts == :desktop
- self.desktop_stylesheets[plugin_directory_name] ||= Set.new
- self.desktop_stylesheets[plugin_directory_name] << asset
+ desktop_stylesheets[plugin_directory_name] ||= Set.new
+ desktop_stylesheets[plugin_directory_name] << asset
elsif opts == :color_definitions
- self.color_definition_stylesheets[plugin_directory_name] = asset
+ color_definition_stylesheets[plugin_directory_name] = asset
else
- self.stylesheets[plugin_directory_name] ||= Set.new
- self.stylesheets[plugin_directory_name] << asset
+ stylesheets[plugin_directory_name] ||= Set.new
+ stylesheets[plugin_directory_name] << asset
end
end
end
@@ -214,16 +214,16 @@ class DiscoursePluginRegistry
def self.stylesheets_exists?(plugin_directory_name, target = nil)
case target
when :desktop
- self.desktop_stylesheets[plugin_directory_name].present?
+ desktop_stylesheets[plugin_directory_name].present?
when :mobile
- self.mobile_stylesheets[plugin_directory_name].present?
+ mobile_stylesheets[plugin_directory_name].present?
else
- self.stylesheets[plugin_directory_name].present?
+ stylesheets[plugin_directory_name].present?
end
end
def self.register_seed_data(key, value)
- self.seed_data[key] = value
+ seed_data[key] = value
end
def self.register_seed_path_builder(&block)
@@ -247,7 +247,7 @@ class DiscoursePluginRegistry
end
def self.register_seedfu_filter(filter = nil)
- self.seedfu_filter << filter
+ seedfu_filter << filter
end
VENDORED_CORE_PRETTY_TEXT_MAP = {
diff --git a/lib/distributed_cache.rb b/lib/distributed_cache.rb
index 39a1fc79531..0f21cf69382 100644
--- a/lib/distributed_cache.rb
+++ b/lib/distributed_cache.rb
@@ -18,7 +18,7 @@ class DistributedCache < MessageBus::DistributedCache
return self[k] if hash.key? k
value = block.call
- self.defer_set(k, value)
+ defer_set(k, value)
value
end
diff --git a/lib/distributed_mutex.rb b/lib/distributed_mutex.rb
index 133b33b1e35..206b5e8e7b7 100644
--- a/lib/distributed_mutex.rb
+++ b/lib/distributed_mutex.rb
@@ -31,7 +31,7 @@ class DistributedMutex
LUA
def self.synchronize(key, redis: nil, validity: DEFAULT_VALIDITY, &blk)
- self.new(key, redis: redis, validity: validity).synchronize(&blk)
+ new(key, redis: redis, validity: validity).synchronize(&blk)
end
def initialize(key, redis: nil, validity: DEFAULT_VALIDITY)
diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb
index 9b1aa1cbc7a..8479afac287 100644
--- a/lib/email/receiver.rb
+++ b/lib/email/receiver.rb
@@ -455,7 +455,7 @@ module Email
# use the first html extracter that matches
if html_extracter = HTML_EXTRACTERS.select { |_, r| html[r] }.min_by { |_, r| html =~ r }
doc = Nokogiri::HTML5.fragment(html)
- self.public_send(:"extract_from_#{html_extracter[0]}", doc)
+ public_send(:"extract_from_#{html_extracter[0]}", doc)
else
markdown =
HtmlToMarkdown.new(html, keep_img_tags: true, keep_cid_imgs: true).to_markdown
diff --git a/lib/email_backup_token.rb b/lib/email_backup_token.rb
index 0aef08ca542..76dc44fed0b 100644
--- a/lib/email_backup_token.rb
+++ b/lib/email_backup_token.rb
@@ -10,20 +10,20 @@ class EmailBackupToken
end
def self.set(user_id)
- token = self.generate
- Discourse.redis.setex self.key(user_id), 1.day.to_i, token
+ token = generate
+ Discourse.redis.setex key(user_id), 1.day.to_i, token
token
end
def self.get(user_id)
- Discourse.redis.get self.key(user_id)
+ Discourse.redis.get key(user_id)
end
def self.del(user_id)
- Discourse.redis.del self.key(user_id)
+ Discourse.redis.del key(user_id)
end
def self.compare(user_id, token)
- token == self.get(user_id)
+ token == get(user_id)
end
end
diff --git a/lib/excerpt_parser.rb b/lib/excerpt_parser.rb
index 347a0b15d0f..79670b2c8a8 100644
--- a/lib/excerpt_parser.rb
+++ b/lib/excerpt_parser.rb
@@ -34,7 +34,7 @@ class ExcerptParser < Nokogiri::XML::SAX::Document
return "" if html.blank?
length = html.length if html.include?("excerpt") && CUSTOM_EXCERPT_REGEX === html
- me = self.new(length, options)
+ me = new(length, options)
parser = Nokogiri::HTML4::SAX::Parser.new(me, Encoding::UTF_8)
catch(:done) { parser.parse(html) }
excerpt = me.excerpt.strip
diff --git a/lib/filter_best_posts.rb b/lib/filter_best_posts.rb
index 09cb3cbe30e..d5e3e561ea4 100644
--- a/lib/filter_best_posts.rb
+++ b/lib/filter_best_posts.rb
@@ -7,7 +7,7 @@ class FilterBestPosts
@filtered_posts = filtered_posts
@topic = topic
@limit = limit
- options.each { |key, value| self.instance_variable_set(:"@#{key}", value) }
+ options.each { |key, value| instance_variable_set(:"@#{key}", value) }
filter
end
diff --git a/lib/git_utils.rb b/lib/git_utils.rb
index 87dd3cbd0b9..ff00cec886a 100644
--- a/lib/git_utils.rb
+++ b/lib/git_utils.rb
@@ -2,28 +2,28 @@
class GitUtils
def self.git_version
- filesystem_overrides["git_version"] || self.try_git("git rev-parse HEAD", "unknown")
+ filesystem_overrides["git_version"] || try_git("git rev-parse HEAD", "unknown")
end
def self.git_branch
- filesystem_overrides["git_branch"] || self.try_git("git branch --show-current", nil) ||
- self.try_git("git config user.discourse-version", "unknown")
+ filesystem_overrides["git_branch"] || try_git("git branch --show-current", nil) ||
+ try_git("git config user.discourse-version", "unknown")
end
def self.full_version
filesystem_overrides["full_version"] ||
- self.try_git('git describe --dirty --match "v[0-9]*" 2> /dev/null', "unknown")
+ try_git('git describe --dirty --match "v[0-9]*" 2> /dev/null', "unknown")
end
def self.has_commit?(hash)
return false if !hash.match?(/\A[a-f0-9]{40}\Z/)
- self.try_git("git merge-base --is-ancestor #{hash} HEAD 2> /dev/null; echo $?", "1") == "0"
+ try_git("git merge-base --is-ancestor #{hash} HEAD 2> /dev/null; echo $?", "1") == "0"
end
def self.last_commit_date
git_cmd = 'git log -1 --format="%ct"'
- seconds = self.try_git(git_cmd, nil)
+ seconds = try_git(git_cmd, nil)
seconds.nil? ? nil : DateTime.strptime(seconds, "%s")
end
diff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rb
index ec8d6301b3f..aec46de33ca 100644
--- a/lib/guardian/user_guardian.rb
+++ b/lib/guardian/user_guardian.rb
@@ -7,7 +7,7 @@ module UserGuardian
end
def can_pick_avatar?(user_avatar, upload)
- return false unless self.user
+ return false unless user
return true if is_admin?
# can always pick blank avatar
return true if !upload
diff --git a/lib/migration/column_dropper.rb b/lib/migration/column_dropper.rb
index 649af059a6d..6941c10b94f 100644
--- a/lib/migration/column_dropper.rb
+++ b/lib/migration/column_dropper.rb
@@ -32,7 +32,7 @@ module Migration
columns.each do |column|
column = column.to_s
- self.drop_readonly(table, column)
+ drop_readonly(table, column)
# safe cause it is protected on method entry, can not be passed in params
DB.exec("ALTER TABLE #{table} DROP COLUMN IF EXISTS #{column}")
end
diff --git a/lib/mini_scheduler_long_running_job_logger.rb b/lib/mini_scheduler_long_running_job_logger.rb
index 85fe742610e..1a4f6609b3e 100644
--- a/lib/mini_scheduler_long_running_job_logger.rb
+++ b/lib/mini_scheduler_long_running_job_logger.rb
@@ -25,7 +25,7 @@ class MiniSchedulerLongRunningJobLogger
@thread ||=
Thread.new do
loop do
- break if self.stop_requested?
+ break if stop_requested?
current_long_running_jobs = Set.new
diff --git a/lib/onebox/mixins/git_blob_onebox.rb b/lib/onebox/mixins/git_blob_onebox.rb
index e010e3ff5df..5f51a062ca5 100644
--- a/lib/onebox/mixins/git_blob_onebox.rb
+++ b/lib/onebox/mixins/git_blob_onebox.rb
@@ -155,7 +155,7 @@ module Onebox
end
def match
- @match ||= @url.match(self.raw_regexp)
+ @match ||= @url.match(raw_regexp)
end
def sha1
@@ -188,12 +188,12 @@ module Onebox
if @lang == "stl" && link.match?(%r{\Ahttps?://(www\.)?github\.com.*/blob/})
@model_file = @lang.dup
- @raw = "https://render.githubusercontent.com/view/solid?url=" + self.raw_template(m)
+ @raw = "https://render.githubusercontent.com/view/solid?url=" + raw_template(m)
else
contents =
URI
- .parse(self.raw_template(m))
- .open({ read_timeout: timeout }.merge(self.auth_headers(m)))
+ .parse(raw_template(m))
+ .open({ read_timeout: timeout }.merge(auth_headers(m)))
.read
if contents.encoding == Encoding::BINARY || contents.bytes.include?(0)
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index 77556003188..72fbf55af39 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -107,7 +107,7 @@ class Plugin::Instance
def self.parse_from_source(path)
source = File.read(path)
metadata = Plugin::Metadata.parse(source)
- self.new(metadata, path)
+ new(metadata, path)
end
def initialize(metadata = nil, path = nil)
@@ -138,7 +138,7 @@ class Plugin::Instance
end
def full_admin_route
- route = self.admin_route
+ route = admin_route
if route.blank?
return if !any_settings? || has_only_enabled_setting?
@@ -162,7 +162,7 @@ class Plugin::Instance
end
def plugin_settings
- @plugin_settings ||= SiteSetting.plugins.select { |_, plugin_name| plugin_name == self.name }
+ @plugin_settings ||= SiteSetting.plugins.select { |_, plugin_name| plugin_name == name }
end
def deprecate_setting(old_setting, new_setting, override, drom_from)
@@ -414,7 +414,7 @@ class Plugin::Instance
end
def register_category_type(klass)
- Categories::TypeRegistry.register(klass, plugin_identifier: self.metadata.name)
+ Categories::TypeRegistry.register(klass, plugin_identifier: metadata.name)
end
def register_problem_check(klass)
@@ -647,7 +647,7 @@ class Plugin::Instance
def discourse_owned?
return false if commit_hash.blank?
- parsed_commit_url = UrlHelper.relaxed_parse(self.commit_url)
+ parsed_commit_url = UrlHelper.relaxed_parse(commit_url)
return false if parsed_commit_url.blank? || parsed_commit_url.path.blank?
github_org = parsed_commit_url.path.split("/")[1]
(github_org == "discourse" || github_org == "discourse-org") &&
@@ -731,8 +731,8 @@ class Plugin::Instance
end
def listen_for(event_name)
- return unless self.respond_to?(event_name)
- DiscourseEvent.on(event_name, &self.method(event_name))
+ return unless respond_to?(event_name)
+ DiscourseEvent.on(event_name, &method(event_name))
end
def register_css(style)
@@ -845,7 +845,7 @@ class Plugin::Instance
# this allows us to present information about a plugin in the UI
# prior to activations
def activate!
- self.instance_eval File.read(path), path
+ instance_eval File.read(path), path
if auto_assets = generate_automatic_assets!
assets.concat(auto_assets)
end
diff --git a/lib/plugin/metadata.rb b/lib/plugin/metadata.rb
index 68ffb01cf62..6381c88b311 100644
--- a/lib/plugin/metadata.rb
+++ b/lib/plugin/metadata.rb
@@ -30,7 +30,7 @@ class Plugin::Metadata
end
def self.parse(text)
- metadata = self.new
+ metadata = new
text.each_line { |line| break unless metadata.parse_line(line) }
metadata
end
@@ -50,10 +50,7 @@ class Plugin::Metadata
attribute = attribute.strip.gsub(/ /, "_").to_sym
if FIELDS.include?(attribute)
- self.public_send(
- "#{attribute}=",
- value.strip.truncate(MAX_FIELD_LENGTHS[attribute] || 1000),
- )
+ public_send("#{attribute}=", value.strip.truncate(MAX_FIELD_LENGTHS[attribute] || 1000))
end
end
diff --git a/lib/post_creator.rb b/lib/post_creator.rb
index aa6c0ed879d..302e2742040 100644
--- a/lib/post_creator.rb
+++ b/lib/post_creator.rb
@@ -244,8 +244,8 @@ class PostCreator
def create!
create
- if !self.errors.full_messages.empty?
- raise ActiveRecord::RecordNotSaved.new(self.errors.full_messages.to_sentence)
+ if !errors.full_messages.empty?
+ raise ActiveRecord::RecordNotSaved.new(errors.full_messages.to_sentence)
end
@post
diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index d3d980d0b96..1b8823001e5 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -68,7 +68,7 @@ class PostRevisor
removed_tags = prev_tags - persisted_tag_names
diff_tags = added_tags | removed_tags
- if diff_tags.present? && !self.silent
+ if diff_tags.present? && !silent
Jobs.enqueue(:notify_tag_change, post_id: post.id, notified_user_ids:, diff_tags:)
PostRevisor.create_small_action_for_tag_changes(
@@ -816,7 +816,7 @@ class PostRevisor
def post_process_post
@post.invalidate_oneboxes = true
@post.trigger_post_process
- DiscourseEvent.trigger(:post_edited, @post, self.topic_changed?, self)
+ DiscourseEvent.trigger(:post_edited, @post, topic_changed?, self)
end
def alert_users
diff --git a/lib/rate_limiter/on_create_record.rb b/lib/rate_limiter/on_create_record.rb
index f24a85a4b55..2df3566949b 100644
--- a/lib/rate_limiter/on_create_record.rb
+++ b/lib/rate_limiter/on_create_record.rb
@@ -35,7 +35,7 @@ class RateLimiter
def rate_limit(limiter_method = nil)
limiter_method = limiter_method || :default_rate_limiter
- self.after_create do |*args|
+ after_create do |*args|
next if @rate_limits_disabled
if rate_limiter = public_send(limiter_method)
@@ -45,14 +45,14 @@ class RateLimiter
end
end
- self.after_destroy do
+ after_destroy do
next if @rate_limits_disabled
if rate_limiter = public_send(limiter_method)
rate_limiter.rollback!
end
end
- self.after_rollback do
+ after_rollback do
next if @rate_limits_disabled
if rate_limiter = public_send(limiter_method)
if @performed.present? && @performed[limiter_method]
diff --git a/lib/s3_helper.rb b/lib/s3_helper.rb
index 457e016f999..28b6effa66c 100644
--- a/lib/s3_helper.rb
+++ b/lib/s3_helper.rb
@@ -104,7 +104,7 @@ class S3Helper
# copy the file in tombstone
if copy_to_tombstone && @tombstone_prefix.present?
- self.copy(get_path_for_s3_upload(s3_filename), File.join(@tombstone_prefix, s3_filename))
+ copy(get_path_for_s3_upload(s3_filename), File.join(@tombstone_prefix, s3_filename))
end
# delete the file
diff --git a/lib/schema_settings_object_validator.rb b/lib/schema_settings_object_validator.rb
index bdf16573ced..fad4e605f2e 100644
--- a/lib/schema_settings_object_validator.rb
+++ b/lib/schema_settings_object_validator.rb
@@ -7,7 +7,7 @@ class SchemaSettingsObjectValidator
objects.each_with_index do |object, index|
humanize_error_messages(
- self.new(schema: schema, object: object).validate,
+ new(schema: schema, object: object).validate,
index:,
error_messages:,
)
@@ -20,7 +20,7 @@ class SchemaSettingsObjectValidator
values = Set.new
objects.each do |object|
- values.merge(self.new(schema: schema, object: object).property_values_of_type(type))
+ values.merge(new(schema: schema, object: object).property_values_of_type(type))
end
values.to_a
diff --git a/lib/search.rb b/lib/search.rb
index e1fc09406e3..74183df1506 100644
--- a/lib/search.rb
+++ b/lib/search.rb
@@ -323,7 +323,7 @@ class Search
end
def self.execute(term, opts = nil)
- self.new(term, opts).execute
+ new(term, opts).execute
end
# Query a term
@@ -1477,7 +1477,7 @@ class Search
end
def self.set_tsquery_weight_filter(term, weight_filter, prefix_match: true)
- "'#{self.escape_string(term)}':#{prefix_match ? "*" : ""}#{weight_filter}"
+ "'#{escape_string(term)}':#{prefix_match ? "*" : ""}#{weight_filter}"
end
def self.escape_string(term)
diff --git a/lib/search/grouped_search_results.rb b/lib/search/grouped_search_results.rb
index bb52afd96f7..56ea3eea9b1 100644
--- a/lib/search/grouped_search_results.rb
+++ b/lib/search/grouped_search_results.rb
@@ -114,7 +114,7 @@ class Search
elsif @is_header_search && public_send(type).length == Search.per_facet
instance_variable_set(:"@more_#{type}", true)
else
- self.public_send(type) << object
+ public_send(type) << object
end
if can_lazy_load_categories
diff --git a/lib/sidekiq_long_running_job_logger.rb b/lib/sidekiq_long_running_job_logger.rb
index 9d3b1081013..a957c0adb30 100644
--- a/lib/sidekiq_long_running_job_logger.rb
+++ b/lib/sidekiq_long_running_job_logger.rb
@@ -20,7 +20,7 @@ class SidekiqLongRunningJobLogger
Thread.new do
loop do
- break if self.stop_requested?
+ break if stop_requested?
begin
current_long_running_jobs = Set.new
diff --git a/lib/site_icon_manager.rb b/lib/site_icon_manager.rb
index c756fe40930..25a3adb65a6 100644
--- a/lib/site_icon_manager.rb
+++ b/lib/site_icon_manager.rb
@@ -97,7 +97,7 @@ module SiteIconManager
define_singleton_method("#{name}_url") do
get_set_cache("#{name}_url") do
- icon = self.public_send(name)
+ icon = public_send(name)
icon ? full_cdn_url(icon.url) : ""
end
end
diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rb
index 014f33dc951..e9f16146607 100644
--- a/lib/site_setting_extension.rb
+++ b/lib/site_setting_extension.rb
@@ -23,7 +23,7 @@ module SiteSettingExtension
def default_locale=(val)
val = val.to_s
raise Discourse::InvalidParameters.new(:value) unless LocaleSiteSetting.valid_value?(val)
- if val != self.default_locale
+ if val != default_locale
add_override!(:default_locale, val)
refresh!
Discourse.request_refresh!
@@ -362,7 +362,7 @@ module SiteSettingExtension
description: description(:default_locale),
type: SiteSetting.types[SiteSetting.types[:locale_enum]],
preview: nil,
- value: self.default_locale,
+ value: default_locale,
valid_values: LocaleSiteSetting.values,
translate_names: LocaleSiteSetting.translate_names?,
}
@@ -869,8 +869,7 @@ module SiteSettingExtension
name: name,
# default_locale is a special case, it is not themeable and we define
# a custom getter for it, so we can just use the normal getter
- value:
- name.to_s == "default_locale" ? self.public_send(name) : self.public_send(name, scoped_to),
+ value: name.to_s == "default_locale" ? public_send(name) : public_send(name, scoped_to),
scoped_to: scoped_to,
)
end
@@ -910,9 +909,9 @@ module SiteSettingExtension
value = filter_value(name, value)
if options
- self.public_send("#{name}=", value, options)
+ public_send("#{name}=", value, options)
else
- self.public_send("#{name}=", value)
+ public_send("#{name}=", value)
end
Discourse.request_refresh! if requires_refresh?(name)
else
@@ -958,10 +957,10 @@ module SiteSettingExtension
"#{name} requires a theme_id because it is themeable",
)
else
- self.public_send(name, scoped_to)
+ public_send(name, scoped_to)
end
else
- self.public_send(name)
+ public_send(name)
end
else
raise Discourse::InvalidParameters.new(
@@ -1139,11 +1138,11 @@ module SiteSettingExtension
setting_type = type_supervisor.get_type(name)
if setting_type == :category_list
define_singleton_method("#{clean_name}_map") do
- self.public_send(clean_name).to_s.split("|").map(&:to_i)
+ public_send(clean_name).to_s.split("|").map(&:to_i)
end
elsif setting_type == :group_list
define_singleton_method("#{clean_name}_map") do
- ids = self.public_send(clean_name).to_s.split("|").map(&:to_i)
+ ids = public_send(clean_name).to_s.split("|").map(&:to_i)
if SiteSetting.granular_anonymous_and_logged_in_groups_permissions &&
ids.include?(Group::AUTO_GROUPS[:everyone])
ids =
@@ -1174,13 +1173,13 @@ module SiteSettingExtension
if %w[simple compact].include?(list_type) || list_type.nil?
define_singleton_method("#{clean_name}_map") do |scoped_to = nil|
- self.public_send(clean_name, scoped_to).to_s.split("|")
+ public_send(clean_name, scoped_to).to_s.split("|")
end
end
end
define_singleton_method "#{clean_name}?" do |scoped_to = nil|
- self.public_send(clean_name, scoped_to)
+ public_send(clean_name, scoped_to)
end
define_singleton_method "#{clean_name}=" do |val|
diff --git a/lib/site_settings/deprecated_settings.rb b/lib/site_settings/deprecated_settings.rb
index ab0fe7c8487..3b71a606c72 100644
--- a/lib/site_settings/deprecated_settings.rb
+++ b/lib/site_settings/deprecated_settings.rb
@@ -26,7 +26,7 @@ module SiteSettings::DeprecatedSettings
)
end
- self.public_send(override ? new_setting : "_#{old_setting}", scoped_to)
+ public_send(override ? new_setting : "_#{old_setting}", scoped_to)
end
SiteSetting.singleton_class.alias_method(:"_#{old_setting}?", :"#{old_setting}?") if !override
@@ -39,7 +39,7 @@ module SiteSettings::DeprecatedSettings
)
end
- self.public_send("#{override ? new_setting : "_" + old_setting}?", scoped_to)
+ public_send("#{override ? new_setting : "_" + old_setting}?", scoped_to)
end
SiteSetting.singleton_class.alias_method(:"_#{old_setting}=", :"#{old_setting}=") if !override
@@ -52,7 +52,7 @@ module SiteSettings::DeprecatedSettings
)
end
- self.public_send("#{override ? new_setting : "_" + old_setting}=", val)
+ public_send("#{override ? new_setting : "_" + old_setting}=", val)
end
end
end
diff --git a/lib/site_settings/type_supervisor.rb b/lib/site_settings/type_supervisor.rb
index ab36d9b2f81..c1439d9e834 100644
--- a/lib/site_settings/type_supervisor.rb
+++ b/lib/site_settings/type_supervisor.rb
@@ -80,15 +80,15 @@ class SiteSettings::TypeSupervisor
def self.parse_value_type(val)
case val
when NilClass
- self.types[:null]
+ types[:null]
when String
- self.types[:string]
+ types[:string]
when Integer
- self.types[:integer]
+ types[:integer]
when Float
- self.types[:float]
+ types[:float]
when TrueClass, FalseClass
- self.types[:bool]
+ types[:bool]
else
raise ArgumentError.new("Invalid value type for site setting: #{val.class}")
end
@@ -310,7 +310,7 @@ class SiteSettings::TypeSupervisor
end
validate_method = "validate_#{name}"
- public_send(validate_method, val) if self.respond_to? validate_method
+ public_send(validate_method, val) if respond_to? validate_method
end
private
diff --git a/lib/slug.rb b/lib/slug.rb
index 16215a7445a..8b3d8774ad6 100644
--- a/lib/slug.rb
+++ b/lib/slug.rb
@@ -12,14 +12,14 @@ module Slug
slug =
case method
when :ascii
- self.ascii_generator(string)
+ ascii_generator(string)
when :encoded
- self.encoded_generator(string)
+ encoded_generator(string)
when :none
- self.none_generator(string)
+ none_generator(string)
end
- slug = self.prettify_slug(slug, max_length: max_length)
+ slug = prettify_slug(slug, max_length: max_length)
(slug.blank? || slug_is_only_numbers?(slug)) ? default : slug
end
diff --git a/lib/socket_server.rb b/lib/socket_server.rb
index c19d9ec2a02..bfb2e03f177 100644
--- a/lib/socket_server.rb
+++ b/lib/socket_server.rb
@@ -29,7 +29,7 @@ class SocketServer
done = false
done = !accept_connection(server) while !done
ensure
- self.stop
+ stop
Rails.logger.info("Cleaned up socket server at #{@socket_path}")
end
end
diff --git a/lib/stylesheet/manager.rb b/lib/stylesheet/manager.rb
index 5ff60fe0ca4..37e6c9ee8ba 100644
--- a/lib/stylesheet/manager.rb
+++ b/lib/stylesheet/manager.rb
@@ -90,7 +90,7 @@ class Stylesheet::Manager
compiled = Set.new
themes.each do |theme_id, light_color_scheme_id, dark_color_scheme_id|
- manager = self.new(theme_id: theme_id)
+ manager = new(theme_id: theme_id)
targets.each do |target|
next if theme_id == -1
diff --git a/lib/stylesheet/manager/builder.rb b/lib/stylesheet/manager/builder.rb
index ba07a32bea6..e7d3fb862ff 100644
--- a/lib/stylesheet/manager/builder.rb
+++ b/lib/stylesheet/manager/builder.rb
@@ -130,7 +130,7 @@ class Stylesheet::Manager::Builder
end
def stylesheet_filename(with_digest = true)
- digest_string = "_#{self.digest}" if with_digest
+ digest_string = "_#{digest}" if with_digest
"#{qualified_target}#{digest_string}.css"
end
diff --git a/lib/system_message.rb b/lib/system_message.rb
index 96f752b9cb3..823f4f261a6 100644
--- a/lib/system_message.rb
+++ b/lib/system_message.rb
@@ -4,12 +4,12 @@
class SystemMessage
def self.create(recipient, type, params = {})
- self.new(recipient).create(type, params)
+ new(recipient).create(type, params)
end
def self.create_from_system_user(recipient, type, params = {})
params = params.merge(from_system: true)
- self.new(recipient).create(type, params)
+ new(recipient).create(type, params)
end
def initialize(recipient)
diff --git a/lib/temporary_redis.rb b/lib/temporary_redis.rb
index c567ecab083..8e3aa110729 100644
--- a/lib/temporary_redis.rb
+++ b/lib/temporary_redis.rb
@@ -60,7 +60,7 @@ class TemporaryRedis
ensure
if !success && (Time.now - start) >= 5
STDERR.puts "ERROR: Could not connect to redis in 5 seconds."
- self.remove
+ remove
exit(1)
elsif !success
sleep 0.1
diff --git a/lib/theme_settings_manager.rb b/lib/theme_settings_manager.rb
index 7fe1fd47073..e3d9e9b438b 100644
--- a/lib/theme_settings_manager.rb
+++ b/lib/theme_settings_manager.rb
@@ -8,13 +8,13 @@ class ThemeSettingsManager
end
def self.cast_row_value(row)
- type_name = self.types.invert[row.data_type].downcase.capitalize
+ type_name = types.invert[row.data_type].downcase.capitalize
klass = "ThemeSettingsManager::#{type_name}".constantize
klass.cast(klass.extract_value_from_row(row))
end
def self.create(name, default, type, theme, opts = {})
- type_name = self.types.invert[type].downcase.capitalize
+ type_name = types.invert[type].downcase.capitalize
klass = "ThemeSettingsManager::#{type_name}".constantize
klass.new(name, default, theme, opts)
end
diff --git a/lib/theme_settings_validator.rb b/lib/theme_settings_validator.rb
index 62ad8d74118..ea560c4ae72 100644
--- a/lib/theme_settings_validator.rb
+++ b/lib/theme_settings_validator.rb
@@ -9,15 +9,15 @@ class ThemeSettingsValidator
def is_valid_value_type?(value, type)
case type
- when self.types[:integer]
+ when types[:integer]
value.is_a?(Integer)
- when self.types[:float]
+ when types[:float]
value.is_a?(Integer) || value.is_a?(Float)
- when self.types[:bool]
+ when types[:bool]
value.is_a?(TrueClass) || value.is_a?(FalseClass)
- when self.types[:list]
+ when types[:list]
value.is_a?(String)
- when self.types[:objects]
+ when types[:objects]
value.is_a?(Array) && value.all? { |v| v.is_a?(Hash) }
else
true
diff --git a/lib/theme_translation_manager.rb b/lib/theme_translation_manager.rb
index 31a171982f4..3cec678893d 100644
--- a/lib/theme_translation_manager.rb
+++ b/lib/theme_translation_manager.rb
@@ -9,14 +9,9 @@ class ThemeTranslationManager
.map do |key, value|
this_key_array = parent_keys + [key]
if value.is_a?(Hash)
- self.list_from_hash(
- locale: locale,
- hash: value,
- theme: theme,
- parent_keys: this_key_array,
- )
+ list_from_hash(locale: locale, hash: value, theme: theme, parent_keys: this_key_array)
else
- self.new(locale: locale, theme: theme, key: this_key_array.join("."), default: value)
+ new(locale: locale, theme: theme, key: this_key_array.join("."), default: value)
end
end
.flatten
diff --git a/lib/theme_translation_parser.rb b/lib/theme_translation_parser.rb
index 2f05e8d8bdb..c11515c5091 100644
--- a/lib/theme_translation_parser.rb
+++ b/lib/theme_translation_parser.rb
@@ -12,7 +12,7 @@ class ThemeTranslationParser
def self.check_contains_hashes(hash)
hash.all? do |_key, value|
- value.is_a?(String) || (value.is_a?(Hash) && self.check_contains_hashes(value))
+ value.is_a?(String) || (value.is_a?(Hash) && check_contains_hashes(value))
end
end
diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb
index 18e01df7af2..853a9010af5 100644
--- a/lib/topic_creator.rb
+++ b/lib/topic_creator.rb
@@ -6,7 +6,7 @@ class TopicCreator
include HasErrors
def self.create(user, guardian, opts)
- self.new(user, guardian, opts).create
+ new(user, guardian, opts).create
end
def initialize(user, guardian, opts)
diff --git a/lib/topic_query.rb b/lib/topic_query.rb
index 9a2e32a23a6..60511264ae9 100644
--- a/lib/topic_query.rb
+++ b/lib/topic_query.rb
@@ -433,7 +433,7 @@ class TopicQuery
end
def self.unseen_filter(list, user)
- self.new.unseen_filter(list, user.first_seen_at || user.created_at, user.whisperer?)
+ new.unseen_filter(list, user.first_seen_at || user.created_at, user.whisperer?)
end
def self.new_filter(list, treat_as_new_topic_start_date: nil, treat_as_new_topic_clause_sql: nil)
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index 93e30c6e02d..f25fb05383e 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -140,7 +140,7 @@ class TopicView
@message_bus_last_id = MessageBus.last_id("/topic/#{@topic.id}")
- options.each { |key, value| self.instance_variable_set(:"@#{key}", value) }
+ options.each { |key, value| instance_variable_set(:"@#{key}", value) }
@post_number = [@post_number.to_i, 1].max
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rb
index b8128c6cee7..ef8a3e97193 100644
--- a/lib/topics_filter.rb
+++ b/lib/topics_filter.rb
@@ -491,7 +491,7 @@ class TopicsFilter
column_name: "first_posts.like_count",
min:,
max:,
- scope: self.joins_first_posts(@scope),
+ scope: joins_first_posts(@scope),
)
end
diff --git a/lib/upcoming_changes.rb b/lib/upcoming_changes.rb
index cd0ae21f00c..f4c105e5a98 100644
--- a/lib/upcoming_changes.rb
+++ b/lib/upcoming_changes.rb
@@ -59,17 +59,16 @@ module UpcomingChanges
end
def self.previous_status_value(status)
- status_value = self.statuses[status.to_sym]
- self.statuses.values.select { |value| value < status_value }.max || -100
+ status_value = statuses[status.to_sym]
+ statuses.values.select { |value| value < status_value }.max || -100
end
def self.previous_status(status)
- self.statuses.keys.select { |key| self.statuses[key] < self.statuses[status.to_sym] }.last ||
- :conceptual
+ statuses.keys.select { |key| statuses[key] < statuses[status.to_sym] }.last || :conceptual
end
def self.image_exists?(change_setting_name)
- File.exist?(File.join(Rails.public_path, self.image_path(change_setting_name)))
+ File.exist?(File.join(Rails.public_path, image_path(change_setting_name)))
end
def self.image_path(change_setting_name)
diff --git a/lib/url_helper.rb b/lib/url_helper.rb
index b24c01f10f5..06e8cc8f541 100644
--- a/lib/url_helper.rb
+++ b/lib/url_helper.rb
@@ -78,7 +78,7 @@ class UrlHelper
end
def self.absolute_without_cdn(url)
- self.absolute(url, nil)
+ absolute(url, nil)
end
def self.schemaless(url)
@@ -86,7 +86,7 @@ class UrlHelper
end
def self.secure_proxy_without_cdn(url)
- self.absolute(Upload.secure_uploads_url_from_upload_url(url), nil)
+ absolute(Upload.secure_uploads_url_from_upload_url(url), nil)
end
def self.normalized_encode(uri)
diff --git a/lib/wizard.rb b/lib/wizard.rb
index 2b327602cdb..8d3966763b8 100644
--- a/lib/wizard.rb
+++ b/lib/wizard.rb
@@ -133,6 +133,6 @@ class Wizard
end
def self.user_requires_completion?(user)
- self.new(user).requires_completion?
+ new(user).requires_completion?
end
end
diff --git a/migrations/lib/converters.rb b/migrations/lib/converters.rb
index bd20388a60d..15c4b5f8c5c 100644
--- a/migrations/lib/converters.rb
+++ b/migrations/lib/converters.rb
@@ -28,12 +28,12 @@ module Migrations
end
def self.names
- self.all.keys.sort
+ all.keys.sort
end
def self.path_of(converter_name)
converter_name = converter_name.downcase
- path = self.all[converter_name]
+ path = all[converter_name]
raise "Could not find a converter named '#{converter_name}'" unless path
path
end
diff --git a/plugins/automation/app/models/discourse_automation/automation.rb b/plugins/automation/app/models/discourse_automation/automation.rb
index 9e606cb2cbc..9ec041aeb8d 100644
--- a/plugins/automation/app/models/discourse_automation/automation.rb
+++ b/plugins/automation/app/models/discourse_automation/automation.rb
@@ -57,8 +57,8 @@ module DiscourseAutomation
change_automation_ids_custom_field_in_mutex(target, custom_field_key) do
target.reload
ids = Array(target.custom_fields[custom_field_key])
- if !ids.include?(self.id)
- ids << self.id
+ if !ids.include?(id)
+ ids << id
ids = ids.compact.uniq
target.custom_fields[custom_field_key] = ids
target.save_custom_fields
@@ -74,9 +74,9 @@ module DiscourseAutomation
change_automation_ids_custom_field_in_mutex(target, custom_field_key) do
target.reload
ids = Array(target.custom_fields[custom_field_key])
- if ids.include?(self.id)
+ if ids.include?(id)
ids = ids.compact.uniq
- ids.delete(self.id)
+ ids.delete(id)
target.custom_fields[custom_field_key] = ids
target.save_custom_fields
end
@@ -152,7 +152,7 @@ module DiscourseAutomation
return if active_id = DiscourseAutomation.get_active_automation
begin
- DiscourseAutomation.set_active_automation(self.id)
+ DiscourseAutomation.set_active_automation(id)
if scriptable.background && !running_in_background
trigger_in_background!(context)
else
@@ -191,7 +191,7 @@ module DiscourseAutomation
end
def new_user_custom_field_name
- "automation_#{self.id}_new_user"
+ "automation_#{id}_new_user"
end
private
diff --git a/plugins/automation/lib/discourse_automation/post_extension.rb b/plugins/automation/lib/discourse_automation/post_extension.rb
index e48a2ddd9a7..470a76a892d 100644
--- a/plugins/automation/lib/discourse_automation/post_extension.rb
+++ b/plugins/automation/lib/discourse_automation/post_extension.rb
@@ -8,7 +8,7 @@ module DiscourseAutomation
def discourse_automation_topic_required_words
return if !SiteSetting.discourse_automation_enabled
- return if self.post_type == Post.types[:small_action]
+ return if post_type == Post.types[:small_action]
return if !topic
return if topic.custom_fields[DiscourseAutomation::AUTOMATION_IDS_CUSTOM_FIELD].blank?
diff --git a/plugins/chat/app/models/chat/category_channel.rb b/plugins/chat/app/models/chat/category_channel.rb
index f8f20c83315..908debf3b5c 100644
--- a/plugins/chat/app/models/chat/category_channel.rb
+++ b/plugins/chat/app/models/chat/category_channel.rb
@@ -24,8 +24,8 @@ module Chat
end
def generate_auto_slug
- return if self.slug.present?
- self.slug = Slug.for(self.title.strip, "")
+ return if slug.present?
+ self.slug = Slug.for(title.strip, "")
self.slug = "" if duplicate_slug?
end
end
diff --git a/plugins/chat/app/models/chat/channel.rb b/plugins/chat/app/models/chat/channel.rb
index 00b80b508e3..4f03e4c19dd 100644
--- a/plugins/chat/app/models/chat/channel.rb
+++ b/plugins/chat/app/models/chat/channel.rb
@@ -143,7 +143,7 @@ module Chat
end
def leave(user)
- self.remove(user)
+ remove(user)
end
def pinned_messages_count
@@ -151,15 +151,15 @@ module Chat
end
def url
- "#{Discourse.base_url}/chat/c/#{self.slug || "-"}/#{self.id}"
+ "#{Discourse.base_url}/chat/c/#{slug || "-"}/#{id}"
end
def relative_url
- "#{Discourse.base_path}/chat/c/#{self.slug || "-"}/#{self.id}"
+ "#{Discourse.base_path}/chat/c/#{slug || "-"}/#{id}"
end
def update_last_message_id!
- self.update!(last_message_id: self.latest_not_deleted_message_id)
+ update!(last_message_id: latest_not_deleted_message_id)
end
def self.ensure_consistency!
@@ -222,7 +222,7 @@ module Chat
end
def latest_not_deleted_message_id(anchor_message_id: nil)
- DB.query_single(<<~SQL, channel_id: self.id, anchor_message_id: anchor_message_id).first
+ DB.query_single(<<~SQL, channel_id: id, anchor_message_id: anchor_message_id).first
SELECT chat_messages.id
FROM chat_messages
LEFT JOIN chat_threads original_message_threads ON original_message_threads.original_message_id = chat_messages.id
@@ -237,9 +237,9 @@ module Chat
end
def mark_all_threads_as_read(user: nil)
- return if !self.threading_enabled
+ return if !threading_enabled
- DB.exec(<<~SQL, channel_id: self.id)
+ DB.exec(<<~SQL, channel_id: id)
UPDATE user_chat_thread_memberships
SET last_read_message_id = chat_threads.last_message_id
FROM chat_threads
@@ -256,7 +256,7 @@ module Chat
def change_status(acting_user, target_status)
return if !Guardian.new(acting_user).can_change_channel_status?(self, target_status)
- self.update!(status: target_status)
+ update!(status: target_status)
log_channel_status_change(acting_user: acting_user)
end
@@ -271,11 +271,11 @@ module Chat
StaffActionLogger.new(acting_user).log_custom(
"chat_channel_status_change",
{
- chat_channel_id: self.id,
- chat_channel_name: self.name,
+ chat_channel_id: id,
+ chat_channel_name: name,
previous_value: status_previously_was,
new_value: status,
- category_id: category_channel? ? self.chatable_id : nil,
+ category_id: category_channel? ? chatable_id : nil,
},
)
@@ -283,7 +283,7 @@ module Chat
end
def duplicate_slug?
- Chat::Channel.where(slug: self.slug).where.not(id: self.id).any?
+ Chat::Channel.where(slug: slug).where.not(id: id).any?
end
end
end
diff --git a/plugins/chat/app/models/chat/channel_archive.rb b/plugins/chat/app/models/chat/channel_archive.rb
index 3276f65fd11..64befcd21fa 100644
--- a/plugins/chat/app/models/chat/channel_archive.rb
+++ b/plugins/chat/app/models/chat/channel_archive.rb
@@ -12,15 +12,15 @@ module Chat
self.table_name = "chat_channel_archives"
def complete?
- self.archived_messages >= self.total_messages && self.chat_channel.chat_messages.count.zero?
+ archived_messages >= total_messages && chat_channel.chat_messages.count.zero?
end
def failed?
- !complete? && self.archive_error.present?
+ !complete? && archive_error.present?
end
def new_topic?
- self.destination_topic_title.present?
+ destination_topic_title.present?
end
end
end
diff --git a/plugins/chat/app/models/chat/direct_message_channel.rb b/plugins/chat/app/models/chat/direct_message_channel.rb
index 2df9480bb2d..090539631e1 100644
--- a/plugins/chat/app/models/chat/direct_message_channel.rb
+++ b/plugins/chat/app/models/chat/direct_message_channel.rb
@@ -21,7 +21,7 @@ module Chat
end
def generate_auto_slug
- self.slug.blank?
+ slug.blank?
end
# Group DMs are DMs with > 2 users
diff --git a/plugins/chat/app/models/chat/draft.rb b/plugins/chat/app/models/chat/draft.rb
index f1a34660546..13a73f96783 100644
--- a/plugins/chat/app/models/chat/draft.rb
+++ b/plugins/chat/app/models/chat/draft.rb
@@ -9,8 +9,8 @@ module Chat
validate :data_length
def data_length
- if self.data && self.data.length > SiteSetting.max_chat_draft_length
- self.errors.add(:base, I18n.t("chat.errors.draft_too_long"))
+ if data && data.length > SiteSetting.max_chat_draft_length
+ errors.add(:base, I18n.t("chat.errors.draft_too_long"))
end
end
end
diff --git a/plugins/chat/app/models/chat/message.rb b/plugins/chat/app/models/chat/message.rb
index c272eae41bb..ae60f4fd5bf 100644
--- a/plugins/chat/app/models/chat/message.rb
+++ b/plugins/chat/app/models/chat/message.rb
@@ -125,12 +125,12 @@ module Chat
def validate_message
WatchedWordsValidator.new(attributes: [:message]).validate(self) if !user&.bot?
- if self.new_record? || self.changed.include?("message")
+ if new_record? || changed.include?("message")
Chat::DuplicateMessageValidator.new(self).validate
end
if uploads.empty? && message_too_short?
- self.errors.add(
+ errors.add(
:base,
I18n.t(
"chat.errors.minimum_length_not_met",
@@ -140,7 +140,7 @@ module Chat
end
if message_too_long?
- self.errors.add(
+ errors.add(
:base,
I18n.t("chat.errors.message_too_long", count: SiteSetting.chat_maximum_message_length),
)
@@ -174,21 +174,16 @@ module Chat
end
def only_uploads?
- self.message.blank? && self.uploads.present?
+ message.blank? && uploads.present?
end
def to_markdown
upload_markdown =
- self
- .upload_references
- .includes(:upload)
- .order(:created_at)
- .map(&:to_markdown)
- .reject(&:empty?)
+ upload_references.includes(:upload).order(:created_at).map(&:to_markdown).reject(&:empty?)
- return self.message if upload_markdown.empty?
+ return message if upload_markdown.empty?
- return ["#{self.message}\n"].concat(upload_markdown).join("\n") if self.message.present?
+ return ["#{message}\n"].concat(upload_markdown).join("\n") if message.present?
upload_markdown.join("\n")
end
@@ -196,7 +191,7 @@ module Chat
def cook
ensure_last_editor_id
- self.cooked = self.class.cook(self.message, user_id: self.last_editor_id)
+ self.cooked = self.class.cook(message, user_id: last_editor_id)
self.cooked_version = BAKED_VERSION
invalidate_parsed_mentions
@@ -204,7 +199,7 @@ module Chat
def rebake!(invalidate_oneboxes: false, priority: nil, skip_notifications: false)
ensure_last_editor_id
- args = { chat_message_id: self.id }
+ args = { chat_message_id: id }
args[:invalidate_oneboxes] = true if invalidate_oneboxes
args[:skip_notifications] = true if skip_notifications
args[:queue] = priority.to_s if priority && priority != :normal
@@ -301,9 +296,9 @@ module Chat
def url
if in_thread?
- "#{Discourse.base_path}/chat/c/-/#{self.chat_channel_id}/t/#{self.thread_id}/#{self.id}"
+ "#{Discourse.base_path}/chat/c/-/#{chat_channel_id}/t/#{thread_id}/#{id}"
else
- "#{Discourse.base_path}/chat/c/-/#{self.chat_channel_id}/#{self.id}"
+ "#{Discourse.base_path}/chat/c/-/#{chat_channel_id}/#{id}"
end
end
@@ -315,7 +310,7 @@ module Chat
end
def in_thread?
- self.thread_id.present? && (self.chat_channel.threading_enabled || self.thread&.force)
+ thread_id.present? && (chat_channel.threading_enabled || thread&.force)
end
def thread_reply?
@@ -323,7 +318,7 @@ module Chat
end
def thread_om?
- in_thread? && self.thread&.original_message_id == self.id
+ in_thread? && thread&.original_message_id == id
end
def parsed_mentions
@@ -344,9 +339,7 @@ module Chat
return if target_ids.empty?
mentions =
- target_ids.map do |target_id|
- { chat_message_id: self.id, target_id: target_id, type: type }
- end
+ target_ids.map { |target_id| { chat_message_id: id, target_id: target_id, type: type } }
Chat::Mention.insert_all(mentions)
end
@@ -360,7 +353,7 @@ module Chat
end
def ensure_last_editor_id
- self.last_editor_id ||= self.user_id
+ self.last_editor_id ||= user_id
end
def create_or_delete_all_mention
diff --git a/plugins/chat/app/models/chat/thread.rb b/plugins/chat/app/models/chat/thread.rb
index 60e6bf56692..edb06582e4b 100644
--- a/plugins/chat/app/models/chat/thread.rb
+++ b/plugins/chat/app/models/chat/thread.rb
@@ -68,7 +68,7 @@ module Chat
# Since the `replies` for the thread can all be deleted, to avoid errors
# in lists and previews of the thread, we can consider the original message
# as the last message in this case as a fallback.
- before_create { self.last_message_id = self.original_message_id }
+ before_create { self.last_message_id = original_message_id }
def add(user, notification_level: Chat::NotificationLevels.all[:tracking])
membership = Chat::UserChatThreadMembership.find_by(user:, thread: self)
@@ -97,15 +97,15 @@ module Chat
end
def replies
- self.chat_messages.where.not(id: self.original_message_id).order("created_at ASC, id ASC")
+ chat_messages.where.not(id: original_message_id).order("created_at ASC, id ASC")
end
def url
- "#{channel.url}/t/#{self.id}"
+ "#{channel.url}/t/#{id}"
end
def relative_url
- "#{channel.relative_url}/t/#{self.id}"
+ "#{channel.relative_url}/t/#{id}"
end
def excerpt
@@ -113,7 +113,7 @@ module Chat
end
def update_last_message_id!
- self.update!(last_message_id: self.latest_not_deleted_message_id)
+ update!(last_message_id: latest_not_deleted_message_id)
end
def latest_not_deleted_message_id(anchor_message_id: nil)
@@ -127,8 +127,8 @@ module Chat
ORDER BY created_at DESC, id DESC
LIMIT 1
SQL
- channel_id: self.channel_id,
- thread_id: self.id,
+ channel_id: channel_id,
+ thread_id: id,
anchor_message_id: anchor_message_id,
).first
end
@@ -173,7 +173,7 @@ module Chat
RETURNING ct.id AS thread_id
SQL
return if updated_thread_ids.empty?
- self.clear_caches!(updated_thread_ids)
+ clear_caches!(updated_thread_ids)
end
end
end
diff --git a/plugins/chat/app/models/concerns/chat/thread_cache.rb b/plugins/chat/app/models/concerns/chat/thread_cache.rb
index ee3735438eb..fd2eb00cf29 100644
--- a/plugins/chat/app/models/concerns/chat/thread_cache.rb
+++ b/plugins/chat/app/models/concerns/chat/thread_cache.rb
@@ -31,51 +31,47 @@ module Chat
def replies_count_cache_updated_at
Time.at(
- Discourse.redis.get(Chat::Thread.replies_count_cache_updated_at_redis_key(self.id)).to_i,
+ Discourse.redis.get(Chat::Thread.replies_count_cache_updated_at_redis_key(id)).to_i,
in: Time.zone,
)
end
def replies_count_cache
- redis_cache = Discourse.redis.get(Chat::Thread.replies_count_cache_redis_key(self.id))&.to_i
+ redis_cache = Discourse.redis.get(Chat::Thread.replies_count_cache_redis_key(id))&.to_i
# If the cache is not present for whatever reason, set it to the current value,
# otherwise INCR/DECR will be way off. No need to enqueue the job or publish,
# since this is likely fetched by a serializer.
if !redis_cache.present?
- set_replies_count_redis_cache(self.replies_count)
- self.replies_count
+ set_replies_count_redis_cache(replies_count)
+ replies_count
else
- redis_cache != self.replies_count ? redis_cache : self.replies_count
+ redis_cache != replies_count ? redis_cache : replies_count
end
end
def set_replies_count_cache(value, update_db: false)
- self.update!(replies_count: value) if update_db
+ update!(replies_count: value) if update_db
set_replies_count_redis_cache(value)
thread_reply_count_cache_changed
end
def set_replies_count_redis_cache(value)
- Discourse.redis.setex(
- Chat::Thread.replies_count_cache_redis_key(self.id),
- 5.minutes.to_i,
- value,
- )
+ Discourse.redis.setex(Chat::Thread.replies_count_cache_redis_key(id), 5.minutes.to_i, value)
end
def increment_replies_count_cache
- Discourse.redis.incr(Chat::Thread.replies_count_cache_redis_key(self.id))
+ Discourse.redis.incr(Chat::Thread.replies_count_cache_redis_key(id))
thread_reply_count_cache_changed
end
def decrement_replies_count_cache
- Discourse.redis.decr(Chat::Thread.replies_count_cache_redis_key(self.id))
+ Discourse.redis.decr(Chat::Thread.replies_count_cache_redis_key(id))
thread_reply_count_cache_changed
end
def thread_reply_count_cache_changed
- Jobs.enqueue_in(5.seconds, Jobs::Chat::UpdateThreadReplyCount, thread_id: self.id)
+ Jobs.enqueue_in(5.seconds, Jobs::Chat::UpdateThreadReplyCount, thread_id: id)
end
end
end
diff --git a/plugins/chat/app/services/chat/publisher.rb b/plugins/chat/app/services/chat/publisher.rb
index 57da6615f15..a4c7bf3f2fc 100644
--- a/plugins/chat/app/services/chat/publisher.rb
+++ b/plugins/chat/app/services/chat/publisher.rb
@@ -44,7 +44,7 @@ module Chat
if !chat_message.thread_reply? || !allow_publish_to_thread?(chat_channel, chat_message)
MessageBus.publish(
- self.new_messages_message_bus_channel(chat_channel.id),
+ new_messages_message_bus_channel(chat_channel.id),
{
type: "channel",
channel_id: chat_channel.id,
@@ -61,7 +61,7 @@ module Chat
if chat_message.thread_reply? && allow_publish_to_thread?(chat_channel, chat_message)
MessageBus.publish(
- self.new_messages_message_bus_channel(chat_channel.id),
+ new_messages_message_bus_channel(chat_channel.id),
{
type: "thread",
channel_id: chat_channel.id,
@@ -320,7 +320,7 @@ module Chat
end
MessageBus.publish(
- self.user_tracking_state_message_bus_channel(user.id),
+ user_tracking_state_message_bus_channel(user.id),
data.as_json,
user_ids: [user.id],
)
@@ -349,7 +349,7 @@ module Chat
end
MessageBus.publish(
- self.bulk_user_tracking_state_message_bus_channel(user.id),
+ bulk_user_tracking_state_message_bus_channel(user.id),
channel_last_read_map.as_json,
user_ids: [user.id],
)
@@ -365,7 +365,7 @@ module Chat
def self.publish_new_mention(user_id, chat_channel_id, chat_message_id)
MessageBus.publish(
- self.new_mentions_message_bus_channel(chat_channel_id),
+ new_mentions_message_bus_channel(chat_channel_id),
{ message_id: chat_message_id, channel_id: chat_channel_id }.as_json,
user_ids: [user_id],
)
diff --git a/plugins/chat/lib/chat/message_bookmarkable.rb b/plugins/chat/lib/chat/message_bookmarkable.rb
index 9af05d68a70..caed07359f6 100644
--- a/plugins/chat/lib/chat/message_bookmarkable.rb
+++ b/plugins/chat/lib/chat/message_bookmarkable.rb
@@ -69,7 +69,7 @@ module Chat
def self.reminder_conditions(bookmark)
bookmark.bookmarkable.present? && bookmark.bookmarkable.chat_channel.present? &&
- self.can_see?(bookmark.user.guardian, bookmark)
+ can_see?(bookmark.user.guardian, bookmark)
end
def self.can_see?(guardian, bookmark)
diff --git a/plugins/chat/lib/chat/message_rate_limiter.rb b/plugins/chat/lib/chat/message_rate_limiter.rb
index 8d1f3b83f00..fd13fa98392 100644
--- a/plugins/chat/lib/chat/message_rate_limiter.rb
+++ b/plugins/chat/lib/chat/message_rate_limiter.rb
@@ -3,7 +3,7 @@
module Chat
class MessageRateLimiter
def self.run!(user)
- instance = self.new(user)
+ instance = new(user)
instance.run!
end
diff --git a/plugins/chat/lib/chat_sdk/message.rb b/plugins/chat/lib/chat_sdk/message.rb
index c9c964c8885..b3adccec021 100644
--- a/plugins/chat/lib/chat_sdk/message.rb
+++ b/plugins/chat/lib/chat_sdk/message.rb
@@ -35,7 +35,7 @@ module ChatSDK
#
# @see #create
def self.create_with_stream(**params, &block)
- self.create(**params, streaming: true, strip_whitespaces: false, &block)
+ create(**params, streaming: true, strip_whitespaces: false, &block)
end
# Streams to a specific chat message.
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 90a05da3636..5eb6bb32760 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -208,7 +208,7 @@ after_initialize do
add_to_serializer(:current_user, :has_joinable_public_channels) do
Chat::ChannelFetcher.secured_public_channel_search(
- self.scope,
+ scope,
following: false,
limit: 1,
status: :open,
@@ -236,7 +236,7 @@ after_initialize do
@has_chat_enabled =
SiteSetting.chat_enabled && scope.can_chat? && object.user_option.chat_enabled
end,
- ) { Chat::ChannelFetcher.unreads_total(self.scope) }
+ ) { Chat::ChannelFetcher.unreads_total(scope) }
add_to_serializer(:user_option, :chat_enabled) { object.chat_enabled }
diff --git a/plugins/chat/spec/system/page_objects/chat/components/channel_row.rb b/plugins/chat/spec/system/page_objects/chat/components/channel_row.rb
index fc963a6efb8..248eec5ad16 100644
--- a/plugins/chat/spec/system/page_objects/chat/components/channel_row.rb
+++ b/plugins/chat/spec/system/page_objects/chat/components/channel_row.rb
@@ -37,7 +37,7 @@ module PageObjects
def build_selector(**args)
selector = SELECTOR
selector += args[:class] if args[:class]
- selector += "[data-chat-channel-id=\"#{self.id}\"]" if self.id
+ selector += "[data-chat-channel-id=\"#{id}\"]" if id
selector
end
end
diff --git a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb
index 57c63a92fbb..56b0c867e8e 100644
--- a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb
+++ b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb
@@ -86,7 +86,7 @@ module AdPlugin
def sanitize_html
return unless html_changed?
- fragment = Loofah.html5_fragment(self.html)
+ fragment = Loofah.html5_fragment(html)
scrubber =
Loofah::Scrubber.new do |node|
diff --git a/plugins/discourse-adplugin/lib/adplugin/guardian_extensions.rb b/plugins/discourse-adplugin/lib/adplugin/guardian_extensions.rb
index 53120bb7a1a..a0c3e139727 100644
--- a/plugins/discourse-adplugin/lib/adplugin/guardian_extensions.rb
+++ b/plugins/discourse-adplugin/lib/adplugin/guardian_extensions.rb
@@ -3,27 +3,27 @@
module AdPlugin
module GuardianExtensions
def show_dfp_ads?
- !self.user.in_any_groups?(SiteSetting.dfp_exclude_groups_map)
+ !user.in_any_groups?(SiteSetting.dfp_exclude_groups_map)
end
def show_adsense_ads?
- !self.user.in_any_groups?(SiteSetting.adsense_exclude_groups_map)
+ !user.in_any_groups?(SiteSetting.adsense_exclude_groups_map)
end
def show_carbon_ads?
- !self.user.in_any_groups?(SiteSetting.carbonads_exclude_groups_map)
+ !user.in_any_groups?(SiteSetting.carbonads_exclude_groups_map)
end
def show_amazon_ads?
- !self.user.in_any_groups?(SiteSetting.amazon_exclude_groups_map)
+ !user.in_any_groups?(SiteSetting.amazon_exclude_groups_map)
end
def show_adbutler_ads?
- !self.user.in_any_groups?(SiteSetting.adbutler_exclude_groups_map)
+ !user.in_any_groups?(SiteSetting.adbutler_exclude_groups_map)
end
def show_to_groups?
- !self.user.in_any_groups?(SiteSetting.no_ads_for_groups_map)
+ !user.in_any_groups?(SiteSetting.no_ads_for_groups_map)
end
end
end
diff --git a/plugins/discourse-ai/app/models/ai_agent.rb b/plugins/discourse-ai/app/models/ai_agent.rb
index 1c9094a04f8..f7cf391d76d 100644
--- a/plugins/discourse-ai/app/models/ai_agent.rb
+++ b/plugins/discourse-ai/app/models/ai_agent.rb
@@ -234,7 +234,7 @@ class AiAgent < ActiveRecord::Base
instance_attributes = {}
attributes.each do |attr|
- value = self.read_attribute(attr)
+ value = self[attr]
instance_attributes[attr] = value
end
@@ -293,7 +293,7 @@ class AiAgent < ActiveRecord::Base
)
instance_attributes[:mcp_server_ids] = enabled_mcp_servers.map(&:id)
- agent_class = DiscourseAi::Agents::Agent.system_agents_by_id[self.id]
+ agent_class = DiscourseAi::Agents::Agent.system_agents_by_id[id]
if agent_class
return(
# we need a new copy so we don't leak information
@@ -310,7 +310,7 @@ class AiAgent < ActiveRecord::Base
)
end
- ai_agent_id = self.id
+ ai_agent_id = id
Class.new(DiscourseAi::Agents::Agent) do
instance_attributes.each { |key, value| define_singleton_method(key) { value } }
diff --git a/plugins/discourse-ai/app/models/ai_mcp_server.rb b/plugins/discourse-ai/app/models/ai_mcp_server.rb
index 32fb8182e9a..39478ef0bd0 100644
--- a/plugins/discourse-ai/app/models/ai_mcp_server.rb
+++ b/plugins/discourse-ai/app/models/ai_mcp_server.rb
@@ -411,7 +411,7 @@ class AiMcpServer < ActiveRecord::Base
if instance_variable_defined?(:@tools_for_serialization)
remove_instance_variable(:@tools_for_serialization)
end
- DiscourseAi::Mcp::ToolRegistry.invalidate!(self.id)
+ DiscourseAi::Mcp::ToolRegistry.invalidate!(id)
AiAgent.agent_cache.flush!
end
diff --git a/plugins/discourse-ai/app/models/embedding_definition.rb b/plugins/discourse-ai/app/models/embedding_definition.rb
index bdf5ac9d913..03c2df8a5ca 100644
--- a/plugins/discourse-ai/app/models/embedding_definition.rb
+++ b/plugins/discourse-ai/app/models/embedding_definition.rb
@@ -133,7 +133,7 @@ class EmbeddingDefinition < ActiveRecord::Base
after_create :create_indexes
def create_indexes
- Jobs.enqueue(:manage_embedding_def_search_index, id: self.id)
+ Jobs.enqueue(:manage_embedding_def_search_index, id: id)
end
def tokenizer
diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rb
index 4c43b8f2945..5449616fcb8 100644
--- a/plugins/discourse-ai/app/models/llm_model.rb
+++ b/plugins/discourse-ai/app/models/llm_model.rb
@@ -361,7 +361,7 @@ class LlmModel < ActiveRecord::Base
trust_level: TrustLevel[4],
)
new_user.save!(validate: false)
- self.update!(user: new_user)
+ update!(user: new_user)
else
user.active = true
user.save!(validate: false)
@@ -381,7 +381,7 @@ class LlmModel < ActiveRecord::Base
user.update!(active: false) if user.active
else
user.destroy!
- self.update!(user: nil)
+ update!(user: nil)
end
end
diff --git a/plugins/discourse-ai/app/models/shared_ai_conversation.rb b/plugins/discourse-ai/app/models/shared_ai_conversation.rb
index 51cf2bbc411..1326d5fae52 100644
--- a/plugins/discourse-ai/app/models/shared_ai_conversation.rb
+++ b/plugins/discourse-ai/app/models/shared_ai_conversation.rb
@@ -76,7 +76,7 @@ class SharedAiConversation < ActiveRecord::Base
def to_json
posts =
- self.populated_context.map do |post|
+ populated_context.map do |post|
{
id: post.id,
cooked: post.cooked,
@@ -84,7 +84,7 @@ class SharedAiConversation < ActiveRecord::Base
created_at: post.created_at,
}
end
- { llm_name: self.llm_name, share_key: self.share_key, title: self.title, posts: posts }
+ { llm_name: llm_name, share_key: share_key, title: title, posts: posts }
end
def url
diff --git a/plugins/discourse-ai/discourse_automation/llm_agent_triage.rb b/plugins/discourse-ai/discourse_automation/llm_agent_triage.rb
index d6a54c4c6ef..c74eca584b6 100644
--- a/plugins/discourse-ai/discourse_automation/llm_agent_triage.rb
+++ b/plugins/discourse-ai/discourse_automation/llm_agent_triage.rb
@@ -45,7 +45,7 @@ if defined?(DiscourseAutomation)
post: post,
agent_id: agent_id,
whisper: whisper,
- automation: self.automation,
+ automation: automation,
silent_mode: silent_mode,
action: context["action"],
)
diff --git a/plugins/discourse-ai/discourse_automation/llm_tagger.rb b/plugins/discourse-ai/discourse_automation/llm_tagger.rb
index 3949da67780..a8a631ce82c 100644
--- a/plugins/discourse-ai/discourse_automation/llm_tagger.rb
+++ b/plugins/discourse-ai/discourse_automation/llm_tagger.rb
@@ -121,7 +121,7 @@ if defined?(DiscourseAutomation)
max_post_tokens: max_post_tokens,
allow_restricted_tags: allow_restricted_tags,
max_posts_for_context: max_posts_for_context,
- automation: self.automation,
+ automation: automation,
)
post.topic.custom_fields["llm_tagger_processed"] = true
diff --git a/plugins/discourse-ai/discourse_automation/llm_triage.rb b/plugins/discourse-ai/discourse_automation/llm_triage.rb
index dbc59f9a412..8e5abe3a9c0 100644
--- a/plugins/discourse-ai/discourse_automation/llm_triage.rb
+++ b/plugins/discourse-ai/discourse_automation/llm_triage.rb
@@ -147,7 +147,7 @@ if defined?(DiscourseAutomation)
flag_type: flag_type.to_s.to_sym,
max_post_tokens: max_post_tokens,
stop_sequences: stop_sequences,
- automation: self.automation,
+ automation: automation,
max_output_tokens: max_output_tokens,
action: context["action"],
notify_author_pm: notify_author_pm,
diff --git a/plugins/discourse-ai/lib/agents/tool_runner.rb b/plugins/discourse-ai/lib/agents/tool_runner.rb
index 383bca0f005..14c9b2b9415 100644
--- a/plugins/discourse-ai/lib/agents/tool_runner.rb
+++ b/plugins/discourse-ai/lib/agents/tool_runner.rb
@@ -367,7 +367,7 @@ module DiscourseAi
while !done
# this is not accurate. but reasonable enough for a timeout
sleep(0.001)
- elapsed += 1 if !self.running_attached_function
+ elapsed += 1 if !running_attached_function
if elapsed > timeout
mutex.synchronize { mini_racer_context.stop unless done }
break
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/index.rb b/plugins/discourse-ai/lib/agents/tool_runner/index.rb
index d7d436084dc..7e752b7feb2 100644
--- a/plugins/discourse-ai/lib/agents/tool_runner/index.rb
+++ b/plugins/discourse-ai/lib/agents/tool_runner/index.rb
@@ -13,7 +13,7 @@ module DiscourseAi
self.running_attached_function = true
options ||= {}
options = options.symbolize_keys
- self.rag_search(query, **options)
+ rag_search(query, **options)
end
end,
)
diff --git a/plugins/discourse-ai/lib/agents/tools/create_artifact.rb b/plugins/discourse-ai/lib/agents/tools/create_artifact.rb
index 36cbf602f8c..9e3255843f0 100644
--- a/plugins/discourse-ai/lib/agents/tools/create_artifact.rb
+++ b/plugins/discourse-ai/lib/agents/tools/create_artifact.rb
@@ -127,7 +127,7 @@ module DiscourseAi
update_custom_html(artifact)
success_response(artifact)
else
- self.custom_raw = self.custom_raw + "\n\n###Error creating artifact..."
+ self.custom_raw = custom_raw + "\n\n###Error creating artifact..."
error_response(artifact.errors.full_messages.join(", "))
end
end
diff --git a/plugins/discourse-ai/lib/agents/tools/researcher.rb b/plugins/discourse-ai/lib/agents/tools/researcher.rb
index fdc0a04d930..21dbfae4447 100644
--- a/plugins/discourse-ai/lib/agents/tools/researcher.rb
+++ b/plugins/discourse-ai/lib/agents/tools/researcher.rb
@@ -202,7 +202,7 @@ module DiscourseAi
(
options[:researcher_llm].present? &&
LlmModel.find_by(id: options[:researcher_llm].to_i)&.to_llm
- ) || self.llm
+ ) || llm
end
def run_inference(chunk_text, goals, post, &blk)
diff --git a/plugins/discourse-ai/lib/ai_helper/assistant.rb b/plugins/discourse-ai/lib/ai_helper/assistant.rb
index f6c810a492b..63a19de039c 100644
--- a/plugins/discourse-ai/lib/ai_helper/assistant.rb
+++ b/plugins/discourse-ai/lib/ai_helper/assistant.rb
@@ -30,7 +30,7 @@ module DiscourseAi
def available_prompts(user)
key = "prompt_cache_#{I18n.locale}"
- prompts = self.class.prompt_cache.fetch(key) { self.all_prompts }
+ prompts = self.class.prompt_cache.fetch(key) { all_prompts }
prompts
.map do |prompt|
diff --git a/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb b/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb
index 7b11b60fc65..a729acc481a 100644
--- a/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb
+++ b/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb
@@ -235,9 +235,9 @@ module DiscourseAi
build_bot_context(
messages: [target_msg],
custom_instructions: custom_instructions,
- user: self.flagging_user,
+ user: flagging_user,
)
- bot = build_scanner_bot(settings: settings, user: self.flagging_user)
+ bot = build_scanner_bot(settings: settings, user: flagging_user)
structured_output = nil
begin
diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/endpoint_compliance.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/endpoint_compliance.rb
index 8ad95b95eac..920fa6ffbe9 100644
--- a/plugins/discourse-ai/spec/lib/completions/endpoints/endpoint_compliance.rb
+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/endpoint_compliance.rb
@@ -105,7 +105,7 @@ class EndpointMock
end
def self.with_chunk_array_support(&blk)
- self.new(nil).with_chunk_array_support(&blk)
+ new(nil).with_chunk_array_support(&blk)
end
protected
diff --git a/plugins/discourse-assign/plugin.rb b/plugins/discourse-assign/plugin.rb
index c031f7622e3..b2c733755eb 100644
--- a/plugins/discourse-assign/plugin.rb
+++ b/plugins/discourse-assign/plugin.rb
@@ -76,7 +76,7 @@ after_initialize do
add_to_serializer(:group_show, :can_show_assigned_tab?) { object.can_show_assigned_tab? }
add_model_callback(UserCustomField, :before_save) do
- self.value = self.value.to_i if self.name == frequency_field
+ self.value = value.to_i if name == frequency_field
end
add_class_method(:group, :assign_allowed_groups) do
@@ -98,9 +98,7 @@ after_initialize do
) < 0
end
- add_to_class(:group, :can_show_assigned_tab?) do
- self.assignable_level > Group::ALIAS_LEVELS[:nobody]
- end
+ add_to_class(:group, :can_show_assigned_tab?) { assignable_level > Group::ALIAS_LEVELS[:nobody] }
add_to_class(:guardian, :can_assign?) { user && user.can_assign? }
diff --git a/plugins/discourse-calendar/app/models/calendar_event.rb b/plugins/discourse-calendar/app/models/calendar_event.rb
index 3ab588d3162..dcc1f484720 100644
--- a/plugins/discourse-calendar/app/models/calendar_event.rb
+++ b/plugins/discourse-calendar/app/models/calendar_event.rb
@@ -39,8 +39,8 @@ class CalendarEvent < ActiveRecord::Base
first_post = post.topic&.first_post
return if !first_post || !first_post.custom_fields[DiscourseCalendar::CALENDAR_CUSTOM_FIELD]
- from = self.convert_to_date_time(dates[0])
- to = self.convert_to_date_time(dates[1]) if dates.size == 2
+ from = convert_to_date_time(dates[0])
+ to = convert_to_date_time(dates[1]) if dates.size == 2
adjust_to = !to || !dates[1]["time"]
if !to && dates[0]["time"]
diff --git a/plugins/discourse-calendar/app/models/discourse_post_event/event.rb b/plugins/discourse-calendar/app/models/discourse_post_event/event.rb
index a0ebb4c9dd1..49501eb201f 100644
--- a/plugins/discourse-calendar/app/models/discourse_post_event/event.rb
+++ b/plugins/discourse-calendar/app/models/discourse_post_event/event.rb
@@ -49,21 +49,12 @@ module DiscoursePostEvent
end
def destroy_topic_custom_field
- if self.post && self.post.is_first_post?
- TopicCustomField.where(
- topic_id: self.post.topic_id,
- name: TOPIC_POST_EVENT_STARTS_AT,
- ).delete_all
-
- TopicCustomField.where(
- topic_id: self.post.topic_id,
- name: TOPIC_POST_EVENT_ENDS_AT,
- ).delete_all
-
- TopicCustomField.where(
- topic_id: self.post.topic_id,
- name: TOPIC_POST_EVENT_ALL_DAY,
- ).delete_all
+ if post && post.is_first_post?
+ TopicCustomField.where(topic_id: post.topic_id, name: TOPIC_POST_EVENT_STARTS_AT).delete_all
+
+ TopicCustomField.where(topic_id: post.topic_id, name: TOPIC_POST_EVENT_ENDS_AT).delete_all
+
+ TopicCustomField.where(topic_id: post.topic_id, name: TOPIC_POST_EVENT_ALL_DAY).delete_all
end
end
@@ -107,11 +98,7 @@ module DiscoursePostEvent
end
return if date.blank?
- Jobs.enqueue(
- :discourse_post_event_bump_topic,
- topic_id: self.post.topic_id,
- date: date.iso8601,
- )
+ Jobs.enqueue(:discourse_post_event_bump_topic, topic_id: post.topic_id, date: date.iso8601)
end
def validate_reminder_unit(input)
@@ -148,23 +135,22 @@ module DiscoursePostEvent
end
def on_going_event_invitees
- return [] if self.starts_at.nil? # Can't determine ongoing status without start time
- if !self.ends_at && self.starts_at < Time.now &&
- (!self.all_day || self.starts_at.end_of_day <= Time.now)
+ return [] if starts_at.nil? # Can't determine ongoing status without start time
+ if !ends_at && starts_at < Time.now && (!all_day || starts_at.end_of_day <= Time.now)
return []
end
- if self.ends_at
+ if ends_at
extended_ends_at =
- self.ends_at + SiteSetting.discourse_post_event_edit_notifications_time_extension.minutes
- return [] if !(self.starts_at..extended_ends_at).cover?(Time.now)
+ ends_at + SiteSetting.discourse_post_event_edit_notifications_time_extension.minutes
+ return [] if !(starts_at..extended_ends_at).cover?(Time.now)
end
invitees.where(status: DiscoursePostEvent::Invitee.statuses[:going])
end
def raw_invitees_length
- if self.raw_invitees && self.raw_invitees.length > 10
+ if raw_invitees && raw_invitees.length > 10
errors.add(
:base,
I18n.t("discourse_post_event.errors.models.event.raw_invitees_length", count: 10),
@@ -173,7 +159,7 @@ module DiscoursePostEvent
end
def raw_invitees_are_groups
- if self.raw_invitees && User.select(:id).where(username: self.raw_invitees).limit(1).count > 0
+ if raw_invitees && User.select(:id).where(username: raw_invitees).limit(1).count > 0
errors.add(
:base,
I18n.t("discourse_post_event.errors.models.event.raw_invitees.only_group"),
@@ -182,8 +168,7 @@ module DiscoursePostEvent
end
def ends_before_start
- if self.original_starts_at && self.original_ends_at &&
- self.original_starts_at >= self.original_ends_at
+ if original_starts_at && original_ends_at && original_starts_at >= original_ends_at
errors.add(
:base,
I18n.t("discourse_post_event.errors.models.event.ends_at_before_starts_at"),
@@ -193,7 +178,7 @@ module DiscoursePostEvent
def allowed_custom_fields
allowed_custom_fields = SiteSetting.discourse_post_event_allowed_custom_fields.split("|")
- self.custom_fields.each do |key, value|
+ custom_fields.each do |key, value|
if !allowed_custom_fields.include?(key)
errors.add(
:base,
@@ -206,9 +191,9 @@ module DiscoursePostEvent
def create_invitees(attrs)
timestamp = Time.now
attrs.map! do |attr|
- { post_id: self.id, created_at: timestamp, updated_at: timestamp }.merge(attr)
+ { post_id: id, created_at: timestamp, updated_at: timestamp }.merge(attr)
end
- result = self.invitees.insert_all!(attrs)
+ result = invitees.insert_all!(attrs)
# batch event does not call callback
ChatChannelSync.sync(self) if chat_enabled?
@@ -217,21 +202,16 @@ module DiscoursePostEvent
end
def notify_invitees!(predefined_attendance: false)
- self
- .invitees
+ invitees
.where(notified: false)
.find_each do |invitee|
- create_notification!(
- invitee.user,
- self.post,
- predefined_attendance: predefined_attendance,
- )
+ create_notification!(invitee.user, post, predefined_attendance: predefined_attendance)
invitee.update!(notified: true)
end
end
def notify_missing_invitees!
- self.missing_users.each { |user| create_notification!(user, self.post) } if self.private?
+ missing_users.each { |user| create_notification!(user, post) } if private?
end
def create_notification!(user, post, predefined_attendance: false)
@@ -251,10 +231,10 @@ module DiscoursePostEvent
post_number: post.post_number,
data: {
user_id: user.id,
- topic_title: self.name || post.topic.title,
+ topic_title: name || post.topic.title,
display_username: post.user.username,
message: message,
- event_name: self.name,
+ event_name: name,
}.to_json,
}
@@ -262,9 +242,9 @@ module DiscoursePostEvent
end
def ongoing?
- return false if self.closed || self.expired? || self.starts_at.nil?
- finishes_at = self.ends_at || self.starts_at.end_of_day
- (self.starts_at..finishes_at).cover?(Time.now)
+ return false if closed || expired? || starts_at.nil?
+ finishes_at = ends_at || starts_at.end_of_day
+ (starts_at..finishes_at).cover?(Time.now)
end
def going_count
@@ -297,42 +277,39 @@ module DiscoursePostEvent
end
def most_likely_going(limit = SiteSetting.displayed_invitees_limit)
- going = self.invitees.order(%i[status user_id]).limit(limit)
+ going = invitees.order(%i[status user_id]).limit(limit)
- if self.private? && going.count < limit
+ if private? && going.count < limit
# invitees are only created when an attendance is set
# so we create a dummy invitee object with only what's needed for serializer
going =
going +
missing_users(going.pluck(:user_id))
.limit(limit - going.count)
- .map { |user| Invitee.new(user: user, post_id: self.id) }
+ .map { |user| Invitee.new(user: user, post_id: id) }
end
going
end
def publish_update!
- self.post.publish_message!("/discourse-post-event/#{self.post.topic_id}", id: self.id)
+ post.publish_message!("/discourse-post-event/#{post.topic_id}", id: id)
end
def fetch_users
- @fetched_users ||= Invitee.extract_uniq_usernames(self.raw_invitees)
+ @fetched_users ||= Invitee.extract_uniq_usernames(raw_invitees)
end
def enforce_private_invitees!
- self.invitees.where.not(user_id: fetch_users.select(:id)).delete_all
+ invitees.where.not(user_id: fetch_users.select(:id)).delete_all
end
def can_user_update_attendance?(user)
- return false if self.closed || self.expired?
- return true if self.public?
+ return false if closed || expired?
+ return true if public?
- self.private? &&
- (
- self.invitees.exists?(user_id: user.id) ||
- (user.groups.pluck(:name) & self.raw_invitees).any?
- )
+ private? &&
+ (invitees.exists?(user_id: user.id) || (user.groups.pluck(:name) & raw_invitees).any?)
end
def self.resolve_image_upload(image_param, post)
@@ -448,18 +425,18 @@ module DiscoursePostEvent
end
end
- def missing_users(excluded_ids = self.invitees.select(:user_id))
+ def missing_users(excluded_ids = invitees.select(:user_id))
users = User.real.activated.not_silenced.not_suspended.not_staged
- if self.raw_invitees.present?
+ if raw_invitees.present?
user_ids =
users
.joins(:groups)
- .where("groups.name" => self.raw_invitees)
+ .where("groups.name" => raw_invitees)
.where.not(id: excluded_ids)
.select(:id)
User.where(id: user_ids)
- elsif self.private?
+ elsif private?
User.none
else
users.where.not(id: excluded_ids)
@@ -467,27 +444,27 @@ module DiscoursePostEvent
end
def update_with_params!(params)
- case params[:status] ? params[:status].to_i : self.status
+ case params[:status] ? params[:status].to_i : status
when Event.statuses[:private]
if params.key?(:raw_invitees)
params = params.merge(raw_invitees: Array(params[:raw_invitees]) - [PUBLIC_GROUP])
else
- params = params.merge(raw_invitees: Array(self.raw_invitees) - [PUBLIC_GROUP])
+ params = params.merge(raw_invitees: Array(raw_invitees) - [PUBLIC_GROUP])
end
- self.update!(params)
- self.enforce_private_invitees!
+ update!(params)
+ enforce_private_invitees!
when Event.statuses[:public]
- self.update!(params.merge(raw_invitees: [PUBLIC_GROUP]))
+ update!(params.merge(raw_invitees: [PUBLIC_GROUP]))
when Event.statuses[:standalone]
- self.update!(params.merge(raw_invitees: []))
- self.invitees.destroy_all
+ update!(params.merge(raw_invitees: []))
+ invitees.destroy_all
end
- self.publish_update!
+ publish_update!
end
def chat_channel_sync
- if self.chat_enabled && self.chat_channel_id.blank? && post.last_editor_id.present?
+ if chat_enabled && chat_channel_id.blank? && post.last_editor_id.present?
DiscoursePostEvent::ChatChannelSync.sync(
self,
guardian: Guardian.new(User.find_by(id: post.last_editor_id)),
diff --git a/plugins/discourse-calendar/app/models/discourse_post_event/event_date.rb b/plugins/discourse-calendar/app/models/discourse_post_event/event_date.rb
index 49a76bea242..f3ad063b52d 100644
--- a/plugins/discourse-calendar/app/models/discourse_post_event/event_date.rb
+++ b/plugins/discourse-calendar/app/models/discourse_post_event/event_date.rb
@@ -22,12 +22,12 @@ module DiscoursePostEvent
after_commit :upsert_topic_custom_field, on: %i[create update]
def upsert_topic_custom_field
- if self.event.post && self.event.post.is_first_post?
+ if event.post && event.post.is_first_post?
TopicCustomField.upsert(
{
- topic_id: self.event.post.topic_id,
+ topic_id: event.post.topic_id,
name: TOPIC_POST_EVENT_STARTS_AT,
- value: self.starts_at,
+ value: starts_at,
created_at: Time.now,
updated_at: Time.now,
},
@@ -36,9 +36,9 @@ module DiscoursePostEvent
TopicCustomField.upsert(
{
- topic_id: self.event.post.topic_id,
+ topic_id: event.post.topic_id,
name: TOPIC_POST_EVENT_ENDS_AT,
- value: self.ends_at,
+ value: ends_at,
created_at: Time.now,
updated_at: Time.now,
},
@@ -47,9 +47,9 @@ module DiscoursePostEvent
TopicCustomField.upsert(
{
- topic_id: self.event.post.topic_id,
+ topic_id: event.post.topic_id,
name: TOPIC_POST_EVENT_ALL_DAY,
- value: self.event.all_day || false,
+ value: event.all_day || false,
created_at: Time.now,
updated_at: Time.now,
},
diff --git a/plugins/discourse-calendar/app/models/discourse_post_event/invitee.rb b/plugins/discourse-calendar/app/models/discourse_post_event/invitee.rb
index 921d939c5d5..20fd9c34998 100644
--- a/plugins/discourse-calendar/app/models/discourse_post_event/invitee.rb
+++ b/plugins/discourse-calendar/app/models/discourse_post_event/invitee.rb
@@ -71,16 +71,16 @@ module DiscoursePostEvent
end
def sync_chat_channel_members
- return if !self.event.chat_enabled?
- ChatChannelSync.sync(self.event)
+ return if !event.chat_enabled?
+ ChatChannelSync.sync(event)
end
def update_topic_tracking!
- topic_id = self.event.post.topic.id
- user_id = self.user.id
+ topic_id = event.post.topic.id
+ user_id = user.id
tracking = :regular
- case self.status
+ case status
when Invitee.statuses[:going]
tracking = :watching
when Invitee.statuses[:interested]
diff --git a/plugins/discourse-calendar/lib/discourse_post_event/post_extension.rb b/plugins/discourse-calendar/lib/discourse_post_event/post_extension.rb
index 3cba38c4e1a..6ae0be0676b 100644
--- a/plugins/discourse-calendar/lib/discourse_post_event/post_extension.rb
+++ b/plugins/discourse-calendar/lib/discourse_post_event/post_extension.rb
@@ -11,7 +11,7 @@ module DiscoursePostEvent
end
def valid_event
- return unless self.raw_changed?
+ return unless raw_changed?
validator = DiscoursePostEvent::EventValidator.new(self)
validator.validate_event
diff --git a/plugins/discourse-calendar/lib/time_sniffer.rb b/plugins/discourse-calendar/lib/time_sniffer.rb
index a61f2e13b35..1e186f6838b 100644
--- a/plugins/discourse-calendar/lib/time_sniffer.rb
+++ b/plugins/discourse-calendar/lib/time_sniffer.rb
@@ -38,10 +38,8 @@ class TimeSniffer
end
def to_time
- Time.use_zone(self.zone) do
- Time.zone.parse(
- "#{self.year}-#{self.month}-#{self.day} #{self.hours}:#{self.minutes}:#{self.seconds}",
- )
+ Time.use_zone(zone) do
+ Time.zone.parse("#{year}-#{month}-#{day} #{hours}:#{minutes}:#{seconds}")
end
end
@@ -51,13 +49,13 @@ class TimeSniffer
def to_hash
{
- year: self.year,
- month: self.month,
- day: self.day,
- hours: self.hours,
- minutes: self.minutes,
- seconds: self.seconds,
- zone: self.zone,
+ year: year,
+ month: month,
+ day: day,
+ hours: hours,
+ minutes: minutes,
+ seconds: seconds,
+ zone: zone,
}
end
@@ -195,11 +193,11 @@ class TimeSniffer
end
def input_from_offset
- self.input[self.offset..-1]
+ input[self.offset..-1]
end
def peek_time(relative_to)
- m = self.input_from_offset.match(TIME_REGEX)
+ m = input_from_offset.match(TIME_REGEX)
if m
parsed =
relative_to.with(
diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rb
index 3b0027adfb1..70fdb205b8b 100644
--- a/plugins/discourse-calendar/plugin.rb
+++ b/plugins/discourse-calendar/plugin.rb
@@ -444,18 +444,18 @@ after_initialize do
end
validate(:post, :validate_calendar) do |force = nil|
- return unless self.raw_changed? || force
+ return unless raw_changed? || force
validator = DiscourseCalendar::CalendarValidator.new(self)
validator.validate_calendar
end
validate(:post, :validate_event) do |force = nil|
- return unless self.raw_changed? || force
- return if self.is_first_post?
+ return unless raw_changed? || force
+ return if is_first_post?
# Skip if not a calendar topic
- return if !self.topic&.first_post&.custom_fields&.[](DiscourseCalendar::CALENDAR_CUSTOM_FIELD)
+ return if !topic&.first_post&.custom_fields&.[](DiscourseCalendar::CALENDAR_CUSTOM_FIELD)
validator = DiscourseCalendar::EventValidator.new(self)
validator.validate_event
diff --git a/plugins/discourse-chat-integration/app/models/channel.rb b/plugins/discourse-chat-integration/app/models/channel.rb
index be928ed2ae8..94dc5448276 100644
--- a/plugins/discourse-chat-integration/app/models/channel.rb
+++ b/plugins/discourse-chat-integration/app/models/channel.rb
@@ -24,7 +24,7 @@ class DiscourseChatIntegration::Channel < DiscourseChatIntegration::PluginModel
private
def init_data
- self.data = {} if self.data.nil?
+ self.data = {} if data.nil?
end
def destroy_rules
diff --git a/plugins/discourse-chat-integration/app/models/plugin_model.rb b/plugins/discourse-chat-integration/app/models/plugin_model.rb
index 06f52199541..73a0e06019c 100644
--- a/plugins/discourse-chat-integration/app/models/plugin_model.rb
+++ b/plugins/discourse-chat-integration/app/models/plugin_model.rb
@@ -3,7 +3,7 @@
class DiscourseChatIntegration::PluginModel < PluginStoreRow
PLUGIN_NAME = "discourse-chat-integration"
- default_scope { self.default_scope }
+ default_scope { default_scope }
after_initialize :init_plugin_model
before_save :set_key
@@ -11,7 +11,7 @@ class DiscourseChatIntegration::PluginModel < PluginStoreRow
def self.default_scope
where(type_name: "JSON").where(plugin_name: self::PLUGIN_NAME).where(
"key LIKE ?",
- "#{self.key_prefix}%",
+ "#{key_prefix}%",
)
end
@@ -31,11 +31,11 @@ class DiscourseChatIntegration::PluginModel < PluginStoreRow
end
def self.alloc_key
- DistributedMutex.synchronize("#{self::PLUGIN_NAME}_#{self.key_prefix}_id") do
- max_id = PluginStore.get(self::PLUGIN_NAME, "#{self.key_prefix}_id")
+ DistributedMutex.synchronize("#{self::PLUGIN_NAME}_#{key_prefix}_id") do
+ max_id = PluginStore.get(self::PLUGIN_NAME, "#{key_prefix}_id")
max_id = 1 unless max_id
- PluginStore.set(self::PLUGIN_NAME, "#{self.key_prefix}_id", max_id + 1)
- "#{self.key_prefix}#{max_id}"
+ PluginStore.set(self::PLUGIN_NAME, "#{key_prefix}_id", max_id + 1)
+ "#{key_prefix}#{max_id}"
end
end
end
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb
index 1284ef58fe5..6ccd3a9a820 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb
@@ -16,13 +16,12 @@ module DiscourseChatIntegration
end
def self.enabled_providers
- self.providers.select { |provider| self.is_enabled(provider) }
+ providers.select { |provider| is_enabled(provider) }
end
def self.disabled_providers
- self
- .providers
- .reject { |provider| self.is_enabled(provider) }
+ providers
+ .reject { |provider| is_enabled(provider) }
.sort_by do |provider|
score = defined?(provider::POPULARITY_SCORE) ? provider::POPULARITY_SCORE : 0
[-score, provider::PROVIDER_NAME]
@@ -30,15 +29,15 @@ module DiscourseChatIntegration
end
def self.provider_names
- self.providers.map! { |provider_klass| provider_klass::PROVIDER_NAME }
+ providers.map! { |provider_klass| provider_klass::PROVIDER_NAME }
end
def self.enabled_provider_names
- self.enabled_providers.map! { |provider_klass| provider_klass::PROVIDER_NAME }
+ enabled_providers.map! { |provider_klass| provider_klass::PROVIDER_NAME }
end
def self.get_by_name(name)
- self.providers.find { |provider_klass| provider_klass::PROVIDER_NAME == name }
+ providers.find { |provider_klass| provider_klass::PROVIDER_NAME == name }
end
def self.is_enabled(provider)
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb
index ad33f3554dd..b55eda1eebd 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb
@@ -84,7 +84,7 @@ module DiscourseChatIntegration::Provider::GroupmeProvider
def self.trigger_notification(post, channel, rule)
data_package = generate_groupme_message(post)
- self.send_via_webhook(data_package, channel)
+ send_via_webhook(data_package, channel)
end
def self.get_channel_by_name(name)
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb
index 1528b6687e4..1895c1967d1 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb
@@ -91,7 +91,7 @@ module DiscourseChatIntegration
channel_id = channel.data["identifier"]
message = mattermost_message(post, channel_id)
- self.send_via_webhook(message)
+ send_via_webhook(message)
end
def self.get_channel_by_name(name)
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb
index b93ccbc828c..09e188c853b 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb
@@ -81,7 +81,7 @@ module DiscourseChatIntegration::Provider::RocketchatProvider
channel_id = channel.data["identifier"]
message = rocketchat_message(post, channel_id)
- self.send_via_webhook(message)
+ send_via_webhook(message)
end
def self.get_channel_by_name(name)
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message.rb
index e0be63e34e1..50ad695705c 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message.rb
@@ -97,7 +97,7 @@ module DiscourseChatIntegration::Provider::SlackProvider
end
def processed_text_with_attachments
- self.text + attachments_string
+ text + attachments_string
end
def raw_text
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message_formatter.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message_formatter.rb
index a5737e979d9..4a510c88271 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message_formatter.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_message_formatter.rb
@@ -9,7 +9,7 @@ module DiscourseChatIntegration::Provider::SlackProvider
end
def self.format(html = "")
- me = self.new
+ me = new
parser = Nokogiri::HTML4::SAX::Parser.new(me, Encoding::UTF_8.to_s)
parser.parse(html)
me.excerpt
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb
index 7a11ff77c7e..1e4a4ec2f46 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb
@@ -365,9 +365,9 @@ module DiscourseChatIntegration::Provider::SlackProvider
message = slack_message(post, channel_id, filter)
if SiteSetting.chat_integration_slack_access_token.empty?
- self.send_via_webhook(message)
+ send_via_webhook(message)
else
- self.send_via_api(post, channel_id, message)
+ send_via_api(post, channel_id, message)
end
end
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb
index 54e6e77a480..f7a892fa796 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb
@@ -43,7 +43,7 @@ module DiscourseChatIntegration
)
if !setting_update_result.success?
- self.do_api_request("deleteWebhook", {})
+ do_api_request("deleteWebhook", {})
raise DiscourseChatIntegration::ProviderError.new(
info: {
error_key: "chat_integration.errors.setting_update_failed",
@@ -60,7 +60,7 @@ module DiscourseChatIntegration
response =
begin
- self.do_api_request("setWebhook", webhook_message, access_token: access_token)
+ do_api_request("setWebhook", webhook_message, access_token: access_token)
rescue JSON::ParserError => err
Rails.logger.error("Failed to parse telegram setWebhook response: #{err.message}")
{ "ok" => false, "description" => err.message }
@@ -78,7 +78,7 @@ module DiscourseChatIntegration
end
def self.sendMessage(message)
- self.do_api_request("sendMessage", message)
+ do_api_request("sendMessage", message)
end
def self.do_api_request(method_name, message, access_token: nil)
diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb
index d8df4a9f84b..fc71c4864ba 100644
--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb
+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb
@@ -55,7 +55,7 @@ module DiscourseChatIntegration
stream = channel.data["stream"]
subject = channel.data["subject"]
- message = self.generate_zulip_message(post, stream, subject)
+ message = generate_zulip_message(post, stream, subject)
response = send_message(message)
diff --git a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
index 313cf4829d9..dc2a6348289 100644
--- a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
+++ b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
@@ -36,7 +36,7 @@ module DiscourseDataExplorer
def cast_params(input_params, opts = {})
result = {}.with_indifferent_access
- self.params.each do |pobj|
+ params.each do |pobj|
result[pobj.identifier] = pobj.cast_to_ruby(input_params[pobj.identifier], opts)
end
result
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb
index 978376ac1b5..60ea39613ef 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/result_format_converter.rb
@@ -2,7 +2,7 @@
module DiscourseDataExplorer
class ResultFormatConverter
def self.convert(file_type, result, opts = {})
- self.new(result, opts).send("to_#{file_type}")
+ new(result, opts).send("to_#{file_type}")
end
def initialize(result, opts)
diff --git a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb
index 32cd7f5bbe8..0cbbf6d5758 100644
--- a/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb
+++ b/plugins/discourse-gamification/app/models/discourse_gamification/gamification_leaderboard.rb
@@ -49,7 +49,7 @@ module DiscourseGamification
end
def self.find_position_by(leaderboard_id:, for_user_id:, period: nil)
- self.scores_for(leaderboard_id, for_user_id: for_user_id, period: period).first
+ scores_for(leaderboard_id, for_user_id: for_user_id, period: period).first
end
def self.scores_for(leaderboard_id, page: 0, for_user_id: false, period: nil, user_limit: nil)
@@ -57,7 +57,7 @@ module DiscourseGamification
limit = user_limit || PAGE_SIZE
period = period || "all_time"
- leaderboard = self.find(leaderboard_id)
+ leaderboard = find(leaderboard_id)
return [] unless leaderboard
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/guardian_extension.rb b/plugins/discourse-gamification/lib/discourse_gamification/guardian_extension.rb
index 4b938e1d924..32754054fc4 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/guardian_extension.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/guardian_extension.rb
@@ -4,8 +4,8 @@ module DiscourseGamification
module GuardianExtension
def can_see_leaderboard?(leaderboard)
return true if leaderboard.visible_to_groups_ids.empty?
- return true if self.is_admin?
- return true if self.user && !(leaderboard.visible_to_groups_ids & self.user.group_ids).empty?
+ return true if is_admin?
+ return true if user && !(leaderboard.visible_to_groups_ids & user.group_ids).empty?
false
end
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb b/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb
index 0292e1fb3d0..20ed8f4fc21 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/leaderboard_cached_view.rb
@@ -68,19 +68,19 @@ module DiscourseGamification
end
def self.create_all
- GamificationLeaderboard.find_each { |leaderboard| self.new(leaderboard).create }
+ GamificationLeaderboard.find_each { |leaderboard| new(leaderboard).create }
end
def self.refresh_all
- GamificationLeaderboard.find_each { |leaderboard| self.new(leaderboard).refresh }
+ GamificationLeaderboard.find_each { |leaderboard| new(leaderboard).refresh }
end
def self.delete_all
- GamificationLeaderboard.find_each { |leaderboard| self.new(leaderboard).delete }
+ GamificationLeaderboard.find_each { |leaderboard| new(leaderboard).delete }
end
def self.purge_all_stale
- GamificationLeaderboard.find_each { |leaderboard| self.new(leaderboard).purge_stale }
+ GamificationLeaderboard.find_each { |leaderboard| new(leaderboard).purge_stale }
end
def self.update_all
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb b/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb
index 2312e6abeab..11c07e4577c 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/user_extension.rb
@@ -18,7 +18,7 @@ module DiscourseGamification
DiscourseGamification::GamificationLeaderboard.find_position_by(
leaderboard_id: default_leaderboard.id,
period: "all_time",
- for_user_id: self.id,
+ for_user_id: id,
)&.total_score || DEFAULT_SCORE
rescue DiscourseGamification::LeaderboardCachedView::NotReadyError
Jobs.enqueue(Jobs::GenerateLeaderboardPositions, leaderboard_id: default_leaderboard.id)
diff --git a/plugins/discourse-gamification/plugin.rb b/plugins/discourse-gamification/plugin.rb
index ff02b7cb120..5be26ea63b5 100644
--- a/plugins/discourse-gamification/plugin.rb
+++ b/plugins/discourse-gamification/plugin.rb
@@ -80,7 +80,7 @@ after_initialize do
add_to_serializer(
:admin_plugin,
:extras,
- include_condition: -> { self.name == "discourse-gamification" },
+ include_condition: -> { name == "discourse-gamification" },
) do
{
gamification_recalculate_scores_remaining:
@@ -89,7 +89,7 @@ after_initialize do
Group
.includes(:flair_upload)
.all
- .map { |group| BasicGroupSerializer.new(group, root: false, scope: self.scope).as_json },
+ .map { |group| BasicGroupSerializer.new(group, root: false, scope: scope).as_json },
gamification_leaderboards:
DiscourseGamification::GamificationLeaderboard
.order(updated_at: :desc)
diff --git a/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb b/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb
index 21c7cf0fea5..c4b15b0acc8 100755
--- a/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb
+++ b/plugins/discourse-gamification/spec/lib/scorables/shared_scorables_spec.rb
@@ -263,7 +263,7 @@ RSpec.describe DiscourseGamification::FlagCreated do
it_behaves_like "Scorable Type" do
before do
Fabricate.times(10, :reviewable, created_by: current_user) do
- after_create { self.update(status: 1) }
+ after_create { update(status: 1) }
end
end
@@ -309,7 +309,7 @@ RSpec.describe DiscourseGamification::UserInvited do
},
).to_return(status: 200, body: "", headers: {})
Fabricate.times(10, :invite, invited_by: current_user) do
- after_create { self.update(redemption_count: 1) }
+ after_create { update(redemption_count: 1) }
end
end
diff --git a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/actions.rb b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/actions.rb
index 7a4c28134f1..b193b18c4b1 100644
--- a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/actions.rb
+++ b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/actions.rb
@@ -9,7 +9,7 @@ module DiscourseNarrativeBot
end
def discobot_username
- self.discobot_user.username_lower
+ discobot_user.username_lower
end
private
@@ -26,12 +26,12 @@ module DiscourseNarrativeBot
skip_validations: true,
}
- new_post = PostCreator.create!(self.discobot_user, default_opts.merge(opts))
+ new_post = PostCreator.create!(discobot_user, default_opts.merge(opts))
reset_rate_limits(post) if new_post
new_post
else
PostCreator.create!(
- self.discobot_user,
+ discobot_user,
{ post_alert_options: default_post_alert_opts, raw: raw, skip_validations: true }.merge(
opts,
),
@@ -81,7 +81,7 @@ module DiscourseNarrativeBot
doc
.css(".mention")
.each do |mention|
- if User.normalize_username(mention.text) == "@#{self.discobot_username}"
+ if User.normalize_username(mention.text) == "@#{discobot_username}"
valid = true
break
end
diff --git a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/advanced_user_narrative.rb b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/advanced_user_narrative.rb
index 9f3481b4b03..8eeb50a0576 100644
--- a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/advanced_user_narrative.rb
+++ b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/advanced_user_narrative.rb
@@ -125,7 +125,7 @@ module DiscourseNarrativeBot
raw:
I18n.t(
"#{I18N_KEY}.edit.bot_created_post_raw",
- i18n_post_args(discobot_username: self.discobot_username),
+ i18n_post_args(discobot_username: discobot_username),
),
topic_id: data[:topic_id],
skip_bot: true,
@@ -145,7 +145,7 @@ module DiscourseNarrativeBot
raw:
I18n.t(
"#{I18N_KEY}.recover.deleted_post_raw",
- i18n_post_args(discobot_username: self.discobot_username),
+ i18n_post_args(discobot_username: discobot_username),
),
topic_id: data[:topic_id],
skip_bot: true,
@@ -159,8 +159,8 @@ module DiscourseNarrativeBot
if SiteSetting.delete_removed_posts_after < 1
opts[:delete_removed_posts_after] = 1
- result = PostActionCreator.notify_moderators(self.discobot_user, post)
- result.reviewable.perform(self.discobot_user, :ignore_and_do_nothing)
+ result = PostActionCreator.notify_moderators(discobot_user, post)
+ result.reviewable.perform(discobot_user, :ignore_and_do_nothing)
end
PostDestroyer.new(@user, post, opts).destroy
@@ -233,7 +233,7 @@ module DiscourseNarrativeBot
#{instance_eval(&@next_instructions)}
MD
- PostCreator.create!(self.discobot_user, raw: raw, topic_id: @topic_id)
+ PostCreator.create!(discobot_user, raw: raw, topic_id: @topic_id)
end
def missing_delete
@@ -257,7 +257,7 @@ module DiscourseNarrativeBot
#{instance_eval(&@next_instructions)}
MD
- PostCreator.create!(self.discobot_user, raw: raw, topic_id: @post.topic_id)
+ PostCreator.create!(discobot_user, raw: raw, topic_id: @post.topic_id)
end
def missing_recover
@@ -323,7 +323,7 @@ module DiscourseNarrativeBot
fake_delay
- post = PostCreator.create!(self.discobot_user, raw: raw, topic_id: @topic_id)
+ post = PostCreator.create!(discobot_user, raw: raw, topic_id: @topic_id)
enqueue_timeout_job(@user)
post
diff --git a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/base.rb b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/base.rb
index e611fa39dd8..062ea2fc66d 100644
--- a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/base.rb
+++ b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/base.rb
@@ -63,7 +63,7 @@ module DiscourseNarrativeBot
if @skip && @state != :end
skip_tutorial(next_state)
else
- self.send(action)
+ send(action)
end
if new_post
@@ -198,12 +198,12 @@ module DiscourseNarrativeBot
def clean_up_state(state)
clean_up_method = "clean_up_#{state}"
- self.send(clean_up_method) if self.class.private_method_defined?(clean_up_method)
+ send(clean_up_method) if self.class.private_method_defined?(clean_up_method)
end
def init_state(state)
init_method = "init_#{state}"
- self.send(init_method) if self.class.private_method_defined?(init_method)
+ send(init_method) if self.class.private_method_defined?(init_method)
end
end
end
diff --git a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb
index 9c17b31b347..18d2b703256 100644
--- a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb
+++ b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb
@@ -41,7 +41,7 @@ module DiscourseNarrativeBot
Proc.new do
I18n.t(
"#{I18N_KEY}.mention.instructions",
- discobot_username: self.discobot_username,
+ discobot_username: discobot_username,
base_uri: Discourse.base_path,
)
end,
@@ -178,7 +178,7 @@ module DiscourseNarrativeBot
MD
PostRevisor.new(post, topic).revise!(
- self.discobot_user,
+ discobot_user,
{ raw: raw },
skip_validations: true,
force_new_version: true,
@@ -234,7 +234,7 @@ module DiscourseNarrativeBot
def missing_bookmark
return unless valid_topic?(@post.topic_id)
- return if @post.user_id == self.discobot_user.id
+ return if @post.user_id == discobot_user.id
fake_delay
enqueue_timeout_job(@user)
@@ -246,7 +246,7 @@ module DiscourseNarrativeBot
def reply_to_bookmark
return unless valid_topic?(@post.topic_id)
- return unless @post.user_id == self.discobot_user.id
+ return unless @post.user_id == discobot_user.id
profile_page_url = url_helpers(:user_url, username: @user.username)
bookmark_url = "#{profile_page_url}/activity/bookmarks"
@@ -389,7 +389,7 @@ module DiscourseNarrativeBot
def missing_likes_like
return unless valid_topic?(@post.topic_id)
- return if @post.user_id == self.discobot_user.id
+ return if @post.user_id == discobot_user.id
fake_delay
enqueue_timeout_job(@user)
@@ -536,7 +536,7 @@ module DiscourseNarrativeBot
@post,
I18n.t(
"#{I18N_KEY}.mention.not_found",
- i18n_post_args(username: @user.username, discobot_username: self.discobot_username),
+ i18n_post_args(username: @user.username, discobot_username: discobot_username),
),
)
end
@@ -618,7 +618,7 @@ module DiscourseNarrativeBot
username: @user.username,
base_url: Discourse.base_url,
certificate: certificate,
- discobot_username: self.discobot_username,
+ discobot_username: discobot_username,
advanced_trigger: AdvancedUserNarrative.reset_trigger,
),
),
@@ -627,7 +627,7 @@ module DiscourseNarrativeBot
end
def like_post(post)
- PostActionCreator.like(self.discobot_user, post)
+ PostActionCreator.like(discobot_user, post)
end
def welcome_topic
diff --git a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/track_selector.rb b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/track_selector.rb
index 200ba3a45a4..2d1a6f79138 100644
--- a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/track_selector.rb
+++ b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/track_selector.rb
@@ -134,7 +134,7 @@ module DiscourseNarrativeBot
message =
I18n.t(
self.class.i18n_key("random_mention.reply"),
- discobot_username: self.discobot_username,
+ discobot_username: discobot_username,
help_trigger: self.class.help_trigger,
)
@@ -166,7 +166,7 @@ module DiscourseNarrativeBot
message =
I18n.t(
self.class.i18n_key("random_mention.tracks"),
- discobot_username: self.discobot_username,
+ discobot_username: discobot_username,
reset_trigger: self.class.reset_trigger,
tracks: [NewUserNarrative.reset_trigger, AdvancedUserNarrative.reset_trigger].join(", "),
)
@@ -174,7 +174,7 @@ module DiscourseNarrativeBot
message << "\n\n#{
I18n.t(
self.class.i18n_key("random_mention.bot_actions"),
- discobot_username: self.discobot_username,
+ discobot_username: discobot_username,
dice_trigger: self.class.dice_trigger,
quote_trigger: self.class.quote_trigger,
quote_sample: DiscourseNarrativeBot::QuoteGenerator.generate(@user),
@@ -225,7 +225,7 @@ module DiscourseNarrativeBot
def skip_track?
if @is_pm_to_bot
@post.raw.match(
- /((^@#{self.discobot_username} #{self.class.skip_trigger})|(^#{self.class.skip_trigger}$))/i,
+ /((^@#{discobot_username} #{self.class.skip_trigger})|(^#{self.class.skip_trigger}$))/i,
)
else
false
@@ -235,7 +235,7 @@ module DiscourseNarrativeBot
@@cooked_triggers = {}
def cook(trigger)
- @@cooked_triggers[trigger] ||= PrettyText.cook("@#{self.discobot_username}\\s+#{trigger}")
+ @@cooked_triggers[trigger] ||= PrettyText.cook("@#{discobot_username}\\s+#{trigger}")
end
def match_trigger?(trigger)
@@ -252,12 +252,12 @@ module DiscourseNarrativeBot
end
def like_user_post
- PostActionCreator.like(self.discobot_user, @post) if @post.raw.match(/thank/i)
+ PostActionCreator.like(discobot_user, @post) if @post.raw.match(/thank/i)
end
def bot_mentioned?
@bot_mentioned ||=
- PostAnalyzer.new(@post.raw, @post.topic_id).raw_mentions.include?(self.discobot_username)
+ PostAnalyzer.new(@post.raw, @post.topic_id).raw_mentions.include?(discobot_username)
end
def public_reply?
diff --git a/plugins/discourse-narrative-bot/plugin.rb b/plugins/discourse-narrative-bot/plugin.rb
index f23543ee96b..2028e462126 100644
--- a/plugins/discourse-narrative-bot/plugin.rb
+++ b/plugins/discourse-narrative-bot/plugin.rb
@@ -44,21 +44,21 @@ after_initialize do
list.include?(certificate_path) ? list : list + [certificate_path]
end
- self.add_model_callback(User, :after_destroy) { DiscourseNarrativeBot::Store.remove(self.id) }
+ add_model_callback(User, :after_destroy) { DiscourseNarrativeBot::Store.remove(id) }
- self.on(:user_created) do |user|
+ on(:user_created) do |user|
if SiteSetting.discourse_narrative_bot_welcome_post_delay == 0 && !user.staged
user.enqueue_bot_welcome_post
end
end
- self.on(:user_first_logged_in) do |user|
+ on(:user_first_logged_in) do |user|
user.enqueue_bot_welcome_post if SiteSetting.discourse_narrative_bot_welcome_post_delay > 0
end
- self.on(:user_unstaged) { |user| user.enqueue_bot_welcome_post }
+ on(:user_unstaged) { |user| user.enqueue_bot_welcome_post }
- self.add_to_class(:user, :enqueue_bot_welcome_post) do
+ add_to_class(:user, :enqueue_bot_welcome_post) do
return if SiteSetting.disable_discourse_narrative_bot_welcome_post
delay = SiteSetting.discourse_narrative_bot_welcome_post_delay
@@ -69,24 +69,23 @@ after_initialize do
Jobs.enqueue_in(
delay,
:narrative_init,
- user_id: self.id,
+ user_id: id,
klass: DiscourseNarrativeBot::NewUserNarrative.to_s,
)
end
when "welcome_message"
- Jobs.enqueue_in(delay, :send_default_welcome_message, user_id: self.id)
+ Jobs.enqueue_in(delay, :send_default_welcome_message, user_id: id)
end
end
- self.add_to_class(:user, :manually_disabled_discobot?) { user_option&.skip_new_user_tips }
+ add_to_class(:user, :manually_disabled_discobot?) { user_option&.skip_new_user_tips }
- self.add_to_class(:user, :enqueue_narrative_bot_job?) do
- SiteSetting.discourse_narrative_bot_enabled && self.human? && !self.anonymous? &&
- !self.staged &&
- !SiteSetting.discourse_narrative_bot_ignored_usernames.split("|").include?(self.username)
+ add_to_class(:user, :enqueue_narrative_bot_job?) do
+ SiteSetting.discourse_narrative_bot_enabled && human? && !anonymous? && !staged &&
+ !SiteSetting.discourse_narrative_bot_ignored_usernames.split("|").include?(username)
end
- self.on(:post_created) do |post, options|
+ on(:post_created) do |post, options|
user = post.user
if user&.enqueue_narrative_bot_job? && !options[:skip_bot]
@@ -94,13 +93,13 @@ after_initialize do
end
end
- self.on(:post_edited) do |post|
+ on(:post_edited) do |post|
if post.user&.enqueue_narrative_bot_job?
Jobs.enqueue(:bot_input, user_id: post.user.id, post_id: post.id, input: "edit")
end
end
- self.on(:post_destroyed) do |post, options, user|
+ on(:post_destroyed) do |post, options, user|
if user&.enqueue_narrative_bot_job? && !options[:skip_bot]
Jobs.enqueue(
:bot_input,
@@ -112,18 +111,18 @@ after_initialize do
end
end
- self.on(:post_recovered) do |post, _, user|
+ on(:post_recovered) do |post, _, user|
if user&.enqueue_narrative_bot_job?
Jobs.enqueue(:bot_input, user_id: user.id, post_id: post.id, input: "recover")
end
end
- self.add_model_callback(PostAction, :after_commit, on: :create) do
+ add_model_callback(PostAction, :after_commit, on: :create) do
if self.post && self.user.enqueue_narrative_bot_job?
input =
- case self.post_action_type_id
+ case post_action_type_id
when *PostActionType.flag_types.values
- self.post_action_type_id == PostActionType.types[:inappropriate] ? "flag" : "reply"
+ post_action_type_id == PostActionType.types[:inappropriate] ? "flag" : "reply"
when PostActionType.types[:like]
"like"
end
@@ -132,24 +131,23 @@ after_initialize do
end
end
- self.add_model_callback(Bookmark, :after_commit, on: :create) do
+ add_model_callback(Bookmark, :after_commit, on: :create) do
if self.user.enqueue_narrative_bot_job?
- if self.bookmarkable_type == "Post" || self.bookmarkable_type == "Topic"
- is_topic = self.bookmarkable_type == "Topic"
- first_post_id =
- Post.where(topic_id: self.bookmarkable_id, post_number: 1).pick(:id) if is_topic
+ if bookmarkable_type == "Post" || bookmarkable_type == "Topic"
+ is_topic = bookmarkable_type == "Topic"
+ first_post_id = Post.where(topic_id: bookmarkable_id, post_number: 1).pick(:id) if is_topic
Jobs.enqueue(
:bot_input,
- user_id: self.user_id,
- post_id: is_topic ? first_post_id : self.bookmarkable_id,
+ user_id: user_id,
+ post_id: is_topic ? first_post_id : bookmarkable_id,
input: "bookmark",
)
end
end
end
- self.on(:topic_notification_level_changed) do |_, user_id, topic_id|
+ on(:topic_notification_level_changed) do |_, user_id, topic_id|
user = User.find_by(id: user_id)
if user && user.enqueue_narrative_bot_job?
@@ -167,7 +165,7 @@ after_initialize do
)
- self.on(:system_message_sent) do |args|
+ on(:system_message_sent) do |args|
next if !SiteSetting.discourse_narrative_bot_enabled
next if args[:message_type] != "tl2_promotion_message"
@@ -194,7 +192,7 @@ after_initialize do
end
end
- self.on(:site_setting_changed) do |name, old_value, new_value|
+ on(:site_setting_changed) do |name, old_value, new_value|
next if name.to_s != "default_locale"
next if !SiteSetting.discourse_narrative_bot_enabled
diff --git a/plugins/discourse-patreon/plugin.rb b/plugins/discourse-patreon/plugin.rb
index 44c1233b0d0..76a24574214 100644
--- a/plugins/discourse-patreon/plugin.rb
+++ b/plugins/discourse-patreon/plugin.rb
@@ -74,7 +74,7 @@ after_initialize do
Patreon::Patron.update_local_user(user, patreon_id, true)
rescue => e
Rails.logger.warn(
- "Patreon group membership callback failed for new user #{self.id} with error: #{e}.\n\n #{e.backtrace.join("\n")}",
+ "Patreon group membership callback failed for new user #{id} with error: #{e}.\n\n #{e.backtrace.join("\n")}",
)
end
end
diff --git a/plugins/discourse-policy/app/models/policy_user.rb b/plugins/discourse-policy/app/models/policy_user.rb
index ec44e882466..e006de9b846 100644
--- a/plugins/discourse-policy/app/models/policy_user.rb
+++ b/plugins/discourse-policy/app/models/policy_user.rb
@@ -16,7 +16,7 @@ class PolicyUser < ActiveRecord::Base
.where(user: user)
.update_all(accepted_at: Time.zone.now)
- self.create!(
+ create!(
post_policy_id: post_policy.id,
user_id: user.id,
accepted_at: Time.zone.now,
@@ -32,7 +32,7 @@ class PolicyUser < ActiveRecord::Base
.where(user: user)
.update_all(revoked_at: Time.zone.now)
- self.create!(
+ create!(
post_policy_id: post_policy.id,
user_id: user.id,
revoked_at: Time.zone.now,
diff --git a/plugins/discourse-policy/plugin.rb b/plugins/discourse-policy/plugin.rb
index a384ab2f19f..c75fa397344 100644
--- a/plugins/discourse-policy/plugin.rb
+++ b/plugins/discourse-policy/plugin.rb
@@ -60,7 +60,7 @@ after_initialize do
TopicView.default_post_custom_fields << DiscoursePolicy::HAS_POLICY
validate(:post, :validate_policy) do
- return unless self.raw_changed?
+ return unless raw_changed?
validator = DiscoursePolicy::PostValidator.new(self)
return unless validator.validate_post
diff --git a/plugins/discourse-post-voting/app/models/post_voting_comment.rb b/plugins/discourse-post-voting/app/models/post_voting_comment.rb
index fd5c166f2f3..d58539c509f 100644
--- a/plugins/discourse-post-voting/app/models/post_voting_comment.rb
+++ b/plugins/discourse-post-voting/app/models/post_voting_comment.rb
@@ -46,7 +46,7 @@ class PostVotingComment < ActiveRecord::Base
private
def cook_raw
- self.cooked = self.class.cook(self.raw)
+ self.cooked = self.class.cook(raw)
self.cooked_version = COOKED_VERSION #TODO automatic rebaking once version is bumped
end
@@ -57,8 +57,7 @@ class PostVotingComment < ActiveRecord::Base
errors.add(:base, I18n.t("post_voting.comment.errors.post_voting_not_enabled"))
elsif post.reply_to_post_number.present?
errors.add(:base, I18n.t("post_voting.comment.errors.not_permitted"))
- elsif self.class.where(post_id: self.post_id).count >=
- SiteSetting.post_voting_comment_limit_per_post
+ elsif self.class.where(post_id: post_id).count >= SiteSetting.post_voting_comment_limit_per_post
errors.add(
:base,
I18n.t(
@@ -70,7 +69,7 @@ class PostVotingComment < ActiveRecord::Base
end
def ensure_last_editor_id
- self.last_editor_id ||= self.user_id
+ self.last_editor_id ||= user_id
end
end
diff --git a/plugins/discourse-post-voting/extensions/post_extension.rb b/plugins/discourse-post-voting/extensions/post_extension.rb
index ed135807aef..742028c2d8a 100644
--- a/plugins/discourse-post-voting/extensions/post_extension.rb
+++ b/plugins/discourse-post-voting/extensions/post_extension.rb
@@ -27,7 +27,7 @@ module PostVoting
end
def comments
- topic.posts.where(reply_to_post_number: self.post_number).order("post_number ASC")
+ topic.posts.where(reply_to_post_number: post_number).order("post_number ASC")
end
private
diff --git a/plugins/discourse-post-voting/extensions/topic_extension.rb b/plugins/discourse-post-voting/extensions/topic_extension.rb
index fdb9b06bf50..d7dacbf4691 100644
--- a/plugins/discourse-post-voting/extensions/topic_extension.rb
+++ b/plugins/discourse-post-voting/extensions/topic_extension.rb
@@ -34,7 +34,7 @@ module PostVoting
def comments
@comments ||=
- PostVotingComment.joins(:post).where("posts.topic_id = ?", self.id).order(created_at: :asc)
+ PostVotingComment.joins(:post).where("posts.topic_id = ?", id).order(created_at: :asc)
end
def last_commented_on
@@ -56,8 +56,7 @@ module PostVoting
end
def is_post_voting?
- @is_post_voting ||=
- SiteSetting.post_voting_enabled && self.subtype == Topic::POST_VOTING_SUBTYPE
+ @is_post_voting ||= SiteSetting.post_voting_enabled && subtype == Topic::POST_VOTING_SUBTYPE
end
# class methods
@@ -77,21 +76,18 @@ module PostVoting
private
def ensure_no_post_voting_subtype
- if will_save_change_to_subtype? && self.subtype == Topic::POST_VOTING_SUBTYPE
- self.errors.add(
- :base,
- I18n.t("topic.post_voting.errors.cannot_change_to_post_voting_subtype"),
- )
+ if will_save_change_to_subtype? && subtype == Topic::POST_VOTING_SUBTYPE
+ errors.add(:base, I18n.t("topic.post_voting.errors.cannot_change_to_post_voting_subtype"))
end
end
def ensure_regular_topic
- return if self.subtype != Topic::POST_VOTING_SUBTYPE
+ return if subtype != Topic::POST_VOTING_SUBTYPE
if !SiteSetting.post_voting_enabled
- self.errors.add(:base, I18n.t("topic.post_voting.errors.post_voting_not_enabled"))
- elsif self.archetype != Archetype.default
- self.errors.add(:base, I18n.t("topic.post_voting.errors.subtype_not_allowed"))
+ errors.add(:base, I18n.t("topic.post_voting.errors.post_voting_not_enabled"))
+ elsif archetype != Archetype.default
+ errors.add(:base, I18n.t("topic.post_voting.errors.subtype_not_allowed"))
end
end
end
diff --git a/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb b/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb
index 2a990ca7f6c..39be3e8a933 100644
--- a/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb
+++ b/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb
@@ -3,10 +3,10 @@
module PostVoting
module GuardianExtension
def can_edit_comment?(comment)
- return false if !self.user
- return true if comment.user_id == self.user.id
- return true if self.is_admin?
- return true if self.is_moderator?
+ return false if !user
+ return true if comment.user_id == user.id
+ return true if is_admin?
+ return true if is_moderator?
false
end
@@ -15,10 +15,10 @@ module PostVoting
end
def can_flag_post_voting_comments?
- return false if self.user.silenced?
- return true if self.user.staff?
+ return false if user.silenced?
+ return true if user.staff?
- self.user.in_any_groups?(SiteSetting.flag_posts_voting_comments_allowed_groups_map)
+ user.in_any_groups?(SiteSetting.flag_posts_voting_comments_allowed_groups_map)
end
def can_flag_post_voting_comment?(comment)
diff --git a/plugins/discourse-post-voting/plugin.rb b/plugins/discourse-post-voting/plugin.rb
index bd6eaf9951f..56ad0675a8e 100644
--- a/plugins/discourse-post-voting/plugin.rb
+++ b/plugins/discourse-post-voting/plugin.rb
@@ -71,7 +71,7 @@ after_initialize do
# TODO: Performance of the query degrades as the number of posts a user has voted
# on increases. We should probably keep a counter cache in the user's
# custom fields.
- add_to_class(:user, :vote_count) { Post.where(user_id: self.id).sum(:qa_vote_count) }
+ add_to_class(:user, :vote_count) { Post.where(user_id: id).sum(:qa_vote_count) }
add_to_serializer(:user_card, :vote_count) { object.vote_count }
@@ -230,9 +230,7 @@ after_initialize do
register_preloaded_category_custom_fields(PostVoting::CREATE_AS_POST_VOTING_DEFAULT)
add_to_class(:category, :create_as_post_voting_default) do
- ActiveModel::Type::Boolean.new.cast(
- self.custom_fields[PostVoting::CREATE_AS_POST_VOTING_DEFAULT],
- )
+ ActiveModel::Type::Boolean.new.cast(custom_fields[PostVoting::CREATE_AS_POST_VOTING_DEFAULT])
end
add_to_serializer(:basic_category, :create_as_post_voting_default) do
object.create_as_post_voting_default
@@ -248,7 +246,7 @@ after_initialize do
add_to_class(:category, :only_post_voting_in_this_category) do
ActiveModel::Type::Boolean.new.cast(
- self.custom_fields[PostVoting::ONLY_POST_VOTING_IN_THIS_CATEGORY],
+ custom_fields[PostVoting::ONLY_POST_VOTING_IN_THIS_CATEGORY],
)
end
add_to_serializer(:basic_category, :only_post_voting_in_this_category) do
@@ -256,8 +254,8 @@ after_initialize do
end
add_model_callback(:post, :before_create) do
- if SiteSetting.post_voting_enabled && self.is_post_voting_topic? && self.via_email &&
- self.reply_to_post_number == 1
+ if SiteSetting.post_voting_enabled && is_post_voting_topic? && via_email &&
+ reply_to_post_number == 1
self.reply_to_post_number = nil
end
end
diff --git a/plugins/discourse-reactions/app/models/discourse_reactions/reaction.rb b/plugins/discourse-reactions/app/models/discourse_reactions/reaction.rb
index 2d41a52a54a..afd1c13f5d3 100644
--- a/plugins/discourse-reactions/app/models/discourse_reactions/reaction.rb
+++ b/plugins/discourse-reactions/app/models/discourse_reactions/reaction.rb
@@ -10,8 +10,8 @@ module DiscourseReactions
has_many :users, through: :reaction_users
belongs_to :post
- scope :positive, -> { where(reaction_value: self.positive_reactions) }
- scope :negative_or_neutral, -> { where(reaction_value: self.negative_or_neutral_reactions) }
+ scope :positive, -> { where(reaction_value: positive_reactions) }
+ scope :negative_or_neutral, -> { where(reaction_value: negative_or_neutral_reactions) }
scope :by_user,
->(user) do
joins(:reaction_users).where(discourse_reactions_reaction_users: { user_id: user.id })
diff --git a/plugins/discourse-reactions/app/models/discourse_reactions/reaction_user.rb b/plugins/discourse-reactions/app/models/discourse_reactions/reaction_user.rb
index 251edef2a97..a35b65517b0 100644
--- a/plugins/discourse-reactions/app/models/discourse_reactions/reaction_user.rb
+++ b/plugins/discourse-reactions/app/models/discourse_reactions/reaction_user.rb
@@ -32,14 +32,14 @@ module DiscourseReactions
delegate :name, to: :user, allow_nil: true
def can_undo?
- self.created_at > SiteSetting.post_undo_action_window_mins.minutes.ago
+ created_at > SiteSetting.post_undo_action_window_mins.minutes.ago
end
def post_action_like
@post_action_like ||=
PostAction.find_by(
- user_id: self.user_id,
- post_id: self.post_id,
+ user_id: user_id,
+ post_id: post_id,
post_action_type_id: PostActionType::LIKE_POST_ACTION_ID,
)
end
diff --git a/plugins/discourse-reactions/app/services/discourse_reactions/reaction_like_synchronizer.rb b/plugins/discourse-reactions/app/services/discourse_reactions/reaction_like_synchronizer.rb
index 4bd6ea5ee13..e23e4510906 100644
--- a/plugins/discourse-reactions/app/services/discourse_reactions/reaction_like_synchronizer.rb
+++ b/plugins/discourse-reactions/app/services/discourse_reactions/reaction_like_synchronizer.rb
@@ -3,7 +3,7 @@
module DiscourseReactions
class ReactionLikeSynchronizer
def self.sync!
- self.new.sync!
+ new.sync!
end
def initialize
diff --git a/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb b/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb
index 499b3b28413..bbdbbc47784 100644
--- a/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb
+++ b/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb
@@ -10,6 +10,6 @@ module DiscourseReactions::PostExtension
end
def emoji_reactions
- @emoji_reactions ||= self.reactions.select { |reaction| Emoji.exists?(reaction.reaction_value) }
+ @emoji_reactions ||= reactions.select { |reaction| Emoji.exists?(reaction.reaction_value) }
end
end
diff --git a/plugins/discourse-reactions/plugin.rb b/plugins/discourse-reactions/plugin.rb
index ec4155d1937..90a66cb2c63 100644
--- a/plugins/discourse-reactions/plugin.rb
+++ b/plugins/discourse-reactions/plugin.rb
@@ -479,7 +479,7 @@ after_initialize do
add_to_serializer(:topic_view, :valid_reactions) { DiscourseReactions::Reaction.valid_reactions }
add_model_callback(User, :before_destroy) do
- DiscourseReactions::ReactionUser.where(user_id: self.id).delete_all
+ DiscourseReactions::ReactionUser.where(user_id: id).delete_all
end
add_report("reactions") do |report|
diff --git a/plugins/discourse-rewind/plugin.rb b/plugins/discourse-rewind/plugin.rb
index abe95539940..30bf4be9e7d 100644
--- a/plugins/discourse-rewind/plugin.rb
+++ b/plugins/discourse-rewind/plugin.rb
@@ -39,7 +39,7 @@ after_initialize do
UserOption.ignored_columns += %i[discourse_rewind_disabled]
add_to_class(:user, :discourse_rewind_and_profile_public?) do
- self.user_option.discourse_rewind_share_publicly && !self.user_option.hide_profile
+ user_option.discourse_rewind_share_publicly && !user_option.hide_profile
end
# add_to_serializer(:current_user) / add_to_serializer(:current_user_option)
diff --git a/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb b/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb
index 31c7f610aa7..5dbacbd7b11 100644
--- a/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb
@@ -21,7 +21,7 @@ module DiscourseSolved::TopicExtension
return unless answer_post = solved.answer_post
answer_post_user = answer_post.user || Discourse.system_user
- accepter = solved.accepter || self.user || Discourse.system_user
+ accepter = solved.accepter || user || Discourse.system_user
excerpt = SiteSetting.solved_quote_length > 0 ? answer_post.cooked : nil
diff --git a/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb b/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb
index 9e3c5350848..60491fd2a7f 100644
--- a/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb
+++ b/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb
@@ -8,11 +8,11 @@ module DiscourseTemplates::TopicExtension
end
def template_item_usage_count
- self.template_item_usage&.usage_count.to_i
+ template_item_usage&.usage_count.to_i
end
def increment_template_item_usage_count!
- DB.exec(<<~SQL, topic_id: self.id)
+ DB.exec(<<~SQL, topic_id: id)
INSERT INTO discourse_templates_usage_count AS uc
(topic_id, usage_count, created_at, updated_at)
VALUES
diff --git a/plugins/discourse-templates/lib/discourse_templates/user_extension.rb b/plugins/discourse-templates/lib/discourse_templates/user_extension.rb
index 32b65c7dfbc..b74f7badec1 100644
--- a/plugins/discourse-templates/lib/discourse_templates/user_extension.rb
+++ b/plugins/discourse-templates/lib/discourse_templates/user_extension.rb
@@ -34,7 +34,7 @@ module DiscourseTemplates::UserExtension
return true if group_id == Group::AUTO_GROUPS[:everyone]
# the user can use templates if belongs to at least one of the allowed groups
- GroupUser.exists?(group_id: group_id, user_id: self.id)
+ GroupUser.exists?(group_id: group_id, user_id: id)
end
end
end
diff --git a/plugins/discourse-topic-voting/app/models/discourse_topic_voting/category_setting.rb b/plugins/discourse-topic-voting/app/models/discourse_topic_voting/category_setting.rb
index 96fc73f715e..ecc76482d52 100644
--- a/plugins/discourse-topic-voting/app/models/discourse_topic_voting/category_setting.rb
+++ b/plugins/discourse-topic-voting/app/models/discourse_topic_voting/category_setting.rb
@@ -11,7 +11,7 @@ module DiscourseTopicVoting
after_save :reset_voting_cache
def unarchive_votes
- DB.exec(<<~SQL, { category_id: self.category_id })
+ DB.exec(<<~SQL, { category_id: category_id })
UPDATE topic_voting_votes
SET archive=false
FROM topics
@@ -24,7 +24,7 @@ module DiscourseTopicVoting
end
def archive_votes
- DB.exec(<<~SQL, { category_id: self.category_id })
+ DB.exec(<<~SQL, { category_id: category_id })
UPDATE topic_voting_votes
SET archive=true
FROM topics
diff --git a/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_extension.rb b/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_extension.rb
index f8e7007866f..ab07b2d3f71 100644
--- a/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_extension.rb
+++ b/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_extension.rb
@@ -20,21 +20,21 @@ module DiscourseTopicVoting
end
def vote_count
- self.topic_vote_count&.votes_count.to_i
+ topic_vote_count&.votes_count.to_i
end
def user_voted?(user)
- if self.current_user_voted
- self.current_user_voted == 1
+ if current_user_voted
+ current_user_voted == 1
else
votes.map(&:user_id).include?(user.id)
end
end
def update_vote_count
- count = self.votes.count
+ count = votes.count
- DB.exec(<<~SQL, topic_id: self.id, votes_count: count)
+ DB.exec(<<~SQL, topic_id: id, votes_count: count)
INSERT INTO topic_voting_topic_vote_count
(topic_id, votes_count, created_at, updated_at)
VALUES
diff --git a/plugins/discourse-topic-voting/lib/discourse_topic_voting/user_extension.rb b/plugins/discourse-topic-voting/lib/discourse_topic_voting/user_extension.rb
index c7727cfc9a4..00f601a0f4f 100644
--- a/plugins/discourse-topic-voting/lib/discourse_topic_voting/user_extension.rb
+++ b/plugins/discourse-topic-voting/lib/discourse_topic_voting/user_extension.rb
@@ -16,11 +16,11 @@ module DiscourseTopicVoting
end
def topics_with_vote
- self.votes.where(archive: false)
+ votes.where(archive: false)
end
def topics_with_archived_vote
- self.votes.where(archive: true)
+ votes.where(archive: true)
end
def can_vote?
@@ -34,7 +34,7 @@ module DiscourseTopicVoting
def vote_limit
return nil unless SiteSetting.topic_voting_enable_vote_limits
- SiteSetting.public_send("topic_voting_tl#{self.trust_level}_vote_limit")
+ SiteSetting.public_send("topic_voting_tl#{trust_level}_vote_limit")
end
def votes_left
diff --git a/plugins/discourse-user-notes/plugin.rb b/plugins/discourse-user-notes/plugin.rb
index 889533dadfd..139879ae733 100644
--- a/plugins/discourse-user-notes/plugin.rb
+++ b/plugins/discourse-user-notes/plugin.rb
@@ -38,9 +38,9 @@ after_initialize do
end
add_model_callback(UserWarning, :after_commit, on: :create) do
- user = User.find_by_id(self.user_id)
- created_by_user = User.find_by_id(self.created_by_id)
- warning_topic = Topic.find_by_id(self.topic_id)
+ user = User.find_by_id(user_id)
+ created_by_user = User.find_by_id(created_by_id)
+ warning_topic = Topic.find_by_id(topic_id)
raw_note =
I18n.with_locale(SiteSetting.default_locale) do
I18n.t(
@@ -49,7 +49,7 @@ after_initialize do
warning_link: "[#{warning_topic.title}](#{warning_topic.url})",
)
end
- DiscourseUserNotes.add_note(user, raw_note, Discourse::SYSTEM_USER_ID, topic_id: self.topic_id)
+ DiscourseUserNotes.add_note(user, raw_note, Discourse::SYSTEM_USER_ID, topic_id: topic_id)
# Fire event after note is created for other plugins to hook into
DiscourseEvent.trigger(:user_warning_created, self)
diff --git a/plugins/poll/lib/poll.rb b/plugins/poll/lib/poll.rb
index 09abd0fa91d..b0dfed87a65 100644
--- a/plugins/poll/lib/poll.rb
+++ b/plugins/poll/lib/poll.rb
@@ -42,7 +42,7 @@ class DiscoursePoll::Poll
end
end
- self.validate_votes!(poll, new_option_ids)
+ validate_votes!(poll, new_option_ids)
old_option_ids =
poll
diff --git a/plugins/poll/lib/post_extension.rb b/plugins/poll/lib/post_extension.rb
index 8ff5745052c..4ae89821b04 100644
--- a/plugins/poll/lib/post_extension.rb
+++ b/plugins/poll/lib/post_extension.rb
@@ -10,7 +10,7 @@ module DiscoursePoll
has_many :polls, dependent: :destroy
after_save do
- polls = self.extracted_polls
+ polls = extracted_polls
self.extracted_polls = nil
next if polls.blank? || !polls.is_a?(Hash)
post = self
diff --git a/plugins/poll/plugin.rb b/plugins/poll/plugin.rb
index a2859fc4947..542b838992c 100644
--- a/plugins/poll/plugin.rb
+++ b/plugins/poll/plugin.rb
@@ -49,11 +49,11 @@ after_initialize do
end
validate(:post, :validate_polls) do |force = nil|
- return unless self.raw_changed? || force
+ return unless raw_changed? || force
validator = DiscoursePoll::PollsValidator.new(self)
return unless (polls = validator.validate_polls)
- return if polls.blank? && self.id.blank?
+ return if polls.blank? && id.blank?
if polls.present?
validator = DiscoursePoll::PostValidator.new(self)
@@ -61,7 +61,7 @@ after_initialize do
end
# are we updating a post?
- if self.id.present?
+ if id.present?
return if polls.blank? && ::Poll.where(post: self).empty?
DiscoursePoll::PollsUpdater.update(self, polls)
@@ -221,7 +221,7 @@ after_initialize do
end
add_to_serializer(:post, :polls, include_condition: -> { preloaded_polls.present? }) do
- preloaded_polls.map { |p| PollSerializer.new(p, root: false, scope: self.scope) }
+ preloaded_polls.map { |p| PollSerializer.new(p, root: false, scope: scope) }
end
add_to_serializer(
diff --git a/script/import_scripts/smf2.rb b/script/import_scripts/smf2.rb
index a3081a96512..35090d7812e 100644
--- a/script/import_scripts/smf2.rb
+++ b/script/import_scripts/smf2.rb
@@ -714,7 +714,7 @@ class ImportScripts::Smf2 < ImportScripts::Base
end
raise Error, "too many arguments" if args.length > 1
self.smfroot = args.first
- read_smf_settings if self.smfroot
+ read_smf_settings if smfroot
self.host ||= "localhost"
self.username ||= Etc.getlogin
@@ -747,7 +747,7 @@ class ImportScripts::Smf2 < ImportScripts::Base
end
def read_smf_settings
- settings = File.join(self.smfroot, "Settings.php")
+ settings = File.join(smfroot, "Settings.php")
File
.readlines(settings)
.each do |line|
diff --git a/script/memstats.rb b/script/memstats.rb
index 4ca1f531dc7..b8af38fb0d8 100755
--- a/script/memstats.rb
+++ b/script/memstats.rb
@@ -48,7 +48,7 @@ class Mapping
attr_accessor :pss
def initialize(lines)
- FIELDS.each { |field| self.public_send("#{field}=", 0) }
+ FIELDS.each { |field| public_send("#{field}=", 0) }
parse_first_line(lines.shift)
lines.each { |l| parse_field_line(l) }
@@ -69,7 +69,7 @@ class Mapping
field = parts[0].downcase.sub(":", "")
if respond_to? "#{field}="
value = Float(parts[1]).to_i
- self.public_send("#{field}=", value)
+ public_send("#{field}=", value)
end
end
end
diff --git a/script/thread_detective.rb b/script/thread_detective.rb
index d72fd5e8ae2..e4af7803beb 100644
--- a/script/thread_detective.rb
+++ b/script/thread_detective.rb
@@ -10,7 +10,7 @@ class ThreadDetective
end
def self.start(max_threads)
- @thread ||= Thread.new { self.new.monitor(max_threads) }
+ @thread ||= Thread.new { new.monitor(max_threads) }
@trace = TracePoint.new(:thread_begin) { |tp| Thread.current.origin = Thread.current.inspect }
@trace.enable
diff --git a/spec/lib/site_setting_extension_spec.rb b/spec/lib/site_setting_extension_spec.rb
index bdd15a8da27..a384a74353b 100644
--- a/spec/lib/site_setting_extension_spec.rb
+++ b/spec/lib/site_setting_extension_spec.rb
@@ -414,7 +414,7 @@ RSpec.describe SiteSettingExtension do
describe "enum setting" do
class TestEnumClass
def self.valid_value?(v)
- self.values.include?(v)
+ values.include?(v)
end
def self.values
diff --git a/spec/lib/site_settings/type_supervisor_spec.rb b/spec/lib/site_settings/type_supervisor_spec.rb
index 7a461bc78ab..59c57f42809 100644
--- a/spec/lib/site_settings/type_supervisor_spec.rb
+++ b/spec/lib/site_settings/type_supervisor_spec.rb
@@ -140,7 +140,7 @@ RSpec.describe SiteSettings::TypeSupervisor do
context "with different data types" do
class TestEnumClass
def self.valid_value?(v)
- self.values.include?(v)
+ values.include?(v)
end
def self.values
@@ -453,7 +453,7 @@ RSpec.describe SiteSettings::TypeSupervisor do
describe ".type_hash" do
class TestEnumClass2
def self.valid_value?(v)
- self.values.include?(v)
+ values.include?(v)
end
def self.values
diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rb
index 6e3207d4743..b21485a6ff5 100644
--- a/spec/lib/topics_filter_spec.rb
+++ b/spec/lib/topics_filter_spec.rb
@@ -480,7 +480,7 @@ RSpec.describe TopicsFilter do
.new(guardian: Guardian.new(user))
.filter_from_query_string("in:#{notification_level}")
.pluck(:id),
- ).to contain_exactly(self.public_send("user_#{notification_level}_topic").id)
+ ).to contain_exactly(public_send("user_#{notification_level}_topic").id)
end
end
end
diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb
index f04e3898626..413a13623c7 100644
--- a/spec/rails_helper.rb
+++ b/spec/rails_helper.rb
@@ -781,7 +781,7 @@ RSpec.configure do |config|
class << self
def using_session_with_localhost_resolution(name, &block)
attempts = 0
- self._using_session(name, &block)
+ _using_session(name, &block)
rescue Socket::ResolutionError
puts "Socket::ResolutionError error encountered... Current thread count: #{Thread.list.size}"
attempts += 1
diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rb
index a902dce8692..82bb17e38e2 100644
--- a/spec/requests/posts_controller_spec.rb
+++ b/spec/requests/posts_controller_spec.rb
@@ -75,7 +75,7 @@ end
RSpec.shared_examples "action requires login" do |method, url, params = {}|
it "raises an exception when not logged in" do
- self.public_send(method, url, **params)
+ public_send(method, url, **params)
expect(response.status).to eq(403)
end
end
diff --git a/spec/support/fake_s3.rb b/spec/support/fake_s3.rb
index fcc88a003ee..d336f5805fe 100644
--- a/spec/support/fake_s3.rb
+++ b/spec/support/fake_s3.rb
@@ -6,7 +6,7 @@ class FakeS3
attr_reader :s3_client
def self.create
- s3 = self.new
+ s3 = new
s3.stub_bucket(SiteSetting.s3_upload_bucket) if SiteSetting.s3_upload_bucket.present?
if SiteSetting.s3_backup_bucket.present?
s3.stub_bucket(
diff --git a/spec/support/topic_guardian_can_see_consistency_check.rb b/spec/support/topic_guardian_can_see_consistency_check.rb
index 32f241a15a2..ee9274a4715 100644
--- a/spec/support/topic_guardian_can_see_consistency_check.rb
+++ b/spec/support/topic_guardian_can_see_consistency_check.rb
@@ -28,8 +28,7 @@ module TopicGuardianCanSeeConsistencyCheck
result = super
if self.class.run_topic_can_see_consistency_check?
- new_result =
- self.can_see_topic_ids(topic_ids: [topic&.id], hide_deleted: hide_deleted).present?
+ new_result = can_see_topic_ids(topic_ids: [topic&.id], hide_deleted: hide_deleted).present?
if result != new_result
raise "result between TopicGuardian#can_see_topic? (#{result}) and TopicGuardian#can_see_topic_ids (#{new_result}) has drifted and returned different results for the same input"
diff --git a/spec/system/page_objects/components/form_kit.rb b/spec/system/page_objects/components/form_kit.rb
index ec56100dead..aa420c6e0fa 100644
--- a/spec/system/page_objects/components/form_kit.rb
+++ b/spec/system/page_objects/components/form_kit.rb
@@ -91,7 +91,7 @@ module PageObjects
raise "'unchecked?' is only supported for control type: #{control_type}"
end
- expect(self.value).to eq(false)
+ expect(value).to eq(false)
end
def checked?
@@ -99,11 +99,11 @@ module PageObjects
raise "'checked?' is only supported for control type: #{control_type}"
end
- expect(self.value).to eq(true)
+ expect(value).to eq(true)
end
def has_value?(expected_value)
- expect(self.value).to eq(expected_value)
+ expect(value).to eq(expected_value)
end
def has_errors?(*messages)