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

@@ -5,9 +5,9 @@ class Admin::BadgesController < Admin::AdminController
badge_types: BadgeType.all.order(:id).to_a,
badge_groupings: BadgeGrouping.all.order(:position).to_a,
badges: Badge.includes(:badge_grouping)
.includes(:badge_type)
.references(:badge_grouping)
.order('badge_groupings.position, badge_type_id, badges.name').to_a,
.includes(:badge_type)
.references(:badge_grouping)
.order('badge_groupings.position, badge_type_id, badges.name').to_a,
protected_system_fields: Badge.protected_system_fields,
triggers: Badge.trigger_hash
}
@@ -43,9 +43,9 @@ class Admin::BadgesController < Admin::AdminController
badge_groupings = BadgeGrouping.all.order(:position).to_a
ids = params[:ids].map(&:to_i)
params[:names].each_with_index do |name,index|
params[:names].each_with_index do |name, index|
id = ids[index].to_i
group = badge_groupings.find{|b| b.id == id} || BadgeGrouping.new()
group = badge_groupings.find { |b| b.id == id } || BadgeGrouping.new()
group.name = name
group.position = index
group.save
@@ -95,7 +95,7 @@ class Admin::BadgesController < Admin::AdminController
# Options:
# :new - reset the badge id to nil before saving
def update_badge_from_params(badge, opts={})
def update_badge_from_params(badge, opts = {})
errors = []
Badge.transaction do
allowed = Badge.column_names.map(&:to_sym)
@@ -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

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

View File

@@ -13,7 +13,7 @@ class Admin::EmailController < Admin::AdminController
Jobs::TestEmail.new.execute(to_address: params[:email_address])
render nothing: true
rescue => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@@ -55,17 +55,17 @@ 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
Email::Sender.new(message, :digest).send
render json: success_json
rescue => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
else
render json: {errors: skip_reason}
render json: { errors: skip_reason }
end
end
@@ -131,18 +131,18 @@ class Admin::EmailController < Admin::AdminController
serializer = IncomingEmailDetailsSerializer.new(incoming_email, root: false)
render_json_dump(serializer)
rescue => e
render json: {errors: [e.message]}, status: 404
render json: { errors: [e.message] }, status: 404
end
end
private
def filter_email_logs(email_logs, params)
email_logs = email_logs.includes(:user, { post: :topic })
.references(:user)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
email_logs = email_logs.includes(:user, post: :topic)
.references(:user)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
email_logs = email_logs.where("users.username ILIKE ?", "%#{params[:user]}%") if params[:user].present?
email_logs = email_logs.where("email_logs.to_address ILIKE ?", "%#{params[:address]}%") if params[:address].present?
@@ -154,10 +154,10 @@ class Admin::EmailController < Admin::AdminController
end
def filter_incoming_emails(incoming_emails, params)
incoming_emails = incoming_emails.includes(:user, { post: :topic })
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
incoming_emails = incoming_emails.includes(:user, post: :topic)
.order(created_at: :desc)
.offset(params[:offset] || 0)
.limit(50)
incoming_emails = incoming_emails.where("from_address ILIKE ?", "%#{params[:from]}%") if params[:from].present?
incoming_emails = incoming_emails.where("to_addresses ILIKE :to OR cc_addresses ILIKE :to", to: "%#{params[:to]}%") if params[:to].present?
@@ -170,7 +170,7 @@ class Admin::EmailController < Admin::AdminController
def delivery_settings
action_mailer_settings
.reject { |k, _| k == :password }
.map { |k, v| { name: k, value: v }}
.map { |k, v| { name: k, value: v } }
end
def delivery_method

View File

@@ -13,8 +13,8 @@ class Admin::EmojisController < Admin::AdminController
Scheduler::Defer.later("Upload Emoji") do
# fix the name
name = name.gsub(/[^a-z0-9]+/i, '_')
.gsub(/_{2,}/, '_')
.downcase
.gsub(/_{2,}/, '_')
.downcase
upload = UploadCreator.new(
file.tempfile,
@@ -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

@@ -11,7 +11,7 @@ class Admin::GroupsController < Admin::AdminController
group = Group.find(params[:group_id].to_i)
users_added = 0
if group.present?
users = (params[:users] || []).map {|u| u.downcase}
users = (params[:users] || []).map { |u| u.downcase }
valid_emails = {}
valid_usernames = {}
@@ -162,7 +162,7 @@ class Admin::GroupsController < Admin::AdminController
protected
def can_not_modify_automatic
render json: {errors: I18n.t('groups.errors.can_not_modify_automatic')}, status: 422
render json: { errors: I18n.t('groups.errors.can_not_modify_automatic') }, status: 422
end
private

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

@@ -17,7 +17,7 @@ class Admin::SiteSettingsController < Admin::AdminController
SiteSetting.set_and_log(id, value, current_user)
render nothing: true
rescue Discourse::InvalidParameters => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end

View File

@@ -14,7 +14,7 @@ class Admin::SiteTextsController < Admin::AdminController
query = params[:q] || ""
if query.blank? && !overridden
extras[:recommended] = true
results = self.class.preferred_keys.map {|k| record_for(k) }
results = self.class.preferred_keys.map { |k| record_for(k) }
else
results = []
translations = I18n.search(query, overridden: overridden)
@@ -69,14 +69,14 @@ class Admin::SiteTextsController < Admin::AdminController
protected
def record_for(k, value=nil)
def record_for(k, value = nil)
if k.ends_with?("_MF")
ovr = TranslationOverride.where(translation_key: k).pluck(:value)
value = ovr[0] if ovr.present?
end
value ||= I18n.t(k)
{id: k, value: value}
{ id: k, value: value }
end
def find_site_text

View File

@@ -6,7 +6,7 @@ class Admin::StaffActionLogsController < Admin::AdminController
staff_action_logs = UserHistory.staff_action_records(current_user, filters).to_a
render json: StaffActionLogsSerializer.new({
staff_action_logs: staff_action_logs,
user_history_actions: UserHistory.staff_actions.sort.map{|name| {id: UserHistory.actions[name], name: name}}
user_history_actions: UserHistory.staff_actions.sort.map { |name| { id: UserHistory.actions[name], name: name } }
}, root: false)
end
@@ -46,20 +46,18 @@ 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.delete_if { |k, v| v[:cur] == v[:prev] }
diff_fields.each do |k,v|
diff_fields.each do |k, v|
output << "<h3>#{k}</h3><p></p>"
diff = DiscourseDiff.new(v[:prev] || "", v[:cur] || "")
output << diff.side_by_side_markdown
end
render json: {side_by_side: output}
render json: { side_by_side: output }
end
protected
@@ -67,11 +65,11 @@ class Admin::StaffActionLogsController < Admin::AdminController
def child_themes(theme)
return "" unless children = theme["child_themes"]
children.map{|row| row["name"]}.join(" ").to_s
children.map { |row| row["name"] }.join(" ").to_s
end
def load_diff(hash, key, val)
if f=val["theme_fields"]
if f = val["theme_fields"]
f.each do |row|
entry = hash[row["target"] + " " + row["name"]] ||= {}
entry[key] = row["value"]

View File

@@ -62,7 +62,7 @@ class Admin::ThemesController < Admin::AdminController
}
respond_to do |format|
format.json { render json: payload}
format.json { render json: payload }
end
end
@@ -77,7 +77,7 @@ class Admin::ThemesController < Admin::AdminController
if @theme.save
update_default_theme
log_theme_change(nil, @theme)
format.json { render json: @theme, status: :created}
format.json { render json: @theme, status: :created }
else
format.json { render json: @theme.errors, status: :unprocessable_entity }
end
@@ -100,7 +100,7 @@ class Admin::ThemesController < Admin::AdminController
@theme.child_theme_relation.to_a.each do |child|
if expected.include?(child.child_theme_id)
expected.reject!{|id| id == child.child_theme_id}
expected.reject! { |id| id == child.child_theme_id }
else
child.destroy
end
@@ -133,12 +133,12 @@ class Admin::ThemesController < Admin::AdminController
update_default_theme
log_theme_change(original_json, @theme)
format.json { render json: @theme, status: :created}
format.json { render json: @theme, status: :created }
else
format.json {
error = @theme.errors[:color_scheme] ? I18n.t("themes.bad_color_scheme") : I18n.t("themes.other_error")
render json: {errors: [ error ]}, status: :unprocessable_entity
render json: { errors: [ error ] }, status: :unprocessable_entity
}
end
end
@@ -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,
:color_scheme_id,
:default,
:user_selectable,
theme_fields: [:name, :target, :value, :upload_id, :type_id],
child_theme_ids: [])
params.require(:theme).permit(
:name,
:color_scheme_id,
:default,
:user_selectable,
theme_fields: [:name, :target, :value, :upload_id, :type_id],
child_theme_ids: []
)
end
end

