Add rubocop to our build. (#5004)

This commit is contained in:
Guo Xiang Tan 2017-07-28 10:20:09 +09:00 committed by GitHub
parent ff4e295c4f
commit 5012d46cbd
871 changed files with 5480 additions and 6056 deletions

View File

@ -1,14 +1,104 @@
AllCops:
TargetRubyVersion: 2.3
TargetRubyVersion: 2.4
DisabledByDefault: true
Metrics/LineLength:
Max: 120
# Prefer &&/|| over and/or.
Style/AndOr:
Enabled: true
Metrics/MethodLength:
# Do not use braces for hash literals when they are the last argument of a
# method call.
Style/BracesAroundHashParameters:
Enabled: true
# Align `when` with `case`.
Layout/CaseIndentation:
Enabled: true
# Align comments with method definitions.
Layout/CommentIndentation:
Enabled: true
# No extra empty lines.
Layout/EmptyLines:
Enabled: true
# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }.
Style/HashSyntax:
Enabled: true
# Two spaces, no tabs (for indentation).
Layout/IndentationWidth:
Enabled: true
Layout/SpaceAfterColon:
Enabled: true
Layout/SpaceAfterComma:
Enabled: true
Layout/SpaceAroundEqualsInParameterDefault:
Enabled: true
Layout/SpaceAroundKeyword:
Enabled: true
Layout/SpaceAroundOperators:
Enabled: true
Layout/SpaceBeforeFirstArg:
Enabled: true
# Defining a method with parameters needs parentheses.
Style/MethodDefParentheses:
Enabled: true
# Use `foo {}` not `foo{}`.
Layout/SpaceBeforeBlockBraces:
Enabled: true
# Use `foo { bar }` not `foo {bar}`.
Layout/SpaceInsideBlockBraces:
Enabled: true
# Use `{ a: 1 }` not `{a:1}`.
Layout/SpaceInsideHashLiteralBraces:
Enabled: true
Layout/SpaceInsideParens:
Enabled: true
# Detect hard tabs, no hard tabs.
Layout/Tab:
Enabled: true
# Blank lines should not have any spaces.
Layout/TrailingBlankLines:
Enabled: true
# No trailing whitespace.
Layout/TrailingWhitespace:
Enabled: true
Lint/BlockAlignment:
Enabled: true
# Align `end` with the matching keyword or starting expression except for
# assignments, where it should be aligned with the LHS.
Lint/EndAlignment:
Enabled: true
EnforcedStyleAlignWith: variable
# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg.
Lint/RequireParentheses:
Enabled: true
Layout/MultilineMethodCallIndentation:
Enabled: true
EnforcedStyle: indented
Layout/AlignHash:
Enabled: true
Bundler/OrderedGems:
Enabled: false
Style/Documentation:
Enabled: false
Style/FrozenStringLiteralComment:
Enabled: False

View File

@ -36,7 +36,7 @@ cache:
- vendor/bundle
before_install:
- gem install bundler
- gem install bundler rubocop
- git clone --depth=1 https://github.com/discourse/discourse-backup-uploads-to-s3.git plugins/discourse-backup-uploads-to-s3
- git clone --depth=1 https://github.com/discourse/discourse-spoiler-alert.git plugins/discourse-spoiler-alert
- git clone --depth=1 https://github.com/discourse/discourse-cakeday.git plugins/discourse-cakeday
@ -48,6 +48,7 @@ before_install:
- eslint --ext .es6 test/javascripts
- eslint --ext .es6 plugins/**/assets/javascripts
- eslint test/javascripts
- rubocop --parallel
before_script:
- bundle exec rake db:create db:migrate

View File

@ -189,7 +189,6 @@ gem 'logster'
gem 'sassc', require: false
if ENV["IMPORT"] == "1"
gem 'mysql2'
gem 'redcarpet'

View File

@ -9,4 +9,3 @@ Discourse::Application.load_tasks
# this prevents crashes when migrating a database in production in certain
# PostgreSQL configuations when trying to create structure.sql
Rake::Task["db:structure:dump"].clear if Rails.env.production?

View File

@ -112,7 +112,7 @@ class Admin::BadgesController < Admin::AdminController
# Badge query contract checks
begin
if SiteSetting.enable_badge_sql
BadgeGranter.contract_checks!(badge.query, { target_posts: badge.target_posts, trigger: badge.trigger })
BadgeGranter.contract_checks!(badge.query, target_posts: badge.target_posts, trigger: badge.trigger)
end
rescue => e
errors << e.message

View File

@ -29,7 +29,6 @@ class Admin::ColorSchemesController < Admin::AdminController
render json: success_json
end
private
def fetch_color_scheme

View File

@ -2,13 +2,13 @@ require 'disk_space'
class Admin::DashboardController < Admin::AdminController
def index
dashboard_data = AdminDashboardData.fetch_cached_stats || Jobs::DashboardStats.new.execute({})
dashboard_data.merge!({version_check: DiscourseUpdates.check_version.as_json}) if SiteSetting.version_checks?
dashboard_data.merge!(version_check: DiscourseUpdates.check_version.as_json) if SiteSetting.version_checks?
dashboard_data[:disk_space] = DiskSpace.cached_stats
render json: dashboard_data
end
def problems
render_json_dump({problems: AdminDashboardData.fetch_problems})
render_json_dump(problems: AdminDashboardData.fetch_problems)
end
end

View File

@ -43,7 +43,7 @@ class Admin::DiagnosticsController < Admin::AdminController
require 'objspace'
io = File.open("discourse-heap-#{SecureRandom.hex(3)}.json", 'w')
ObjectSpace.dump_all(:output => io)
ObjectSpace.dump_all(output: io)
io.close
render plain: "HEAP DUMP:\n#{io.path}"

View File

@ -55,7 +55,7 @@ class Admin::EmailController < Admin::AdminController
params.require(:username)
params.require(:email)
user = User.find_by_username(params[:username])
message, skip_reason = UserNotifications.send(:digest, user, {since: params[:last_seen_at]})
message, skip_reason = UserNotifications.send(:digest, user, since: params[:last_seen_at])
if message
message.to = params[:email]
begin
@ -138,7 +138,7 @@ class Admin::EmailController < Admin::AdminController
private
def filter_email_logs(email_logs, params)
email_logs = email_logs.includes(:user, { post: :topic })
email_logs = email_logs.includes(:user, post: :topic)
.references(:user)
.order(created_at: :desc)
.offset(params[:offset] || 0)
@ -154,7 +154,7 @@ class Admin::EmailController < Admin::AdminController
end
def filter_incoming_emails(incoming_emails, params)
incoming_emails = incoming_emails.includes(:user, { post: :topic })
incoming_emails = incoming_emails.includes(:user, post: :topic)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)

View File

@ -61,4 +61,3 @@ class Admin::EmojisController < Admin::AdminController
end
end

View File

@ -10,11 +10,11 @@ class Admin::FlagsController < Admin::AdminController
if posts.blank?
render json: { posts: [], topics: [], users: [] }
else
render json: MultiJson.dump({
render json: MultiJson.dump(
posts: posts,
topics: serialize_data(topics, FlaggedTopicSerializer),
users: serialize_data(users, FlaggedUserSerializer)
})
)
end
end

View File

@ -46,7 +46,7 @@ class Admin::ScreenedIpAddressesController < Admin::AdminController
def roll_up
subnets = ScreenedIpAddress.roll_up(current_user)
render json: success_json.merge!({ subnets: subnets })
render json: success_json.merge!(subnets: subnets)
end
private

View File

@ -46,13 +46,11 @@ class Admin::StaffActionLogsController < Admin::AdminController
cur: child_themes(cur)
}
load_diff(diff_fields, :cur, cur)
load_diff(diff_fields, :prev, prev)
diff_fields.delete_if { |k, v| v[:cur] == v[:prev] }
diff_fields.each do |k, v|
output << "<h3>#{k}</h3><p></p>"
diff = DiscourseDiff.new(v[:prev] || "", v[:cur] || "")

View File