View File

@@ -51,8 +51,7 @@ class Admin::UserFieldsController < Admin::AdminController
options = params[:user_field][:options]
if options.present?
UserFieldOption.where(user_field_id: field.id).delete_all
field.user_field_options_attributes = options.map {|o| {value: o} }.uniq
field.user_field_options_attributes = options.map { |o| { value: o } }.uniq
end
end
end

View File

@@ -77,7 +77,7 @@ class Admin::UsersController < Admin::AdminController
@user.logged_out
render json: success_json
else
render json: {error: I18n.t('admin_js.admin.users.id_not_found')}, status: 404
render json: { error: I18n.t('admin_js.admin.users.id_not_found') }, status: 404
end
end
@@ -154,8 +154,7 @@ 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)
if !@user.trust_level_locked && [0, 1, 2].include?(level) && Promotion.send("tl#{level + 1}_met?", @user)
@user.trust_level_locked = true
@user.save
end
@@ -187,7 +186,7 @@ class Admin::UsersController < Admin::AdminController
unless @user.trust_level_locked
p = Promotion.new(@user)
2.times{ p.review }
2.times { p.review }
p.review_tl2
if @user.trust_level == 3 && Promotion.tl3_lost?(@user)
@user.change_trust_level!(2, log_action_for: current_user)
@@ -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: {
@@ -339,12 +338,12 @@ class Admin::UsersController < Admin::AdminController
user.save!
user.grant_admin!
user.change_trust_level!(4)
user.email_tokens.update_all confirmed: true
user.email_tokens.update_all confirmed: true
email_token = user.email_tokens.create(email: user.email)
unless params[:send_email] == '0' || params[:send_email] == 'false'
Jobs.enqueue( :critical_user_email,
Jobs.enqueue(:critical_user_email,
type: :account_created,
user_id: user.id,
email_token: email_token.token)

View File

@@ -28,7 +28,7 @@ class Admin::WatchedWordsController < Admin::AdminController
File.open(file.tempfile, encoding: "ISO-8859-1").each_line do |line|
WatchedWord.create_or_update_word(word: line, action_key: action_key) unless line.empty?
end
data = {url: '/ok'}
data = { url: '/ok' }
rescue => e
data = failed_json.merge(errors: [e.message])
end

View File

@@ -6,10 +6,10 @@ class Admin::WebHooksController < Admin::AdminController
offset = params[:offset].to_i
web_hooks = WebHook.limit(limit)
.offset(offset)
.includes(:web_hook_event_types)
.includes(:categories)
.includes(:groups)
.offset(offset)
.includes(:web_hook_event_types)
.includes(:categories)
.includes(:groups)
json = {
web_hooks: serialize_data(web_hooks, AdminWebHookSerializer),

View File

@@ -147,7 +147,7 @@ class ApplicationController < ActionController::Base
render_json_error I18n.t('read_only_mode_enabled'), type: :read_only, status: 503
end
def rescue_discourse_actions(type, status_code, include_ember=false)
def rescue_discourse_actions(type, status_code, include_ember = false)
show_json_errors = (request.format && request.format.json?) ||
(request.xhr?) ||
@@ -175,7 +175,7 @@ class ApplicationController < ActionController::Base
def set_current_user_for_logs
if current_user
Logster.add_to_env(request.env,"username",current_user.username)
Logster.add_to_env(request.env, "username", current_user.username)
response.headers["X-Discourse-Username"] = current_user.username
end
response.headers["X-Discourse-Route"] = "#{controller_name}/#{action_name}"
@@ -298,9 +298,9 @@ class ApplicationController < ActionController::Base
current_user ? SiteSetting.homepage : SiteSetting.anonymous_homepage
end
def serialize_data(obj, serializer, opts=nil)
def serialize_data(obj, serializer, opts = nil)
# If it's an array, apply the serializer as an each_serializer to the elements
serializer_opts = {scope: guardian}.merge!(opts || {})
serializer_opts = { scope: guardian }.merge!(opts || {})
if obj.respond_to?(:to_ary)
serializer_opts[:each_serializer] = serializer
ActiveModel::ArraySerializer.new(obj.to_ary, serializer_opts).as_json
@@ -313,11 +313,11 @@ class ApplicationController < ActionController::Base
# 20% slower than calling MultiJSON.dump ourselves. I'm not sure why
# Rails doesn't call MultiJson.dump when you pass it json: obj but
# it seems we don't need whatever Rails is doing.
def render_serialized(obj, serializer, opts=nil)
def render_serialized(obj, serializer, opts = nil)
render_json_dump(serialize_data(obj, serializer, opts), opts)
end
def render_json_dump(obj, opts=nil)
def render_json_dump(obj, opts = nil)
opts ||= {}
if opts[:rest_serializer]
obj['__rest_serializer'] = "1"
@@ -341,7 +341,7 @@ class ApplicationController < ActionController::Base
Middleware::AnonymousCache.anon_cache(request.env, time_length)
end
def fetch_user_from_params(opts=nil, eager_load = [])
def fetch_user_from_params(opts = nil, eager_load = [])
opts ||= {}
user = if params[:username]
username_lower = params[:username].downcase.chomp('.json')
@@ -361,9 +361,9 @@ class ApplicationController < ActionController::Base
end
def post_ids_including_replies
post_ids = params[:post_ids].map {|p| p.to_i}
post_ids = params[:post_ids].map { |p| p.to_i }
if params[:reply_post_ids]
post_ids |= PostReply.where(post_id: params[:reply_post_ids].map {|p| p.to_i}).pluck(:reply_id)
post_ids |= PostReply.where(post_id: params[:reply_post_ids].map { |p| p.to_i }).pluck(:reply_id)
end
post_ids
end
@@ -394,7 +394,6 @@ class ApplicationController < ActionController::Base
end
end
def secure_session
SecureSession.new(session["secure_session_id"] ||= SecureRandom.hex)
end
@@ -433,14 +432,16 @@ class ApplicationController < ActionController::Base
def custom_html_json
target = view_context.mobile_view? ? :mobile : :desktop
data = if @theme_key
{
top: Theme.lookup_field(@theme_key, target, "after_header"),
footer: Theme.lookup_field(@theme_key, target, "footer")
}
else
{}
end
data =
if @theme_key
{
top: Theme.lookup_field(@theme_key, target, "after_header"),
footer: Theme.lookup_field(@theme_key, target, "footer")
}
else
{}
end
if DiscoursePluginRegistry.custom_html
data.merge! DiscoursePluginRegistry.custom_html
@@ -480,7 +481,7 @@ class ApplicationController < ActionController::Base
# opts:
# type - a machine-readable description of the error
# status - HTTP status code to return
def render_json_error(obj, opts={})
def render_json_error(obj, opts = {})
opts = { status: opts } if opts.is_a?(Integer)
render json: MultiJson.dump(create_errors_json(obj, opts[:type])), status: opts[:status] || 422
end
@@ -493,7 +494,7 @@ class ApplicationController < ActionController::Base
{ failed: 'FAILED' }
end
def json_result(obj, opts={})
def json_result(obj, opts = {})
if yield(obj)
json = success_json
@@ -574,21 +575,20 @@ class ApplicationController < ActionController::Base
raise Discourse::ReadOnly.new if !(request.get? || request.head?) && Discourse.readonly_mode?
end
def build_not_found_page(status=404, layout=false)
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?
@slug.tr!('-',' ')
@slug.tr!('-', ' ')
render_to_string status: status, layout: layout, formats: [:html], template: '/exceptions/not_found'
end
protected
def render_post_json(post, add_raw=true)
def render_post_json(post, add_raw = true)
post_serializer = PostSerializer.new(post, scope: guardian, root: false)
post_serializer.add_raw = add_raw

View File

@@ -14,7 +14,7 @@ class BadgesController < ApplicationController
if (params[:only_listable] == "true") || !request.xhr?
# NOTE: this is sorted client side if needed
badges = badges.includes(:badge_grouping)
.where(enabled: true, listable: true)
.where(enabled: true, listable: true)
end

View File

@@ -218,7 +218,7 @@ class CategoriesController < ApplicationController
end
if p = params[:permissions]
p.each do |k,v|
p.each do |k, v|
p[k] = v.to_i
end
end
@@ -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
@@ -265,7 +265,7 @@ class CategoriesController < ApplicationController
@staff_action_logger = StaffActionLogger.new(current_user)
end
def include_topics(parent_category=nil)
def include_topics(parent_category = nil)
view_context.mobile_view? ||
params[:include_topics] ||
(parent_category && parent_category.subcategory_list_includes_topics?) ||

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

@@ -11,7 +11,7 @@ class ComposerMessagesController < ApplicationController
if params[:topic_id].present?
topic = Topic.where(id: params[:topic_id]).first
if guardian.can_see?(topic)
json[:extras] = {duplicate_lookup: TopicLink.duplicate_lookup(topic)}
json[:extras] = { duplicate_lookup: TopicLink.duplicate_lookup(topic) }
end
end

View File

@@ -53,7 +53,7 @@ class DirectoryItemsController < ApplicationController
# Put yourself at the top of the first page
if result.present? && current_user.present? && page == 0
position = result.index {|r| r.user_id == current_user.id }
position = result.index { |r| r.user_id == current_user.id }
# Don't show the record unless you're not in the top positions already
if (position || 10) >= 10

View File

@@ -5,7 +5,7 @@ class DraftController < ApplicationController
def show
seq = params[:sequence] || DraftSequence.current(current_user, params[:draft_key])
render json: {draft: Draft.get(current_user, params[:draft_key], seq), draft_sequence: seq}
render json: { draft: Draft.get(current_user, params[:draft_key], seq), draft_sequence: seq }
end
def update

View File

@@ -31,8 +31,8 @@ class EmailController < ApplicationController
if @topic.category_id
if CategoryUser.exists?(user_id: @user.id, notification_level: CategoryUser.watching_levels, category_id: @topic.category_id)
@watched_count = TopicUser.joins(:topic)
.where(user: @user, notification_level: watching, "topics.category_id" => @topic.category_id)
.count
.where(user: @user, notification_level: watching, "topics.category_id" => @topic.category_id)
.count
end
end
end
@@ -52,28 +52,28 @@ class EmailController < ApplicationController
if topic
if params["unwatch_topic"]
TopicUser.where(topic_id: topic.id, user_id: user.id)
.update_all(notification_level: TopicUser.notification_levels[:tracking])
.update_all(notification_level: TopicUser.notification_levels[:tracking])
updated = true
end
if params["unwatch_category"] && topic.category_id
TopicUser.joins(:topic)
.where(:user => user,
:notification_level => TopicUser.notification_levels[:watching],
"topics.category_id" => topic.category_id)
.update_all(notification_level: TopicUser.notification_levels[:tracking])
.where(:user => user,
:notification_level => TopicUser.notification_levels[:watching],
"topics.category_id" => topic.category_id)
.update_all(notification_level: TopicUser.notification_levels[:tracking])
CategoryUser.where(user_id: user.id,
category_id: topic.category_id,
notification_level: CategoryUser.watching_levels
category_id: topic.category_id,
notification_level: CategoryUser.watching_levels
)
.destroy_all
.destroy_all
updated = true
end
if params["mute_topic"]
TopicUser.where(topic_id: topic.id, user_id: user.id)
.update_all(notification_level: TopicUser.notification_levels[:muted])
.update_all(notification_level: TopicUser.notification_levels[:muted])
updated = true
end
end
@@ -90,9 +90,9 @@ class EmailController < ApplicationController
if params["unsubscribe_all"]
user.user_option.update_columns(email_always: false,
email_digests: false,
email_direct: false,
email_private_messages: false)
email_digests: false,
email_direct: false,
email_private_messages: false)
updated = true
end

View File

@@ -74,7 +74,7 @@ class EmbedController < ApplicationController
by_url = {}
if embed_urls.present?
urls = embed_urls.map {|u| u.sub(/#discourse-comments$/, '').sub(/\/$/, '') }
urls = embed_urls.map { |u| u.sub(/#discourse-comments$/, '').sub(/\/$/, '') }
topic_embeds = TopicEmbed.where(embed_url: urls).includes(:topic).references(:topic)
topic_embeds.each do |te|
@@ -88,7 +88,7 @@ class EmbedController < ApplicationController
end
end
render json: {counts: by_url}, callback: params[:callback]
render json: { counts: by_url }, callback: params[:callback]
end
private
@@ -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: {
@@ -274,8 +274,8 @@ class GroupsController < ApplicationController
end
GroupUser.where(group_id: group.id)
.where(user_id: user_id)
.update_all(notification_level: notification_level)
.where(user_id: user_id)
.update_all(notification_level: notification_level)
render json: success_json
end

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')
@@ -81,7 +82,7 @@ class InvitesController < ApplicationController
render json: failed_json, status: 422
end
rescue Invite::UserExists, ActiveRecord::RecordInvalid => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@@ -110,7 +111,7 @@ class InvitesController < ApplicationController
render json: failed_json, status: 422
end
rescue => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@@ -163,7 +164,7 @@ class InvitesController < ApplicationController
data = if extension.downcase == ".csv"
path = Invite.create_csv(file, name)
Jobs.enqueue(:bulk_invite, filename: "#{name}#{extension}", current_user_id: current_user.id)
{url: path}
{ url: path }
else
failed_json.merge(errors: [I18n.t("bulk_invite.file_should_be_csv")])
end

View File

@@ -205,7 +205,7 @@ class ListController < ApplicationController
render 'list', formats: [:rss]
end
def top(options=nil)
def top(options = nil)
options ||= {}
period = ListController.best_period_for(current_user.try(:previous_visit_at), options[:category])
send("top_#{period}", options)
@@ -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)
@@ -362,23 +362,23 @@ class ListController < ApplicationController
else # :next
public_send(method, opts.merge(next_page_params(opts)))
end
url.sub('.json?','?')
url.sub('.json?', '?')
end
def get_excluded_category_ids(current_category=nil)
def get_excluded_category_ids(current_category = nil)
exclude_category_ids = Category.where(suppress_from_homepage: true)
exclude_category_ids = exclude_category_ids.where.not(id: current_category) if current_category
exclude_category_ids.pluck(:id)
end
def self.best_period_for(previous_visit_at, category_id=nil)
def self.best_period_for(previous_visit_at, category_id = nil)
default_period = ((category_id && Category.where(id: category_id).pluck(:default_top_period).first) ||
SiteSetting.top_page_default_timeframe).to_sym
best_period_with_topics_for(previous_visit_at, category_id, default_period) || default_period
end
def self.best_period_with_topics_for(previous_visit_at, category_id=nil, default_period=SiteSetting.top_page_default_timeframe)
def self.best_period_with_topics_for(previous_visit_at, category_id = nil, default_period = SiteSetting.top_page_default_timeframe)
best_periods_for(previous_visit_at, default_period.to_sym).each do |period|
top_topics = TopTopic.where("#{period}_score > 0")
top_topics = top_topics.joins(:topic).where("topics.category_id = ?", category_id) if category_id
@@ -389,12 +389,12 @@ class ListController < ApplicationController
false
end
def self.best_periods_for(date, default_period=:all)
def self.best_periods_for(date, default_period = :all)
date ||= 1.year.ago
periods = []
periods << default_period if :all != default_period
periods << :daily if :daily != default_period && date > 8.days.ago
periods << :weekly if :weekly != default_period && date > 35.days.ago
periods << :daily if :daily != default_period && date > 8.days.ago
periods << :weekly if :weekly != default_period && date > 35.days.ago
periods << :monthly if :monthly != default_period && date > 180.days.ago
periods << :yearly if :yearly != default_period
periods

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

@@ -37,9 +37,9 @@ class NotificationsController < ApplicationController
offset = params[:offset].to_i
notifications = Notification.where(user_id: user.id)
.visible
.includes(:topic)
.order(created_at: :desc)
.visible
.includes(:topic)
.order(created_at: :desc)
total_rows = notifications.dup.count
notifications = notifications.offset(offset).limit(60)

View File

@@ -12,10 +12,9 @@ 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')
.includes(:user)
.order('post_actions.created_at asc')
if !guardian.can_see_post_actors?(post.topic, post_action_type_id)
if !current_user

View File

@@ -41,23 +41,23 @@ class PostsController < ApplicationController
if params[:id] == "private_posts"
raise Discourse::NotFound if current_user.nil?
posts = Post.private_posts
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
rss_description = I18n.t("rss_description.private_posts")
else
posts = Post.public_posts
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
.order(created_at: :desc)
.where('posts.id <= ?', last_post_id)
.where('posts.id > ?', last_post_id - 50)
.includes(topic: :category)
.includes(user: :primary_group)
.includes(:reply_to_user)
.limit(50)
rss_description = I18n.t("rss_description.posts")
end
@@ -92,12 +92,12 @@ class PostsController < ApplicationController
user = fetch_user_from_params
posts = Post.public_posts
.where(user_id: user.id)
.where(post_type: Post.types[:regular])
.order(created_at: :desc)
.includes(:user)
.includes(topic: :category)
.limit(50)
.where(user_id: user.id)
.where(post_type: Post.types[:regular])
.order(created_at: :desc)
.includes(:user)
.includes(topic: :category)
.limit(50)
posts = posts.reject { |post| !guardian.can_see?(post) || post.topic.blank? }
@@ -230,20 +230,20 @@ class PostsController < ApplicationController
RateLimiter.new(current_user, "delete_post", 3, 1.minute).performed! unless current_user.staff?
if too_late_to(:delete_post, post)
render json: {errors: [I18n.t('too_late_to_edit')]}, status: 422
render json: { errors: [I18n.t('too_late_to_edit')] }, status: 422
return
end
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
end
def expand_embed
render json: {cooked: TopicEmbed.expanded_for(find_post_from_params) }
render json: { cooked: TopicEmbed.expanded_for(find_post_from_params) }
rescue
render_json_error I18n.t('errors.embed.load_from_remote')
end
@@ -266,10 +266,10 @@ class PostsController < ApplicationController
raise Discourse::InvalidParameters.new(:post_ids) if posts.blank?
# Make sure we can delete the posts
posts.each {|p| guardian.ensure_can_delete!(p) }
posts.each { |p| guardian.ensure_can_delete!(p) }
Post.transaction do
posts.each {|p| PostDestroyer.new(current_user, p).destroy }
posts.each { |p| PostDestroyer.new(current_user, p).destroy }
end
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
@@ -441,7 +441,7 @@ class PostsController < ApplicationController
limit = [(params[:limit] || 60).to_i, 100].min
posts = user_posts(guardian, user.id, offset: offset, limit: limit)
.where(id: PostAction.where(post_action_type_id: PostActionType.notify_flag_type_ids)
.where(id: PostAction.where(post_action_type_id: PostActionType.notify_flag_type_ids)
.where(disagreed_at: nil)
.select(:post_id))
@@ -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
@@ -529,9 +528,9 @@ class PostsController < ApplicationController
def user_posts(guardian, user_id, opts)
posts = Post.includes(:user, :topic, :deleted_by, :user_actions)
.where(user_id: user_id)
.with_deleted
.order(created_at: :desc)
.where(user_id: user_id)
.with_deleted
.order(created_at: :desc)
if guardian.user.moderator?
@@ -545,7 +544,7 @@ class PostsController < ApplicationController
end
posts.offset(opts[:offset])
.limit(opts[:limit])
.limit(opts[:limit])
end
def create_params
@@ -622,7 +621,7 @@ class PostsController < ApplicationController
"post##" << Digest::SHA1.hexdigest(args
.to_a
.concat([["user", current_user.id]])
.sort{|x,y| x[0] <=> y[0]}.join do |x,y|
.sort { |x, y| x[0] <=> y[0] }.join do |x, y|
"#{x}:#{y}"
end)
end

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

@@ -98,7 +98,7 @@ class SearchController < ApplicationController
search_context = params[:search_context]
unless search_context
if (context = params[:context]) && (id = params[:context_id])
search_context = {type: context, id: id}
search_context = { type: context, id: id }
end
end
@@ -108,7 +108,7 @@ class SearchController < ApplicationController
# A user is found by username
context_obj = nil
if ['user','private_messages'].include? search_context[:type]
if ['user', 'private_messages'].include? search_context[:type]
context_obj = User.find_by(username_lower: search_context[:id].downcase)
elsif 'category' == search_context[:type]
context_obj = Category.find_by(id: search_context[:id].to_i)

View File

@@ -9,7 +9,7 @@ class SessionController < ApplicationController
ACTIVATE_USER_KEY = "activate_user"
def csrf
render json: {csrf: form_authenticity_token }
render json: { csrf: form_authenticity_token }
end
def sso
@@ -35,7 +35,7 @@ class SessionController < ApplicationController
end
end
def sso_provider(payload=nil)
def sso_provider(payload = nil)
payload ||= request.query_string
if SiteSetting.enable_sso_provider
sso = SingleSignOn.parse(payload, SiteSetting.sso_secret)
@@ -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}")
@@ -292,11 +292,11 @@ class SessionController < ApplicationController
end
def invalid_credentials
render json: {error: I18n.t("login.incorrect_username_email_or_password")}
render json: { error: I18n.t("login.incorrect_username_email_or_password") }
end
def login_not_approved
render json: {error: I18n.t("login.not_approved")}
render json: { error: I18n.t("login.not_approved") }
end
def not_activated(user)
@@ -310,19 +310,19 @@ class SessionController < ApplicationController
end
def not_allowed_from_ip_address(user)
render json: {error: I18n.t("login.not_allowed_from_ip_address", username: user.username)}
render json: { error: I18n.t("login.not_allowed_from_ip_address", username: user.username) }
end
def admin_not_allowed_from_ip_address(user)
render json: {error: I18n.t("login.admin_not_allowed_from_ip_address", username: user.username)}
render json: { error: I18n.t("login.admin_not_allowed_from_ip_address", username: user.username) }
end
def failed_to_login(user)
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

@@ -26,7 +26,7 @@ class SimilarTopicsController < ApplicationController
return render json: [] if invalid_length || !Topic.count_exceeds_minimum?
topics = Topic.similar_to(title, raw, current_user).to_a
topics.map! {|t| SimilarTopic.new(t) }
topics.map! { |t| SimilarTopic.new(t) }
render_serialized(topics, SimilarTopicSerializer, root: :similar_topics, rest_serializer: true)
end

View File

@@ -13,9 +13,9 @@ class StaticController < ApplicationController
return redirect_to path('/login') if SiteSetting.login_required? && current_user.nil? && (params[:id] == 'faq' || params[:id] == 'guidelines')
map = {
"faq" => {redirect: "faq_url", topic_id: "guidelines_topic_id"},
"tos" => {redirect: "tos_url", topic_id: "tos_topic_id"},
"privacy" => {redirect: "privacy_policy_url", topic_id: "privacy_topic_id"}
"faq" => { redirect: "faq_url", topic_id: "guidelines_topic_id" },
"tos" => { redirect: "tos_url", topic_id: "tos_topic_id" },
"privacy" => { redirect: "privacy_policy_url", topic_id: "privacy_topic_id" }
}
@page = params[:id]
@@ -100,7 +100,7 @@ class StaticController < ApplicationController
# a huge expiry, we also cache these assets in nginx so it bypassed if needed
def favicon
data = DistributedMemoizer.memoize('favicon' + SiteSetting.favicon_url, 60*30) do
data = DistributedMemoizer.memoize('favicon' + SiteSetting.favicon_url, 60 * 30) do
begin
file = FileHelper.download(
SiteSetting.favicon_url,
@@ -137,21 +137,19 @@ class StaticController < ApplicationController
end
end
def cdn_asset
serve_asset
end
protected
def serve_asset(suffix=nil)
def serve_asset(suffix = nil)
path = File.expand_path(Rails.root + "public/assets/#{params[:path]}#{suffix}")
# 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

@@ -20,7 +20,7 @@ class StepsController < ApplicationController
else
errors = []
updater.errors.messages.each do |field, msg|
errors << {field: field, description: msg.join }
errors << { field: field, description: msg.join }
end
render json: { errors: errors }, status: 422
end

View File

@@ -19,17 +19,17 @@ class StylesheetsController < ApplicationController
no_cookies
target,digest = params[:name].split(/_([a-f0-9]{40})/)
target, digest = params[:name].split(/_([a-f0-9]{40})/)
if !Rails.env.production?
# TODO add theme
# calling this method ensures we have a cache for said target
# we hold of re-compilation till someone asks for asset
if target.include?("theme")
split_target,theme_id = target.split(/_(-?[0-9]+)/)
split_target, theme_id = target.split(/_(-?[0-9]+)/)
theme = Theme.find(theme_id) if theme_id
else
split_target,color_scheme_id = target.split(/_(-?[0-9]+)/)
split_target, color_scheme_id = target.split(/_(-?[0-9]+)/)
theme = Theme.find_by(color_scheme_id: color_scheme_id)
end
Stylesheet::Manager.stylesheet_link_tag(split_target, nil, theme&.key)
@@ -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

@@ -14,18 +14,18 @@ class TagsController < ::ApplicationController
:tag_feed,
:search,
:check_hashtag,
Discourse.anonymous_filters.map { |f| :"show_#{f}"}
Discourse.anonymous_filters.map { |f| :"show_#{f}" }
].flatten
before_filter :set_category_from_params, except: [:index, :update, :destroy, :tag_feed, :search, :notifications, :update_notifications]
def index
categories = Category.where("id in (select category_id from category_tags)")
.where("id in (?)", guardian.allowed_category_ids)
.preload(:tags)
.where("id in (?)", guardian.allowed_category_ids)
.preload(:tags)
category_tag_counts = categories.map do |c|
h = Tag.category_tags_by_count_query(c, limit: 300).count(Tag::COUNT_ARG)
h.merge!(c.tags.where.not(name: h.keys).inject({}) { |sum,t| sum[t.name] = 0; sum }) # unused tags
{id: c.id, tags: self.class.tag_counts_json(h)}
h.merge!(c.tags.where.not(name: h.keys).inject({}) { |sum, t| sum[t.name] = 0; sum }) # unused tags
{ id: c.id, tags: self.class.tag_counts_json(h) }
end
tag_counts = self.class.tags_by_count(guardian, limit: 300).count(Tag::COUNT_ARG)
@@ -91,7 +91,7 @@ class TagsController < ::ApplicationController
tag.name = new_tag_name
if tag.save
StaffActionLogger.new(current_user).log_custom('renamed_tag', previous_value: params[:tag_id], new_value: new_tag_name)
render json: { tag: { id: new_tag_name }}
render json: { tag: { id: new_tag_name } }
else
render_json_error tag.errors.full_messages
end
@@ -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,15 +129,13 @@ 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]
}
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 } }
tags = tags_with_counts.count(Tag::COUNT_ARG).map { |t, c| { id: t, text: t, count: c } }
json_response = { results: tags }
@@ -161,7 +159,7 @@ class TagsController < ::ApplicationController
raise Discourse::NotFound unless tag
level = params[:tag_notification][:notification_level].to_i
TagUser.change(current_user.id, tag.id, level)
render json: {notification_level: level}
render json: { notification_level: level }
end
def check_hashtag
@@ -180,12 +178,12 @@ class TagsController < ::ApplicationController
raise Discourse::NotFound unless SiteSetting.tagging_enabled?
end
def self.tags_by_count(guardian, opts={})
def self.tags_by_count(guardian, opts = {})
guardian.filter_allowed_categories(Tag.tags_by_count_query(opts))
end
def self.tag_counts_json(tag_counts)
tag_counts.map {|t, c| { id: t, text: t, count: c } }
tag_counts.map { |t, c| { id: t, text: t, count: c } }
end
def set_category_from_params
@@ -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
@@ -236,7 +234,7 @@ class TagsController < ::ApplicationController
end
end
def url_method(opts={})
def url_method(opts = {})
if opts[:parent_category] && opts[:category]
"tag_parent_category_category_#{action_name}_path"
elsif opts[:category]
@@ -254,7 +252,7 @@ class TagsController < ::ApplicationController
else # :next
public_send(method, opts.merge(next_page_params(opts)))
end
url.sub('.json?','?')
url.sub('.json?', '?')
end
def build_topic_list_options

View File

@@ -40,7 +40,7 @@ class TopicsController < ApplicationController
topic = Topic.find_by(slug: params[:slug].downcase)
guardian.ensure_can_see!(topic)
raise Discourse::NotFound unless topic
render json: {slug: topic.slug, topic_id: topic.id, url: topic.url}
render json: { slug: topic.slug, topic_id: topic.id, url: topic.url }
end
def show
@@ -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,
@@ -206,17 +206,16 @@ class TopicsController < ApplicationController
guardian.ensure_can_see!(@topic)
@posts = Post.where(hidden: false, deleted_at: nil, topic_id: @topic.id)
.where('posts.id in (?)', post_ids)
.joins("LEFT JOIN users u on u.id = posts.user_id")
.pluck(:id, :cooked, :username)
.map do |post_id, cooked, username|
{
post_id: post_id,
username: username,
excerpt: PrettyText.excerpt(cooked, 800, keep_emoji_images: true)
}
end
.where('posts.id in (?)', post_ids)
.joins("LEFT JOIN users u on u.id = posts.user_id")
.pluck(:id, :cooked, :username)
.map do |post_id, cooked, username|
{
post_id: post_id,
username: username,
excerpt: PrettyText.excerpt(cooked, 800, keep_emoji_images: true)
}
end
render json: @posts.to_json
end
@@ -266,7 +265,7 @@ class TopicsController < ApplicationController
params.require(:enabled)
params.permit(:until)
status = params[:status]
status = params[:status]
topic_id = params[:topic_id].to_i
enabled = params[:enabled] == 'true'
@@ -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
@@ -353,8 +352,8 @@ class TopicsController < ApplicationController
topic = Topic.find(params[:topic_id].to_i)
PostAction.joins(:post)
.where(user_id: current_user.id)
.where('topic_id = ?', topic.id).each do |pa|
.where(user_id: current_user.id)
.where('topic_id = ?', topic.id).each do |pa|
PostAction.remove_act(current_user, pa.post, PostActionType.types[:bookmark])
end
@@ -378,7 +377,7 @@ class TopicsController < ApplicationController
group_ids = current_user.groups.pluck(:id)
if group_ids.present?
allowed_groups = topic.allowed_groups
.where('topic_allowed_groups.group_id IN (?)', group_ids).pluck(:id)
.where('topic_allowed_groups.group_id IN (?)', group_ids).pluck(:id)
allowed_groups.each do |id|
if archive
GroupArchivedMessage.archive!(id, topic.id)
@@ -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]
@@ -505,7 +503,7 @@ class TopicsController < ApplicationController
render json: failed_json, status: 422
end
rescue Topic::UserExists => e
render json: {errors: [e.message]}, status: 422
render json: { errors: [e.message] }, status: 422
end
end
@@ -547,10 +545,10 @@ class TopicsController < ApplicationController
guardian.ensure_can_change_post_owner!
begin
PostOwnerChanger.new( post_ids: params[:post_ids].to_a,
topic_id: params[:topic_id].to_i,
new_owner: User.find_by(username: params[:username]),
acting_user: current_user ).change_owner!
PostOwnerChanger.new(post_ids: params[:post_ids].to_a,
topic_id: params[:topic_id].to_i,
new_owner: User.find_by(username: params[:username]),
acting_user: current_user).change_owner!
render json: success_json
rescue ArgumentError
render json: failed_json, status: 422
@@ -594,8 +592,8 @@ class TopicsController < ApplicationController
current_user,
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?}
(params[:timings] || []).map { |post_number, t| [post_number.to_i, t.to_i] },
mobile: view_context.mobile_view?
)
render nothing: true
end
@@ -608,7 +606,7 @@ class TopicsController < ApplicationController
def bulk
if params[:topic_ids].present?
topic_ids = params[:topic_ids].map {|t| t.to_i}
topic_ids = params[:topic_ids].map { |t| t.to_i }
elsif params[:filter] == 'unread'
tq = TopicQuery.new(current_user)
topics = TopicQuery.unread_filter(tq.joined_topic_user, current_user.id, staff: guardian.is_staff?).listable_topics
@@ -664,7 +662,7 @@ class TopicsController < ApplicationController
params[:slug] && @topic_view.topic.slug != params[:slug]
end
def redirect_to_correct_topic(topic, post_number=nil)
def redirect_to_correct_topic(topic, post_number = nil)
url = topic.relative_url
url << "/#{post_number}" if post_number.to_i > 0
url << ".json" if request.format.json?
@@ -728,9 +726,9 @@ class TopicsController < ApplicationController
def render_topic_changes(dest_topic)
if dest_topic.present?
render json: {success: true, url: dest_topic.relative_url}
render json: { success: true, url: dest_topic.relative_url }
else
render json: {success: false}
render json: { success: false }
end
end