@ -192,13 +192,14 @@ class Admin::ThemesController < Admin::AdminController
begin
# deep munge is a train wreck, work around it for now
params[:theme][:child_theme_ids] ||= [] if params[:theme].key?(:child_theme_ids)
params.require(:theme)
.permit(:name,
params.require(:theme).permit(
:name,
:color_scheme_id,
:default,
:user_selectable,
theme_fields: [:name, :target, :value, :upload_id, :type_id],
child_theme_ids: [])
child_theme_ids: []
)
end
end

View File

@ -55,4 +55,3 @@ class Admin::UserFieldsController < Admin::AdminController
end
end
end

View File

@ -154,7 +154,6 @@ class Admin::UsersController < Admin::AdminController
guardian.ensure_can_change_trust_level!(@user)
level = params[:level].to_i
if !@user.trust_level_locked && [0, 1, 2].include?(level) && Promotion.send("tl#{level + 1}_met?", @user)
@user.trust_level_locked = true
@user.save
@ -242,7 +241,7 @@ class Admin::UsersController < Admin::AdminController
d = UserDestroyer.new(current_user)
User.where(id: params[:users]).each do |u|
success_count += 1 if guardian.can_delete_user?(u) and d.destroy(u, params.slice(:context)) rescue UserDestroyer::PostsExistError
success_count += 1 if guardian.can_delete_user?(u) && d.destroy(u, params.slice(:context)) rescue UserDestroyer::PostsExistError
end
render json: {

View File

@ -394,7 +394,6 @@ class ApplicationController < ActionController::Base
end
end
def secure_session
SecureSession.new(session["secure_session_id"] ||= SecureRandom.hex)
end
@ -433,7 +432,9 @@ class ApplicationController < ActionController::Base
def custom_html_json
target = view_context.mobile_view? ? :mobile : :desktop
data = if @theme_key
data =
if @theme_key
{
top: Theme.lookup_field(@theme_key, target, "after_header"),
footer: Theme.lookup_field(@theme_key, target, "footer")
@ -577,7 +578,7 @@ class ApplicationController < ActionController::Base
def build_not_found_page(status = 404, layout = false)
category_topic_ids = Category.pluck(:topic_id).compact
@container_class = "wrap not-found-container"
@top_viewed = TopicQuery.new(nil, {except_topic_ids: category_topic_ids}).list_top_for("monthly").topics.first(10)
@top_viewed = TopicQuery.new(nil, except_topic_ids: category_topic_ids).list_top_for("monthly").topics.first(10)
@recent = Topic.where.not(id: category_topic_ids).recent(10)
@slug = params[:slug].class == String ? params[:slug] : ''
@slug = (params[:id].class == String ? params[:id] : '') if @slug.blank?
@ -585,7 +586,6 @@ class ApplicationController < ActionController::Base
render_to_string status: status, layout: layout, formats: [:html], template: '/exceptions/not_found'
end
protected
def render_post_json(post, add_raw = true)

View File

@ -250,10 +250,10 @@ class CategoriesController < ApplicationController
:default_view,
:subcategory_list_style,
:default_top_period,
:custom_fields => [params[:custom_fields].try(:keys)],
:permissions => [*p.try(:keys)],
:allowed_tags => [],
:allowed_tag_groups => [])
custom_fields: [params[:custom_fields].try(:keys)],
permissions: [*p.try(:keys)],
allowed_tags: [],
allowed_tag_groups: [])
end
end

View File

@ -8,7 +8,7 @@ class ClicksController < ApplicationController
params = track_params.merge(ip: request.remote_ip)
if params[:topic_id].present? || params[:post_id].present?
params.merge!({ user_id: current_user.id }) if current_user.present?
params.merge!(user_id: current_user.id) if current_user.present?
@redirect_url = TopicLinkClick.create_from(params)
end

View File

@ -96,7 +96,7 @@ class EmbedController < ApplicationController
def get_embeddable_css_class
@embeddable_css_class = ""
embeddable_host = EmbeddableHost.record_for_url(request.referer)
@embeddable_css_class = " class=\"#{embeddable_host.class_name}\"" if embeddable_host.present? and embeddable_host.class_name.present?
@embeddable_css_class = " class=\"#{embeddable_host.class_name}\"" if embeddable_host.present? && embeddable_host.class_name.present?
end
def ensure_api_request
@ -114,5 +114,4 @@ class EmbedController < ApplicationController
raise Discourse::InvalidAccess.new('invalid referer host')
end
end

View File

@ -124,13 +124,13 @@ class GroupsController < ApplicationController
members = group.users
.order('NOT group_users.owner')
.order(order)
.order(:username_lower => dir)
.order(username_lower: dir)
.limit(limit)
.offset(offset)
owners = group.users
.order(order)
.order(:username_lower => dir)
.order(username_lower: dir)
.where('group_users.owner')
render json: {

View File

@ -26,4 +26,3 @@ class HighlightJsController < ApplicationController
end
end
end

View File

@ -16,11 +16,12 @@ class InvitesController < ApplicationController
invite = Invite.find_by(invite_key: params[:id])
if invite.present?
store_preloaded("invite_info", MultiJson.dump({
store_preloaded("invite_info", MultiJson.dump(
invited_by: UserNameSerializer.new(invite.invited_by, scope: guardian, root: false),
email: invite.email,
username: UserNameSuggester.suggest(invite.email)
}))
username: UserNameSuggester.suggest(invite.email))
)
render layout: 'application'
else
flash.now[:error] = I18n.t('invite.not_found')

View File

@ -308,7 +308,7 @@ class ListController < ApplicationController
parent_category_id = nil
if parent_slug_or_id.present?
parent_category_id = Category.query_parent_category(parent_slug_or_id)
permalink_redirect_or_not_found and return if parent_category_id.blank? && !id
permalink_redirect_or_not_found && (return) if parent_category_id.blank? && !id
end
@category = Category.query_category(slug_or_id, parent_category_id)
@ -319,7 +319,7 @@ class ListController < ApplicationController
(redirect_to category.url, status: 301) && return if category
end
permalink_redirect_or_not_found and return if !@category
permalink_redirect_or_not_found && (return) if !@category
@description_meta = @category.description_text
raise Discourse::NotFound unless guardian.can_see?(@category)

View File

@ -31,7 +31,7 @@ class MetadataController < ApplicationController
}
if SiteSetting.native_app_install_banner
manifest = manifest.merge({
manifest = manifest.merge(
prefer_related_applications: true,
related_applications: [
{
@ -39,7 +39,7 @@ class MetadataController < ApplicationController
id: "com.discourse"
}
]
})
)
end
manifest

View File

@ -12,7 +12,6 @@ class PostActionUsersController < ApplicationController
post = finder.first
guardian.ensure_can_see!(post)
post_actions = post.post_actions.where(post_action_type_id: post_action_type_id)
.includes(:user)
.order('post_actions.created_at asc')

View File

@ -236,7 +236,7 @@ class PostsController < ApplicationController
guardian.ensure_can_delete!(post)
destroyer = PostDestroyer.new(current_user, post, { context: params[:context] })
destroyer = PostDestroyer.new(current_user, post, context: params[:context])
destroyer.destroy
render nothing: true
@ -399,7 +399,7 @@ class PostsController < ApplicationController
post = find_post_from_params
guardian.ensure_can_wiki!(post)
post.revise(current_user, { wiki: params[:wiki] })
post.revise(current_user, wiki: params[:wiki])
render nothing: true
end
@ -408,7 +408,7 @@ class PostsController < ApplicationController
guardian.ensure_can_change_post_type!
post = find_post_from_params
post.revise(current_user, { post_type: params[:post_type].to_i })
post.revise(current_user, post_type: params[:post_type].to_i)
render nothing: true
end
@ -479,7 +479,6 @@ class PostsController < ApplicationController
render json: json_obj, status: (!!success) ? 200 : 422
end
def find_post_revision_from_params
post_id = params[:id] || params[:post_id]
revision = params[:revision].to_i

View File

@ -41,18 +41,17 @@ class QueuedPostsController < ApplicationController
render_serialized(qp, QueuedPostSerializer, root: :queued_posts)
end
private
def user_deletion_opts
base = {
context: I18n.t('queue.delete_reason', {performed_by: current_user.username}),
context: I18n.t('queue.delete_reason', performed_by: current_user.username),
delete_posts: true,
delete_as_spammer: true
}
if Rails.env.production? && ENV["Staging"].nil?
base.merge!({block_email: true, block_ip: true})
base.merge!(block_email: true, block_ip: true)
end
base

View File

@ -112,7 +112,7 @@ class SessionController < ApplicationController
activation = UserActivator.new(user, request, session, cookies)
activation.finish
session["user_created_message"] = activation.message
redirect_to users_account_created_path and return
redirect_to(users_account_created_path) && (return)
else
if SiteSetting.verbose_sso_logging
Rails.logger.warn("Verbose SSO log: User was logged on #{user.username}\n\n#{sso.diagnostics}")
@ -321,8 +321,8 @@ class SessionController < ApplicationController
message = user.suspend_reason ? "login.suspended_with_reason" : "login.suspended"
render json: {
error: I18n.t(message, { date: I18n.l(user.suspended_till, format: :date_only),
reason: Rack::Utils.escape_html(user.suspend_reason) }),
error: I18n.t(message, date: I18n.l(user.suspended_till, format: :date_only),
reason: Rack::Utils.escape_html(user.suspend_reason)),
reason: 'suspended'
}
end
@ -337,7 +337,6 @@ class SessionController < ApplicationController
render_serialized(user, UserSerializer)
end
def render_sso_error(status:, text:)
@sso_error = text
render status: status, layout: 'no_ember'

View File

@ -137,7 +137,6 @@ class StaticController < ApplicationController
end
end
def cdn_asset
serve_asset
end
@ -151,7 +150,6 @@ class StaticController < ApplicationController
# SECURITY what if path has /../
raise Discourse::NotFound unless path.start_with?(Rails.root.to_s + "/public/assets")
response.headers["Expires"] = 1.year.from_now.httpdate
response.headers["Access-Control-Allow-Origin"] = params[:origin] if params[:origin]

View File

@ -59,7 +59,6 @@ class StylesheetsController < ApplicationController
return render nothing: true, status: 304
end
unless File.exist?(location)
if current = query.limit(1).pluck(source_map ? :source_map : :content).first
File.write(location, current)

View File

@ -69,7 +69,7 @@ class TagGroupsController < ApplicationController
end
def tag_groups_params
result = params.permit(:id, :name, :one_per_topic, :tag_names => [], :parent_tag_name => [])
result = params.permit(:id, :name, :one_per_topic, tag_names: [], parent_tag_name: [])
result[:tag_names] ||= []
result[:parent_tag_name] ||= []
result[:one_per_topic] = (params[:one_per_topic] == "true")

View File

@ -116,7 +116,7 @@ class TagsController < ::ApplicationController
@title = "#{SiteSetting.title} - #{@description}"
@atom_link = "#{Discourse.base_url}/tags/#{tag_id}.rss"
query = TopicQuery.new(current_user, {tags: [tag_id]})
query = TopicQuery.new(current_user, tags: [tag_id])
latest_results = query.latest_results
@topic_list = query.create_list(:by_tag, {}, latest_results)
@ -129,12 +129,10 @@ class TagsController < ::ApplicationController
tags_with_counts = DiscourseTagging.filter_allowed_tags(
Tag.tags_by_count_query(params.slice(:limit)),
guardian,
{
for_input: params[:filterForInput],
term: params[:q],
category: category,
selected_tags: params[:selected_tags]
}
)
tags = tags_with_counts.count(Tag::COUNT_ARG).map { |t, c| { id: t, text: t, count: c } }
@ -201,13 +199,13 @@ class TagsController < ::ApplicationController
parent_category_id = nil
if parent_slug_or_id.present?
parent_category_id = Category.query_parent_category(parent_slug_or_id)
category_redirect_or_not_found and return if parent_category_id.blank?
category_redirect_or_not_found && (return) if parent_category_id.blank?
end
@filter_on_category = Category.query_category(slug_or_id, parent_category_id)
end
category_redirect_or_not_found and return if !@filter_on_category
category_redirect_or_not_found && (return) if !@filter_on_category
guardian.ensure_can_see!(@filter_on_category)
end

View File

@ -155,7 +155,6 @@ class TopicsController < ApplicationController
TopicUser.change(current_user.id, params[:topic_id].to_i, notification_level: TopicUser.notification_levels[:muted])
end
perform_show_response
end
@ -164,7 +163,8 @@ class TopicsController < ApplicationController
params.require(:topic_id)
params.permit(:min_trust_level, :min_score, :min_replies, :bypass_trust_level_score, :only_moderator_liked)
opts = { best: params[:best].to_i,
opts = {
best: params[:best].to_i,
min_trust_level: params[:min_trust_level] ? params[:min_trust_level].to_i : 1,
min_score: params[:min_score].to_i,
min_replies: params[:min_replies].to_i,
@ -217,7 +217,6 @@ class TopicsController < ApplicationController
}
end
render json: @posts.to_json
end
@ -319,13 +318,13 @@ class TopicsController < ApplicationController
)
if topic.save
render json: success_json.merge!({
render json: success_json.merge!(
execute_at: topic_status_update&.execute_at,
duration: topic_status_update&.duration,
based_on_last_post: topic_status_update&.based_on_last_post,
closed: topic.closed,
category_id: topic_status_update&.category_id
})
)
else
render_json_error(topic)
end
@ -421,7 +420,7 @@ class TopicsController < ApplicationController
guardian.ensure_can_delete!(topic)
first_post = topic.ordered_posts.first
PostDestroyer.new(current_user, first_post, { context: params[:context] }).destroy
PostDestroyer.new(current_user, first_post, context: params[:context]).destroy
render nothing: true
end
@ -484,7 +483,6 @@ class TopicsController < ApplicationController
topic = Topic.find_by(id: params[:topic_id])
groups = Group.lookup_groups(
group_ids: params[:group_ids],
group_names: params[:group_names]
@ -595,7 +593,7 @@ class TopicsController < ApplicationController
params[:topic_id].to_i,
params[:topic_time].to_i,
(params[:timings] || []).map { |post_number, t| [post_number.to_i, t.to_i] },
{mobile: view_context.mobile_view?}
mobile: view_context.mobile_view?
)
render nothing: true
end

View File

@ -104,6 +104,6 @@ class UserBadgesController < ApplicationController
def can_assign_badge_to_user?(user)
master_api_call = current_user.nil? && is_api?
master_api_call or guardian.can_grant_badges?(user)
master_api_call || guardian.can_grant_badges?(user)
end
end

View File

@ -83,7 +83,6 @@ class Users::OmniauthCallbacksController < ApplicationController
render layout: 'no_ember'
end
def self.find_authenticator(name)
BUILTIN_AUTH.each do |authenticator|
if authenticator.name == name

View File