View File

@@ -40,7 +40,7 @@ class UserApiKeysController < ApplicationController
@client_id = params[:client_id]
@auth_redirect = params[:auth_redirect]
@push_url = params[:push_url]
@localized_scopes = params[:scopes].split(",").map{|s| I18n.t("user_api_key.scopes.#{s}")}
@localized_scopes = params[:scopes].split(",").map { |s| I18n.t("user_api_key.scopes.#{s}") }
@scopes = params[:scopes]
rescue Discourse::InvalidAccess
@@ -52,10 +52,10 @@ class UserApiKeysController < ApplicationController
require_params
unless SiteSetting.allowed_user_api_auth_redirects
.split('|')
.any?{|u| params[:auth_redirect] == u}
.split('|')
.any? { |u| params[:auth_redirect] == u }
raise Discourse::InvalidAccess
raise Discourse::InvalidAccess
end
raise Discourse::InvalidAccess unless meets_tl?
@@ -126,7 +126,7 @@ class UserApiKeysController < ApplicationController
:client_id,
:auth_redirect,
:application_name
].each{|p| params.require(p)}
].each { |p| params.require(p) }
end
def validate_params

View File

@@ -89,7 +89,7 @@ class UserAvatarsController < ApplicationController
return render_blank if size < 8 || size > 1000
if !Discourse.avatar_sizes.include?(size) && Discourse.store.external?
closest = Discourse.avatar_sizes.to_a.min { |a,b| (size-a).abs <=> (size-b).abs }
closest = Discourse.avatar_sizes.to_a.min { |a, b| (size - a).abs <=> (size - b).abs }
avatar_url = UserAvatar.local_avatar_url(hostname, user.username_lower, upload_id, closest)
return redirect_to cdn_path(avatar_url)
end

View File

@@ -33,12 +33,12 @@ class UserBadgesController < ApplicationController
if params[:grouped]
user_badges = user_badges.group(:badge_id)
.select(UserBadge.attribute_names.map {|x| "MAX(#{x}) AS #{x}" }, 'COUNT(*) AS "count"')
.select(UserBadge.attribute_names.map { |x| "MAX(#{x}) AS #{x}" }, 'COUNT(*) AS "count"')
end
user_badges = user_badges.includes(badge: [:badge_grouping, :badge_type])
.includes(post: :topic)
.includes(:granted_by)
.includes(post: :topic)
.includes(:granted_by)
render_serialized(user_badges, DetailedUserBadgeSerializer, root: :user_badges)
end
@@ -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

@@ -36,7 +36,7 @@ class Users::OmniauthCallbacksController < ApplicationController
auth[:session] = session
authenticator = self.class.find_authenticator(params[:provider])
provider = Discourse.auth_providers && Discourse.auth_providers.find{|p| p.name == params[:provider]}
provider = Discourse.auth_providers && Discourse.auth_providers.find { |p| p.name == params[:provider] }
@auth_result = authenticator.after_authenticate(auth)
@@ -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

@@ -50,7 +50,7 @@ class UsersController < ApplicationController
topic_id = params[:include_post_count_for].to_i
if topic_id != 0
user_serializer.topic_post_count = {topic_id => Post.where(topic_id: topic_id, user_id: @user.id).count }
user_serializer.topic_post_count = { topic_id => Post.where(topic_id: topic_id, user_id: @user.id).count }
end
if !params[:skip_track_visit] && (@user != current_user)
@@ -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
@@ -224,8 +224,8 @@ class UsersController < ApplicationController
pending_count = Invite.find_pending_invites_count(inviter)
redeemed_count = Invite.find_redeemed_invites_count(inviter)
render json: {counts: { pending: pending_count, redeemed: redeemed_count,
total: (pending_count.to_i + redeemed_count.to_i) } }
render json: { counts: { pending: pending_count, redeemed: redeemed_count,
total: (pending_count.to_i + redeemed_count.to_i) } }
end
def is_local_username
@@ -238,7 +238,7 @@ class UsersController < ApplicationController
Group.mentionable(current_user)
.where(name: usernames)
.pluck(:name, :user_count)
.map{ |name,user_count| {name: name, user_count: user_count} }
.map { |name, user_count| { name: name, user_count: user_count } }
end
usernames -= groups
@@ -250,14 +250,14 @@ class UsersController < ApplicationController
topic_id = params[:topic_id]
unless topic_id.blank?
topic = Topic.find_by(id: topic_id)
usernames.each{ |username| cannot_see.push(username) unless Guardian.new(User.find_by_username(username)).can_see?(topic) }
usernames.each { |username| cannot_see.push(username) unless Guardian.new(User.find_by_username(username)).can_see?(topic) }
end
result = User.where(staged: false)
.where(username_lower: usernames)
.pluck(:username_lower)
.where(username_lower: usernames)
.pluck(:username_lower)
render json: {valid: result, valid_groups: groups, mentionable_groups: mentionable_groups, cannot_see: cannot_see}
render json: { valid: result, valid_groups: groups, mentionable_groups: mentionable_groups, cannot_see: cannot_see }
end
def render_available_true
@@ -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
@@ -385,7 +385,7 @@ class UsersController < ApplicationController
end
def get_honeypot_value
render json: {value: honeypot_value, challenge: challenge_value}
render json: { value: honeypot_value, challenge: challenge_value }
end
def password_reset
@@ -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
@@ -456,7 +456,7 @@ class UsersController < ApplicationController
}
end
else
render json: {is_developer: UsernameCheckerService.is_developer?(@user.email)}
render json: { is_developer: UsernameCheckerService.is_developer?(@user.email) }
end
end
end
@@ -469,14 +469,15 @@ class UsersController < ApplicationController
end
def logon_after_password_reset
message = if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
'password_reset.success'
else
@requires_approval = true
'password_reset.success_unapproved'
end
message =
if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
'password_reset.success'
else
@requires_approval = true
'password_reset.success_unapproved'
end
@success = I18n.t(message)
end
@@ -606,7 +607,7 @@ class UsersController < ApplicationController
User.transaction do
@user.email = params[:email]
if @user.save
@user.email_tokens.create(email: @user.email)
enqueue_activation_email
@@ -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,
@@ -683,8 +683,8 @@ class UsersController < ApplicationController
if params[:include_mentionable_groups] == "true" && current_user
to_render[:groups] = Group.mentionable(current_user)
.where("name ILIKE :term_like", term_like: "#{term}%")
.map do |m|
.where("name ILIKE :term_like", term_like: "#{term}%")
.map do |m|
{ name: m.name, full_name: m.full_name }
end
end
@@ -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
@@ -797,14 +797,14 @@ class UsersController < ApplicationController
private
def honeypot_value
Digest::SHA1::hexdigest("#{Discourse.current_hostname}:#{GlobalSetting.safe_secret_key_base}")[0,15]
Digest::SHA1::hexdigest("#{Discourse.current_hostname}:#{GlobalSetting.safe_secret_key_base}")[0, 15]
end
def challenge_value
challenge = $redis.get('SECRET_CHALLENGE')
unless challenge && challenge.length == 16*2
unless challenge && challenge.length == 16 * 2
challenge = SecureRandom.hex(16)
$redis.set('SECRET_CHALLENGE',challenge)
$redis.set('SECRET_CHALLENGE', challenge)
end
challenge
@@ -833,9 +833,9 @@ class UsersController < ApplicationController
def user_params
result = params.permit(:name, :email, :password, :username, :date_of_birth)
.merge(ip_address: request.remote_ip,
registration_ip_address: request.remote_ip,
locale: user_locale)
.merge(ip_address: request.remote_ip,
registration_ip_address: request.remote_ip,
locale: user_locale)
if !UsernameCheckerService.is_developer?(result['email']) &&
is_api? &&
@@ -845,7 +845,6 @@ class UsersController < ApplicationController
result.merge!(params.permit(:active, :staged))
end
result
end