@ -59,7 +59,7 @@ class UsersController < ApplicationController
# This is a hack to get around a Rails issue where values with periods aren't handled correctly
# when used as part of a route.
if params[:external_id] and params[:external_id].ends_with? '.json'
if params[:external_id] && params[:external_id].ends_with?('.json')
return render_json_dump(user_serializer)
end
@ -265,7 +265,7 @@ class UsersController < ApplicationController
end
def changing_case_of_own_username(target_user, username)
target_user and username.downcase == target_user.username.downcase
target_user && username.downcase == (target_user.username.downcase)
end
# Used for checking availability of a username and will return suggestions
@ -433,7 +433,7 @@ class UsersController < ApplicationController
if @error
render layout: 'no_ember'
else
store_preloaded("password_reset", MultiJson.dump({ is_developer: UsernameCheckerService.is_developer?(@user.email) }))
store_preloaded("password_reset", MultiJson.dump(is_developer: UsernameCheckerService.is_developer?(@user.email)))
end
return redirect_to(wizard_path) if request.put? && Wizard.user_requires_completion?(@user)
end
@ -469,7 +469,8 @@ class UsersController < ApplicationController
end
def logon_after_password_reset
message = if Guardian.new(@user).can_access_forum?
message =
if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
'password_reset.success'
@ -662,7 +663,6 @@ class UsersController < ApplicationController
@group = Group.find_by(name: params[:group])
end
results = UserSearch.new(term,
topic_id: topic_id,
topic_allowed_users: topic_allowed_users,
@ -752,7 +752,7 @@ class UsersController < ApplicationController
@user = fetch_user_from_params
guardian.ensure_can_delete_user!(@user)
UserDestroyer.new(current_user).destroy(@user, { delete_posts: true, context: params[:context] })
UserDestroyer.new(current_user).destroy(@user, delete_posts: true, context: params[:context])
render json: success_json
end
@ -845,7 +845,6 @@ class UsersController < ApplicationController
result.merge!(params.permit(:active, :staged))
end
result
end

View File

@ -114,7 +114,6 @@ module Jobs
end
end
dbs =
if opts[:current_site_id]
[opts[:current_site_id]]

View File

@ -14,4 +14,3 @@ module Jobs
end
end

View File

@ -12,7 +12,7 @@ module Jobs
if Guardian.new(topic_timer.user).can_delete?(topic)
first_post = topic.ordered_posts.first
PostDestroyer.new(topic_timer.user, first_post, { context: I18n.t("topic_statuses.auto_deleted_by_timer") }).destroy
PostDestroyer.new(topic_timer.user, first_post, context: I18n.t("topic_statuses.auto_deleted_by_timer")).destroy
topic_timer.trash!(Discourse.system_user)
end
end

View File

@ -83,7 +83,8 @@ module Jobs
web_hook_event = WebHookEvent.create!(web_hook_id: web_hook.id)
begin
content_type = case web_hook.content_type
content_type =
case web_hook.content_type
when WebHook.content_types['application/x-www-form-urlencoded']
'application/x-www-form-urlencoded'
else

View File

@ -8,7 +8,7 @@ module Jobs
sidekiq_options retry: false
HEADER_ATTRS_FOR ||= HashWithIndifferentAccess.new({
HEADER_ATTRS_FOR ||= HashWithIndifferentAccess.new(
user_archive: ['topic_title', 'category', 'sub_category', 'is_pm', 'post', 'like_count', 'reply_count', 'url', 'created_at'],
user_list: ['id', 'name', 'username', 'email', 'title', 'created_at', 'last_seen_at', 'last_posted_at', 'last_emailed_at', 'trust_level', 'approved', 'suspended_at', 'suspended_till', 'blocked', 'active', 'admin', 'moderator', 'ip_address'],
user_stats: ['topics_entered', 'posts_read_count', 'time_read', 'topic_count', 'post_count', 'likes_given', 'likes_received'],
@ -18,8 +18,8 @@ module Jobs
screened_email: ['email', 'action', 'match_count', 'last_match_at', 'created_at', 'ip_address'],
screened_ip: ['ip_address', 'action', 'match_count', 'last_match_at', 'created_at'],
screened_url: ['domain', 'action', 'match_count', 'last_match_at', 'created_at'],
report: ['date', 'value'],
})
report: ['date', 'value']
)
def execute(args)
@entity = args[:entity]

View File

@ -57,7 +57,7 @@ module Jobs
end
end
rescue => e
Discourse.handle_job_exception(e, error_context(args, "Sending post to mailing list subscribers", { user_id: user.id, user_email: user.email }))
Discourse.handle_job_exception(e, error_context(args, "Sending post to mailing list subscribers", user_id: user.id, user_email: user.email))
end
end
end

View File

@ -15,9 +15,7 @@ module Jobs
clients = args["clients"]
clients.group_by { |r| r[1] }.each do |push_url, group|
notifications = group.map do |client_id, _|
notification.merge({
client_id: client_id
})
notification.merge(client_id: client_id)
end
result = Excon.post(push_url,

View File

@ -19,5 +19,3 @@ module Jobs
end
end

View File

@ -10,4 +10,3 @@ module Jobs
end
end

View File

@ -7,7 +7,7 @@ module Jobs
if problems_started_at && problems_started_at < 2.days.ago
# If there have been problems reported on the dashboard for a while,
# send a message to admins no more often than once per week.
GroupMessage.create(Group[:admins].name, :dashboard_problems, {limit_once_per: 7.days.to_i})
GroupMessage.create(Group[:admins].name, :dashboard_problems, limit_once_per: 7.days.to_i)
end
AdminDashboardData.refresh_stats

View File

@ -8,7 +8,7 @@ module Jobs
def execute(args)
badge = Badge.find(Badge::NewUserOfTheMonth)
return unless SiteSetting.enable_badges? and badge.enabled?
return unless SiteSetting.enable_badges? && badge.enabled?
# Don't award it if a month hasn't gone by
return if UserBadge.where("badge_id = ? AND granted_at >= ?",
@ -22,9 +22,7 @@ module Jobs
user = User.find(user_id)
if user.badges.where(id: Badge::NewUserOfTheMonth).blank?
BadgeGranter.grant(badge, user)
SystemMessage.new(user).create('new_user_of_the_month', {
month_year: Time.now.strftime("%B %Y")
})
SystemMessage.new(user).create('new_user_of_the_month', month_year: Time.now.strftime("%B %Y"))
end
end
end
@ -75,10 +73,8 @@ module Jobs
LIMIT :max_awarded
SQL
User.exec_sql(sql, {
like: PostActionType.types[:like],
max_awarded: MAX_AWARDED
}).each do |row|
User.exec_sql(sql, like: PostActionType.types[:like],
max_awarded: MAX_AWARDED).each do |row|
scores[row['id'].to_i] = row['score'].to_f
end
scores

View File

@ -25,8 +25,8 @@ module Jobs
target_group_names: Group[:moderators].name,
archetype: Archetype.private_message,
subtype: TopicSubtype.system_message,
title: I18n.t('flags_reminder.subject_template', { count: flagged_posts_count }),
raw: mentions + I18n.t('flags_reminder.flags_were_submitted', { count: SiteSetting.notify_about_flags_after })
title: I18n.t('flags_reminder.subject_template', count: flagged_posts_count),
raw: mentions + I18n.t('flags_reminder.flags_were_submitted', count: SiteSetting.notify_about_flags_after)
)
self.last_notified_id = flag_ids.max

View File

@ -7,7 +7,7 @@ module Jobs
def execute(args)
if SiteSetting.must_approve_users && SiteSetting.pending_users_reminder_delay >= 0
query = AdminUserIndexQuery.new({query: 'pending', stats: false}).find_users_query # default order is: users.created_at DESC
query = AdminUserIndexQuery.new(query: 'pending', stats: false).find_users_query # default order is: users.created_at DESC
if SiteSetting.pending_users_reminder_delay > 0
query = query.where('users.created_at < ?', SiteSetting.pending_users_reminder_delay.hours.ago)
end
@ -33,8 +33,8 @@ module Jobs
target_usernames: target_usernames,
archetype: Archetype.private_message,
subtype: TopicSubtype.pending_users_reminder,
title: I18n.t("system_messages.pending_users_reminder.subject_template", {count: count}),
raw: I18n.t("system_messages.pending_users_reminder.text_body_template", {count: count, base_url: Discourse.base_url})
title: I18n.t("system_messages.pending_users_reminder.subject_template", count: count),
raw: I18n.t("system_messages.pending_users_reminder.text_body_template", count: count, base_url: Discourse.base_url)
)
self.previous_newest_username = newest_username

View File

@ -7,4 +7,3 @@ module Jobs
end
end
end

View File

@ -6,7 +6,7 @@ module Jobs
every 1.day
def execute(args)
if SiteSetting.version_checks? and (DiscourseUpdates.updated_at.nil? or DiscourseUpdates.updated_at < 1.minute.ago)
if SiteSetting.version_checks? && (DiscourseUpdates.updated_at.nil? || DiscourseUpdates.updated_at < (1.minute.ago))
begin
prev_missing_versions_count = DiscourseUpdates.missing_versions_count || 0
@ -18,10 +18,10 @@ module Jobs
DiscourseUpdates.updated_at = Time.zone.now
DiscourseUpdates.missing_versions = json['versions']
if GlobalSetting.new_version_emails and
SiteSetting.new_version_emails and
json['missingVersionsCount'] > 0 and
prev_missing_versions_count < json['missingVersionsCount'].to_i
if GlobalSetting.new_version_emails &&
SiteSetting.new_version_emails &&
json['missingVersionsCount'] > (0) &&
prev_missing_versions_count < (json['missingVersionsCount'].to_i)
message = VersionMailer.send_notice
Email::Sender.new(message, :new_version).send

View File

@ -12,4 +12,3 @@ class AdminConfirmationMailer < ActionMailer::Base
)
end
end

View File

@ -23,7 +23,7 @@ class PendingFlagsMailer < ActionMailer::Base
@hours = SiteSetting.notify_about_flags_after
subject = "[#{SiteSetting.title}] " + I18n.t('flags_reminder.subject_template', { count: PostAction.flagged_posts_count })
subject = "[#{SiteSetting.title}] " + I18n.t('flags_reminder.subject_template', count: PostAction.flagged_posts_count)
build_email(SiteSetting.contact_email, subject: subject)
end

View File

@ -157,7 +157,6 @@ class UserNotifications < ActionMailer::Base
end
end
def user_replied(user, opts)
opts[:allow_reply_by_email] = true
opts[:use_site_subject] = true
@ -438,7 +437,6 @@ class UserNotifications < ActionMailer::Base
message = email_post_markdown(post) + (reached_limit ? "\n\n#{I18n.t "user_notifications.reached_limit", count: SiteSetting.max_emails_per_day_per_user}" : "");
end
unless translation_override_exists
html = UserNotificationRenderer.new(Rails.configuration.paths["app/views"]).render(
template: 'email/notification',

View File

@ -6,7 +6,7 @@ class VersionMailer < ActionMailer::Base
def send_notice
if SiteSetting.contact_email.present?
missing_versions = DiscourseUpdates.missing_versions
if missing_versions.present? and missing_versions.first['notes'].present?
if missing_versions.present? && missing_versions.first['notes'].present?
build_email(SiteSetting.contact_email,
template: 'new_version_mailer_with_notes',
notes: missing_versions.first['notes'],

View File

@ -208,7 +208,6 @@ class Badge < ActiveRecord::Base
val
end
def slug
Slug.for(self.display_name, '-')
end

View File

@ -3,7 +3,6 @@ class BadgeType < ActiveRecord::Base
Silver = 2
Bronze = 3
has_many :badges
validates :name, presence: true, uniqueness: true
end

View File

@ -72,7 +72,6 @@ class Category < ActiveRecord::Base
has_many :category_tag_groups, dependent: :destroy
has_many :tag_groups, through: :category_tag_groups
scope :latest, -> { order('topic_count DESC') }
scope :secured, -> (guardian = nil) {
@ -183,7 +182,6 @@ SQL
end
end
def visible_posts
query = Post.joins(:topic)
.where(['topics.category_id = ?', self.id])
@ -260,7 +258,7 @@ SQL
end
def publish_category_deletion
MessageBus.publish('/categories', {deleted_categories: [self.id]})
MessageBus.publish('/categories', deleted_categories: [self.id])
end
def parent_category_validator
@ -321,7 +319,7 @@ SQL
end
def allowed_tags=(tag_names_arg)
DiscourseTagging.add_or_create_tags_by_name(self, tag_names_arg, {unlimited: true})
DiscourseTagging.add_or_create_tags_by_name(self, tag_names_arg, unlimited: true)
end
def allowed_tag_groups=(group_names)

View File

@ -28,7 +28,7 @@ class CategoryFeaturedTopic < ActiveRecord::Base
results = query.list_category_topic_ids(c).uniq
# Add some topics that are visible to everyone:
anon_query = TopicQuery.new(nil, query_opts.merge({except_topic_ids: [c.topic_id] + results}))
anon_query = TopicQuery.new(nil, query_opts.merge(except_topic_ids: [c.topic_id] + results))
results += anon_query.list_category_topic_ids(c).uniq
return if results == existing

View File

@ -154,7 +154,6 @@ SQL
end
def self.ensure_consistency!
exec_sql <<SQL
DELETE FROM category_users

View File

@ -28,7 +28,7 @@ class ColorScheme < ActiveRecord::Base
]
CUSTOM_SCHEMES.each do |k, v|
list.push({id: k.to_s, colors: v})
list.push(id: k.to_s, colors: v)
end
list
end

View File

@ -42,7 +42,7 @@ module HasCustomFields
end
included do
has_many :_custom_fields, dependent: :destroy, :class_name => "#{name}CustomField"
has_many :_custom_fields, dependent: :destroy, class_name: "#{name}CustomField"
after_save :save_custom_fields
attr_accessor :preloaded_custom_fields

View File

@ -11,18 +11,18 @@ module Positionable
position = [[position_arg, 0].max, self.class.count - 1].min
if self.position.nil? or position > self.position
if self.position.nil? || position > (self.position)
self.exec_sql "
UPDATE #{self.class.table_name}
SET position = position - 1
WHERE position > :current_position and position <= :new_position",
{current_position: self.position, new_position: position}
current_position: self.position, new_position: position
elsif position < self.position
self.exec_sql "
UPDATE #{self.class.table_name}
SET position = position + 1
WHERE position >= :new_position and position < :current_position",
{current_position: self.position, new_position: position}
current_position: self.position, new_position: position
else
# Not moving to a new position
return
@ -31,6 +31,6 @@ module Positionable
self.exec_sql "
UPDATE #{self.class.table_name}
SET position = :position
WHERE id = :id", {id: id, position: position}
WHERE id = :id", id: id, position: position
end
end

View File

@ -8,7 +8,6 @@ module Trashable
belongs_to :deleted_by, class_name: 'User'
end
module ClassMethods
def with_deleted
# lifted from acts_as_paranoid, works around https://github.com/rails/rails/issues/4306
@ -44,7 +43,6 @@ module Trashable
trash_update(nil, nil)
end
private
def trash_update(deleted_at, deleted_by_id)

View File

@ -30,7 +30,8 @@ class DirectoryItem < ActiveRecord::Base
# Don't calculate it if the user directory is disabled
return unless SiteSetting.enable_user_directory?
since = case period_type
since =
case period_type
when :daily then 1.day.ago
when :weekly then 1.week.ago
when :monthly then 1.month.ago
@ -47,7 +48,6 @@ class DirectoryItem < ActiveRecord::Base
u.id IS NULL AND
di.period_type = :period_type", period_type: period_types[period_type]
exec_sql "INSERT INTO directory_items(period_type, user_id, likes_received, likes_given, topics_entered, days_visited, posts_read, topic_count, post_count)
SELECT
:period_type,
@ -117,7 +117,6 @@ class DirectoryItem < ActiveRecord::Base
reply_type: UserAction::REPLY,
regular_post_type: Post.types[:regular]
if period_type == :all
exec_sql <<SQL
UPDATE user_stats s

View File

@ -134,7 +134,6 @@ class GlobalSetting
setting
end
def resolve(current, default)
BaseProvider.coerce(
if current.present?
@ -167,7 +166,6 @@ class GlobalSetting
end
end
def lookup(key, default)
var = @data[key]
resolve(var, var.nil? ? default : "")
@ -207,7 +205,6 @@ class GlobalSetting
end
end
class << self
attr_accessor :provider
end

View File

@ -44,26 +44,26 @@ class Group < ActiveRecord::Base
validates :flair_url, url: true, if: Proc.new { |g| g.flair_url && g.flair_url[0, 3] != 'fa-' }
AUTO_GROUPS = {
:everyone => 0,
:admins => 1,
:moderators => 2,
:staff => 3,
:trust_level_0 => 10,
:trust_level_1 => 11,
:trust_level_2 => 12,
:trust_level_3 => 13,
:trust_level_4 => 14
everyone: 0,
admins: 1,
moderators: 2,
staff: 3,
trust_level_0: 10,
trust_level_1: 11,
trust_level_2: 12,
trust_level_3: 13,
trust_level_4: 14
}
AUTO_GROUP_IDS = Hash[*AUTO_GROUPS.to_a.flatten.reverse]
STAFF_GROUPS = [:admins, :moderators, :staff]
ALIAS_LEVELS = {
:nobody => 0,
:only_admins => 1,
:mods_and_admins => 2,
:members_mods_and_admins => 3,
:everyone => 99
nobody: 0,
only_admins: 1,
mods_and_admins: 2,
members_mods_and_admins: 3,
everyone: 99
}
def self.visibility_levels
@ -237,7 +237,8 @@ class Group < ActiveRecord::Base
end
# Remove people from groups they don't belong in.
remove_subquery = case name
remove_subquery =
case name
when :admins
"SELECT id FROM users WHERE NOT admin"
when :moderators
@ -256,7 +257,8 @@ class Group < ActiveRecord::Base
SQL
# Add people to groups
insert_subquery = case name
insert_subquery =
case name
when :admins
"SELECT id FROM users WHERE admin"
when :moderators

View File

@ -15,12 +15,11 @@ class GroupArchivedMessage < ActiveRecord::Base
MessageBus.publish("/topic/#{topic_id}", { type: "archived" }, group_ids: [group_id])
end
def self.trigger(event, group_id, topic_id)
group = Group.find_by(id: group_id)
topic = Topic.find_by(id: topic_id)
if group && topic
DiscourseEvent.trigger(event, {group: group, topic: topic})
DiscourseEvent.trigger(event, group: group, topic: topic)
end
end

View File

@ -25,36 +25,41 @@ class GroupUser < ActiveRecord::Base
def set_primary_group
if group.primary_group
self.class.exec_sql("UPDATE users
self.class.exec_sql("
UPDATE users
SET primary_group_id = :id
WHERE id = :user_id",
id: group.id, user_id: user_id)
id: group.id, user_id: user_id
)
end
end
def remove_primary_group
self.class.exec_sql("UPDATE users
self.class.exec_sql("
UPDATE users
SET primary_group_id = NULL
WHERE id = :user_id AND primary_group_id = :id",
id: group.id, user_id: user_id)
id: group.id, user_id: user_id
)
end
def remove_title
if group.title.present?
self.class.exec_sql("UPDATE users SET title = NULL
self.class.exec_sql("
UPDATE users SET title = NULL
WHERE title = :title AND id = :id",
id: user_id,
title: group.title)
id: user_id, title: group.title
)
end
end
def update_title
if group.title.present?
self.class.exec_sql("UPDATE users SET title = :title
self.class.exec_sql("
UPDATE users SET title = :title
WHERE (title IS NULL OR title = '') AND id = :id",
id: user_id,
title: group.title)
id: user_id, title: group.title
)
end
end

View File

@ -39,7 +39,6 @@ class IncomingLink < ActiveRecord::Base
cid = current_user ? (current_user.id) : (nil)
unless cid && cid == user_id
create(referer: referer,
@ -53,7 +52,6 @@ class IncomingLink < ActiveRecord::Base
end
def referer=(referer)
self.incoming_referer_id = nil
@ -87,7 +85,6 @@ class IncomingLink < ActiveRecord::Base
end
end
# Internal: Update appropriate link counts.
def update_link_counts
exec_sql("UPDATE topics

View File

@ -58,7 +58,6 @@ class IncomingLinksReport
per_user.joins(:post).count("DISTINCT posts.topic_id")
end
# Return top 10 domains that brought traffic to the site within the last 30 days
def self.report_top_traffic_sources(report)
report.y_titles[:num_clicks] = I18n.t("reports.#{report.type}.num_clicks")
@ -76,7 +75,7 @@ class IncomingLinksReport
def self.link_count_per_domain(limit = 10)
IncomingLink.where('incoming_links.created_at > ?', 30.days.ago)
.joins(:incoming_referer => :incoming_domain)
.joins(incoming_referer: :incoming_domain)
.group('incoming_domains.name')
.order('count_all DESC')
.limit(limit).count
@ -84,7 +83,7 @@ class IncomingLinksReport
def self.per_domain(domains)
IncomingLink
.joins(:incoming_referer => :incoming_domain)
.joins(incoming_referer: :incoming_domain)
.where('incoming_links.created_at > ? AND incoming_domains.name IN (?)', 30.days.ago, domains)
.group('incoming_domains.name')
end
@ -94,7 +93,6 @@ class IncomingLinksReport
per_domain(domains).joins(:post).count("DISTINCT posts.topic_id")
end
def self.report_top_referred_topics(report)
report.y_titles[:num_clicks] = I18n.t("reports.#{report.type}.num_clicks")
num_clicks = link_count_per_topic

View File

@ -71,22 +71,23 @@ class Invite < ActiveRecord::Base
end
def self.invite_by_email(email, invited_by, topic = nil, group_ids = nil, custom_message = nil)
create_invite_by_email(email, invited_by, {
create_invite_by_email(email, invited_by,
topic: topic,
group_ids: group_ids,
custom_message: custom_message,
send_email: true
})
)
end
# generate invite link
def self.generate_invite_link(email, invited_by, topic = nil, group_ids = nil)
invite = create_invite_by_email(email, invited_by, {
invite = create_invite_by_email(email, invited_by,
topic: topic,
group_ids: group_ids,
send_email: false
})
return "#{Discourse.base_url}/invites/#{invite.invite_key}" if invite
)
"#{Discourse.base_url}/invites/#{invite.invite_key}" if invite
end
# Create an invite for a user, supplying an optional topic
@ -164,7 +165,7 @@ class Invite < ActiveRecord::Base
def self.find_all_invites_from(inviter, offset = 0, limit = SiteSetting.invites_per_page)
Invite.where(invited_by_id: inviter.id)
.where('invites.email IS NOT NULL')
.includes(:user => :user_stat)
.includes(user: :user_stat)
.order('CASE WHEN invites.user_id IS NOT NULL THEN 0 ELSE 1 END',
'user_stats.time_read DESC',
'invites.redeemed_at DESC')

View File

@ -94,7 +94,6 @@ InviteRedeemer = Struct.new(:invite, :username, :name, :password, :user_custom_f
User.where(admin: false).find_by_email(invite.email)
end
def add_to_private_topics_if_invited
invite.topics.private_messages.each do |t|
t.topic_allowed_users.create(user_id: invited_user.id)

View File

@ -182,7 +182,7 @@ class Post < ActiveRecord::Base
def matches_recent_post?
post_id = $redis.get(unique_post_key)
post_id != nil and post_id.to_i != id
post_id != (nil) && post_id.to_i != (id)
end
def raw_hash
@ -218,9 +218,9 @@ class Post < ActiveRecord::Base
# case we can skip the rendering pipeline.
return raw if cook_method == Post.cook_methods[:raw_html]
cooked = nil
cooked =
if cook_method == Post.cook_methods[:email]
cooked = EmailCook.new(raw).cook
EmailCook.new(raw).cook
else
cloned = args.dup
cloned[1] ||= {}
@ -228,7 +228,7 @@ class Post < ActiveRecord::Base
post_user = self.user
cloned[1][:user_id] = post_user.id if post_user
cooked = if add_nofollow?
if add_nofollow?
post_analyzer.cook(*args)
else
# At trust level 3, we don't apply nofollow to links
@ -492,7 +492,7 @@ class Post < ActiveRecord::Base
old_user: (self.user.username_lower rescue nil) || I18n.t('change_owner.deleted_user'),
new_user: new_user.username_lower
)
revise(actor, {raw: self.raw, user_id: new_user.id, edit_reason: edit_reason}, {bypass_bump: true, skip_revision: skip_revision})
revise(actor, { raw: self.raw, user_id: new_user.id, edit_reason: edit_reason }, bypass_bump: true, skip_revision: skip_revision)
if post_number == topic.highest_post_number
topic.update_columns(last_post_user_id: new_user.id)
@ -577,7 +577,6 @@ class Post < ActiveRecord::Base
self.quote_count = temp_collector.size
end
def save_reply_relationships
add_to_quoted_post_numbers(reply_to_post_number)
return if self.quoted_post_numbers.blank?

View File

@ -62,7 +62,7 @@ class PostAction < ActiveRecord::Base
$redis.set('posts_flagged_count', posts_flagged_count)
user_ids = User.staff.pluck(:id)
MessageBus.publish('/flagged_counts', { total: posts_flagged_count }, { user_ids: user_ids })
MessageBus.publish('/flagged_counts', { total: posts_flagged_count }, user_ids: user_ids)
end
def self.flagged_posts_count
@ -107,7 +107,6 @@ SQL
(map[row.topic_id] ||= []) << row.post_number
end
map
end
@ -237,7 +236,9 @@ SQL
opts[:target_group_names] = target_moderators
else
opts[:subtype] = TopicSubtype.notify_user
opts[:target_usernames] = if post_action_type == :notify_user
opts[:target_usernames] =
if post_action_type == :notify_user
post.user.username
elsif post_action_type != :notify_moderators
# this is a hack to allow a PM with no recipients, we should think through
@ -260,9 +261,9 @@ SQL
related_post_id = create_message_for_post_action(user, post, post_action_type_id, opts)
staff_took_action = opts[:take_action] || false
targets_topic = if opts[:flag_topic] && post.topic
post.topic.reload
post.topic.posts_count != 1
targets_topic =
if opts[:flag_topic] && post.topic
post.topic.reload.posts_count != 1
end
where_attrs = {
@ -445,7 +446,6 @@ SQL
Post.where(id: post_id).update_all ["#{column} = ?", count]
end
topic_id = Post.with_deleted.where(id: post_id).pluck(:topic_id).first
# topic_user

View File

@ -5,7 +5,6 @@ class PostTiming < ActiveRecord::Base
validates_presence_of :post_number
validates_presence_of :msecs
def self.pretend_read(topic_id, actual_read_post_number, pretend_read_post_number)
# This is done in SQL cause the logic is quite tricky and we want to do this in one db hit
#
@ -60,7 +59,6 @@ class PostTiming < ActiveRecord::Base
record_new_timing(args) if rows == 0
end
def self.destroy_for(user_id, topic_ids)
PostTiming.transaction do
PostTiming.delete_all(['user_id = ? and topic_id in (?)', user_id, topic_ids])
@ -92,7 +90,6 @@ class PostTiming < ActiveRecord::Base
join_table << "SELECT #{topic_id.to_i} topic_id, #{post_number.to_i} post_number,
#{current_user.id.to_i} user_id, #{time.to_i} msecs, #{index} idx"
highest_seen = post_number.to_i > highest_seen ?
post_number.to_i : highest_seen
end

View File

@ -128,7 +128,7 @@ class Report
def self.report_time_to_first_response(report)
report.data = []
Topic.time_to_first_response_per_day(report.start_date, report.end_date, {category_id: report.category_id}).each do |r|
Topic.time_to_first_response_per_day(report.start_date, report.end_date, category_id: report.category_id).each do |r|
report.data << { x: Date.parse(r["date"]), y: r["hours"].to_f.round(2) }
end
report.total = Topic.time_to_first_response_total(category_id: report.category_id)

View File

@ -19,7 +19,7 @@ class ScreenedEmail < ActiveRecord::Base
end
def self.block(email, opts = {})
find_by_email(Email.downcase(email)) || create(opts.slice(:action_type, :ip_address).merge({email: email}))
find_by_email(Email.downcase(email)) || create(opts.slice(:action_type, :ip_address).merge(email: email))
end
def self.should_block?(email)

View File

@ -69,8 +69,8 @@ class ScreenedIpAddress < ActiveRecord::Base
def self.exists_for_ip_address_and_action?(ip_address, action_type, opts = {})
b = match_for_ip_address(ip_address)
found = (!!b and b.action_type == action_type)
b.record_match! if found and opts[:record_match] != false
found = (!!b && b.action_type == (action_type))
b.record_match! if found && opts[:record_match] != (false)
found
end

View File

@ -122,12 +122,10 @@ class Theme < ActiveRecord::Base
@cache.clear
end
def self.targets
@targets ||= Enum.new(common: 0, desktop: 1, mobile: 2)
end
def notify_scheme_change(clear_manager_cache = true)
Stylesheet::Manager.cache.clear if clear_manager_cache
message = refresh_message_for_targets(["desktop", "mobile", "admin"], self)
@ -223,10 +221,13 @@ class Theme < ActiveRecord::Base
fields = ThemeField.where(target_id: [Theme.targets[target], Theme.targets[:common]])
.where(name: name.to_s)
.includes(:theme)
.joins("JOIN (
.joins("
JOIN (
SELECT #{theme_ids.map.with_index { |id, idx| "#{id} AS theme_id, #{idx} AS sort_column" }.join(" UNION ALL SELECT ")}
) as X ON X.theme_id = theme_fields.theme_id")
) as X ON X.theme_id = theme_fields.theme_id"
)
.order('sort_column, target_id')
fields.each(&:ensure_baked!)
fields
end

View File

@ -90,7 +90,6 @@ COMPILED
@scss_fields ||= %w(scss embedded_scss)
end
def ensure_baked!
if ThemeField.html_fields.include?(self.name)
if !self.value_baked || compiler_version != COMPILER_VERSION

View File

@ -32,7 +32,6 @@ class TopTopic < ActiveRecord::Base
refresh_older!
end
def self.periods
@@periods ||= [:all, :yearly, :quarterly, :monthly, :weekly, :daily].freeze
end

View File

@ -57,23 +57,23 @@ class Topic < ActiveRecord::Base
rate_limit :limit_topics_per_day
rate_limit :limit_private_messages_per_day
validates :title, :if => Proc.new { |t| t.new_record? || t.title_changed? },
:presence => true,
:topic_title_length => true,
:censored_words => true,
:quality_title => { :unless => :private_message? },
:unique_among => { :unless => Proc.new { |t| (SiteSetting.allow_duplicate_topic_titles? || t.private_message?) },
:message => :has_already_been_used,
:allow_blank => true,
:case_sensitive => false,
:collection => Proc.new{ Topic.listable_topics } }
validates :title, if: Proc.new { |t| t.new_record? || t.title_changed? },
presence: true,
topic_title_length: true,
censored_words: true,
quality_title: { unless: :private_message? },
unique_among: { unless: Proc.new { |t| (SiteSetting.allow_duplicate_topic_titles? || t.private_message?) },
message: :has_already_been_used,
allow_blank: true,
case_sensitive: false,
collection: Proc.new { Topic.listable_topics } }
validates :category_id,
:presence => true,
:exclusion => {
:in => Proc.new{[SiteSetting.uncategorized_category_id]}
presence: true,
exclusion: {
in: Proc.new { [SiteSetting.uncategorized_category_id] }
},
:if => Proc.new { |t|
if: Proc.new { |t|
(t.new_record? || t.category_id_changed?) &&
!SiteSetting.allow_uncategorized_topics &&
(t.archetype.nil? || t.archetype == Archetype.default) &&
@ -504,7 +504,6 @@ class Topic < ActiveRecord::Base
end
end
def self.reset_all_highest!
exec_sql <<SQL
WITH
@ -542,7 +541,6 @@ WHERE
SQL
end
# If a post is deleted we have to update our highest post counters
def self.reset_highest(topic_id)
result = exec_sql "UPDATE topics
@ -809,7 +807,7 @@ SQL
end
def email_already_exists_for?(invite)
invite.email_already_exists and private_message?
invite.email_already_exists && private_message?
end
def grant_permission_to_user(lower_email)
@ -1147,14 +1145,14 @@ SQL
builder.where("p.deleted_at IS NULL")
builder.where("p.post_number > 1")
builder.where("p.user_id != t.user_id")
builder.where("p.user_id in (:user_ids)", {user_ids: opts[:user_ids]}) if opts[:user_ids]
builder.where("p.user_id in (:user_ids)", user_ids: opts[:user_ids]) if opts[:user_ids]
builder.where("p.post_type = :post_type", post_type: Post.types[:regular])
builder.where("EXTRACT(EPOCH FROM p.created_at - t.created_at) > 0")
builder.exec
end
def self.time_to_first_response_per_day(start_date, end_date, opts = {})
time_to_first_response(TIME_TO_FIRST_RESPONSE_SQL, opts.merge({start_date: start_date, end_date: end_date}))
time_to_first_response(TIME_TO_FIRST_RESPONSE_SQL, opts.merge(start_date: start_date, end_date: end_date))
end
def self.time_to_first_response_total(opts = nil)
@ -1245,7 +1243,6 @@ SQL
end
# == Schema Information
#
# Table name: topics

View File

@ -3,10 +3,10 @@ class TopicNotifier
@topic = topic
end
{ :watch! => :watching,
:track! => :tracking,
:regular! => :regular,
:mute! => :muted }.each_pair do |method_name, level|
{ watch!: :watching,
track!: :tracking,
regular!: :regular,
mute!: :muted }.each_pair do |method_name, level|
define_method method_name do |user_id|
change_level user_id, level

View File

@ -179,7 +179,6 @@ class TopicTrackingState
end
def self.report_raw_sql(opts = nil)
unread =
@ -205,7 +204,6 @@ class TopicTrackingState
c.id AS category_id,
tu.notification_level"
sql = <<SQL
SELECT #{select}
FROM topics

View File

@ -191,7 +191,6 @@ SQL
TopicUser.notification_reasons[:auto_track_tag]
end
end
unless attrs[:notification_level]
@ -276,7 +275,8 @@ SQL
# ... user visited the topic but did not read the posts
#
# 86400000 = 1 day
rows = if user.staff?
rows =
if user.staff?
exec_sql(UPDATE_TOPIC_USER_SQL_STAFF, args).values
else
exec_sql(UPDATE_TOPIC_USER_SQL, args).values

View File

@ -28,7 +28,6 @@ class TopicViewItem < ActiveRecord::Base
/*where*/
)"
builder = SqlBuilder.new(sql)
if !user_id

View File

@ -30,7 +30,7 @@ class TranslationOverride < ActiveRecord::Base
def self.i18n_changed
I18n.reload!
MessageBus.publish('/i18n-flush', { refresh: true })
MessageBus.publish('/i18n-flush', refresh: true)
end
def check_interpolation_keys

View File

@ -194,13 +194,11 @@ class TrustLevel3Requirements
(min_likes_received.to_f / 4.0).ceil
end
def self.clear_cache
$redis.del NUM_TOPICS_KEY
$redis.del NUM_POSTS_KEY
end
CACHE_DURATION = 1.day.seconds - 60
NUM_TOPICS_KEY = "tl3_num_topics"
NUM_POSTS_KEY = "tl3_num_posts"

View File

@ -74,7 +74,7 @@ class User < ActiveRecord::Base
has_many :acting_group_histories, dependent: :destroy, foreign_key: :acting_user_id, class_name: GroupHistory
has_many :targeted_group_histories, dependent: :destroy, foreign_key: :target_user_id, class_name: GroupHistory
delegate :last_sent_email_address, :to => :email_logs
delegate :last_sent_email_address, to: :email_logs
validates_presence_of :username
validate :username_validator, if: :username_changed?
@ -240,7 +240,6 @@ class User < ActiveRecord::Base
find_by(username_lower: username.downcase)
end
def enqueue_welcome_message(message_type)
return unless SiteSetting.send_welcome_message?
Jobs.enqueue(:send_system_message, user_id: id, message_type: message_type)
@ -377,7 +376,6 @@ class User < ActiveRecord::Base
notification = notifications.visible.order('notifications.id desc').first
json = NotificationSerializer.new(notification).as_json if notification
sql = "
SELECT * FROM (
SELECT n.id, n.read FROM notifications n
@ -727,7 +725,7 @@ class User < ActiveRecord::Base
'MAX(badges.grant_count) AS badges_grant_count')
.joins(:badge)
.order('badges_badge_type_id ASC, badges_grant_count ASC, badge_id DESC')
.includes(:user, :granted_by, { badge: :badge_type }, { post: :topic })
.includes(:user, :granted_by, { badge: :badge_type }, post: :topic)
tl_badge = query.where("user_badges.badge_id IN (:tl_badge_ids)",
tl_badge_ids: tl_badge_ids)
@ -750,7 +748,6 @@ class User < ActiveRecord::Base
result.group('date(users.created_at)').order('date(users.created_at)').count
end
def secure_category_ids
cats = self.admin? ? Category.where(read_restricted: true) : secure_categories.references(:categories)
cats.pluck('categories.id').sort
@ -760,7 +757,6 @@ class User < ActiveRecord::Base
Category.topic_create_allowed(self.id).select(:id)
end
# Flag all posts from a user as spam
def flag_linked_posts_as_spam
disagreed_flag_post_ids = PostAction.where(post_action_type_id: PostActionType.types[:spam])
@ -812,7 +808,6 @@ class User < ActiveRecord::Base
.exists?
end
def refresh_avatar
return if @import_mode

View File

@ -276,7 +276,7 @@ SQL
require_parameters(hash, :action_type, :user_id, :acting_user_id, :target_topic_id, :target_post_id)
if action = UserAction.find_by(hash.except(:created_at))
action.destroy
MessageBus.publish("/user/#{hash[:user_id]}", {user_action_id: action.id, remove: true})
MessageBus.publish("/user/#{hash[:user_id]}", user_action_id: action.id, remove: true)
end
if !Topic.where(id: hash[:target_topic_id], archetype: Archetype.private_message).exists?

View File

@ -25,7 +25,7 @@ class UserArchivedMessage < ActiveRecord::Base
user = User.find_by(id: user_id)
topic = Topic.find_by(id: topic_id)
if user && topic
DiscourseEvent.trigger(event, {user: user, topic: topic})
DiscourseEvent.trigger(event, user: user, topic: topic)
end
end
end

View File

@ -121,7 +121,7 @@ class UserHistory < ActiveRecord::Base
query = query.where(custom_type: filters[:custom_type]) if filters[:custom_type].present?
[:acting_user, :target_user].each do |key|
if filters[key] and obj_id = User.where(username_lower: filters[key].downcase).pluck(:id)
if filters[key] && (obj_id = User.where(username_lower: filters[key].downcase).pluck(:id))
query = query.where("#{key}_id = ?", obj_id)
end
end
@ -151,7 +151,6 @@ class UserHistory < ActiveRecord::Base
query
end
def set_admin_only
self.admin_only = UserHistory.admin_only_action_ids.include?(self.action)
self

View File

@ -94,7 +94,6 @@ class UserOption < ActiveRecord::Base
# top must be in the top_menu
return unless SiteSetting.top_menu =~ /(^|\|)top(\||$)/i
# not enough topics
return unless period = SiteSetting.min_redirected_to_top_period(1.days.ago)
@ -118,14 +117,18 @@ class UserOption < ActiveRecord::Base
def treat_as_new_topic_start_date
duration = new_topic_duration_minutes || SiteSetting.default_other_new_topic_duration_minutes.to_i
times = [case duration
times = [
case duration
when User::NewTopicDuration::ALWAYS
user.created_at
when User::NewTopicDuration::LAST_VISIT
user.previous_visit_at || user.user_stat.new_since
else
duration.minutes.ago
end, user.user_stat.new_since, Time.at(SiteSetting.min_new_topics_time).to_datetime]
end,
user.user_stat.new_since,
Time.at(SiteSetting.min_new_topics_time).to_datetime
]
times.max
end

View File

@ -30,7 +30,6 @@ class WatchedWord < ActiveRecord::Base
scope :by_action, -> { order("action ASC, word ASC") }
def self.normalize_word(w)
w.strip.downcase.squeeze('*')
end

View File

@ -6,12 +6,14 @@ class WebHookEvent < ActiveRecord::Base
default_scope { order('created_at DESC') }
def update_web_hook_delivery_status
web_hook.last_delivery_status = case status
web_hook.last_delivery_status =
case status
when 200..299
WebHook.last_delivery_statuses[:successful]
else
WebHook.last_delivery_statuses[:failed]
end
web_hook.save!
end
end

View File

@ -10,7 +10,6 @@ class DetailedUserBadgeSerializer < BasicUserBadgeSerializer
alias :include_topic_id? :include_post_number?
alias :include_topic_title? :include_post_number?
def post_number
object.post.post_number if object.post
end

View File

@ -20,11 +20,11 @@ class PostActionTypeSerializer < ApplicationSerializer
end
def description
i18n('description', {tos_url: tos_path})
i18n('description', tos_url: tos_path)
end
def short_description
i18n('short_description', {tos_url: tos_path})
i18n('short_description', tos_url: tos_path)
end
protected

View File

@ -22,4 +22,3 @@ module PostItemExcerpt
end
end

Some files were not shown because too many files have changed in this diff Show More