Rubocop: move dot in multi-line calls to leading position (#9262)

This commit is contained in:
rhymes 2020-07-16 15:51:11 +02:00 committed by GitHub
parent 204fb51f14
commit f1ec04a0c9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
126 changed files with 849 additions and 851 deletions

View file

@ -37,9 +37,7 @@ Layout/ClassStructure:
Layout/DotPosition:
Description: 'Checks the position of the dot in multi-line method calls.'
StyleGuide: '#consistent-multi-line-chains'
# TODO: [@thepracticaldev/oss] enable leading?
EnforcedStyle: trailing
EnforcedStyle: leading
Layout/EmptyLinesAroundAttributeAccessor:
Description: "Keep blank lines around attribute accessors."

View file

@ -41,20 +41,20 @@ module Api
end
def show
@article = Article.published.
includes(:user).
select(SHOW_ATTRIBUTES_FOR_SERIALIZATION).
find(params[:id]).
decorate
@article = Article.published
.includes(:user)
.select(SHOW_ATTRIBUTES_FOR_SERIALIZATION)
.find(params[:id])
.decorate
set_surrogate_key_header @article.record_key
end
def show_by_slug
@article = Article.published.
select(SHOW_ATTRIBUTES_FOR_SERIALIZATION).
find_by!(path: "/#{params[:username]}/#{params[:slug]}").
decorate
@article = Article.published
.select(SHOW_ATTRIBUTES_FOR_SERIALIZATION)
.find_by!(path: "/#{params[:username]}/#{params[:slug]}")
.decorate
set_surrogate_key_header @article.record_key
render "show"
@ -95,13 +95,13 @@ module Api
@user.articles.published
end
@articles = @articles.
includes(:organization).
select(ME_ATTRIBUTES_FOR_SERIALIZATION).
order(published_at: :desc, created_at: :desc).
page(params[:page]).
per(num).
decorate
@articles = @articles
.includes(:organization)
.select(ME_ATTRIBUTES_FOR_SERIALIZATION)
.order(published_at: :desc, created_at: :desc)
.page(params[:page])
.per(num)
.decorate
end
private

View file

@ -11,19 +11,19 @@ module Api
def index
article = Article.find(params[:a_id])
@comments = article.comments.
includes(:user).
select(ATTRIBUTES_FOR_SERIALIZATION).
arrange
@comments = article.comments
.includes(:user)
.select(ATTRIBUTES_FOR_SERIALIZATION)
.arrange
set_surrogate_key_header article.record_key, Comment.table_key, edge_cache_keys(@comments)
end
def show
tree_with_root_comment = Comment.subtree_of(params[:id].to_i(26)).
includes(:user).
select(ATTRIBUTES_FOR_SERIALIZATION).
arrange
tree_with_root_comment = Comment.subtree_of(params[:id].to_i(26))
.includes(:user)
.select(ATTRIBUTES_FOR_SERIALIZATION)
.arrange
# being only one tree we know that the root comment is the first (and only) key
@comment = tree_with_root_comment.keys.first

View file

@ -10,12 +10,12 @@ module Api
private_constant :USERS_ATTRIBUTES_FOR_SERIALIZATION
def users
@follows = Follow.followable_user(@user.id).
includes(:follower).
select(USERS_ATTRIBUTES_FOR_SERIALIZATION).
order(created_at: :desc).
page(params[:page]).
per(@follows_limit)
@follows = Follow.followable_user(@user.id)
.includes(:follower)
.select(USERS_ATTRIBUTES_FOR_SERIALIZATION)
.order(created_at: :desc)
.page(params[:page])
.per(@follows_limit)
end
private

View file

@ -22,9 +22,9 @@ module Api
private_constant :ATTRIBUTES_FOR_SERIALIZATION
def index
@listings = Listing.published.
select(ATTRIBUTES_FOR_SERIALIZATION).
includes(:user, :organization, :taggings, :listing_category)
@listings = Listing.published
.select(ATTRIBUTES_FOR_SERIALIZATION)
.includes(:user, :organization, :taggings, :listing_category)
if params[:category].present?
@listings = @listings.in_category(params[:category])

View file

@ -15,10 +15,10 @@ module Api
relation = PodcastEpisode.includes(:podcast).reachable
end
@podcast_episodes = relation.
select(:id, :slug, :title, :podcast_id).
order(published_at: :desc).
page(page).per(num)
@podcast_episodes = relation
.select(:id, :slug, :title, :podcast_id)
.order(published_at: :desc)
.page(page).per(num)
set_surrogate_key_header PodcastEpisode.table_key, @podcast_episodes.map(&:record_key)
end

View file

@ -11,9 +11,9 @@ module Api
per_page = (params[:per_page] || 10).to_i
num = [per_page, 1000].min
@tags = Tag.select(ATTRIBUTES_FOR_SERIALIZATION).
order(taggings_count: :desc).
page(page).per(num)
@tags = Tag.select(ATTRIBUTES_FOR_SERIALIZATION)
.order(taggings_count: :desc)
.page(page).per(num)
set_surrogate_key_header Tag.table_key, @tags.map(&:record_key)
end

View file

@ -13,11 +13,11 @@ module Api
per_page = (params[:per_page] || 24).to_i
num = [per_page, 1000].min
@video_articles = Article.with_video.
includes([:user]).
select(INDEX_ATTRIBUTES_FOR_SERIALIZATION).
order(hotness_score: :desc).
page(page).per(num)
@video_articles = Article.with_video
.includes([:user])
.select(INDEX_ATTRIBUTES_FOR_SERIALIZATION)
.order(hotness_score: :desc)
.page(page).per(num)
set_surrogate_key_header "videos", Article.table_key, @video_articles.map(&:record_key)
end

View file

@ -9,8 +9,8 @@ class BufferedArticlesController < ApplicationController
def buffered_articles_urls
relation = if Rails.env.production?
Article.where("last_buffered > ?", 24.hours.ago).
or(Article.where("published_at > ?", 20.minutes.ago))
Article.where("last_buffered > ?", 24.hours.ago)
.or(Article.where("published_at > ?", 20.minutes.ago))
else
Article.all
end

View file

@ -163,10 +163,10 @@ class ChatChannelMembershipsController < ApplicationController
"joined",
)
NotifyMailer.
with(membership: @chat_channel_membership, inviter: @chat_channel_membership.user).
channel_invite_email.
deliver_later
NotifyMailer
.with(membership: @chat_channel_membership, inviter: @chat_channel_membership.user)
.channel_invite_email
.deliver_later
notice = "Accepted request of #{@chat_channel_membership.user.username} to join #{channel_name}."
end

View file

@ -26,11 +26,11 @@ class ChatChannelsController < ApplicationController
end
def show
@chat_messages = @chat_channel.messages.
includes(:user).
order(created_at: :desc).
offset(params[:message_offset]).
limit(50)
@chat_messages = @chat_channel.messages
.includes(:user)
.order(created_at: :desc)
.offset(params[:message_offset])
.limit(50)
end
def create
@ -147,9 +147,9 @@ class ChatChannelsController < ApplicationController
skip_authorization
@chat_channel =
ChatChannel.
select(CHANNEL_ATTRIBUTES_FOR_SERIALIZATION).
find_by(id: params[:id])
ChatChannel
.select(CHANNEL_ATTRIBUTES_FOR_SERIALIZATION)
.find_by(id: params[:id])
return if @chat_channel&.has_member?(current_user)
@ -169,12 +169,12 @@ class ChatChannelsController < ApplicationController
def render_unopened_json_response
@chat_channels_memberships = if session_current_user_id
ChatChannelMembership.where(user_id: session_current_user_id).
where(has_unopened_messages: true).
where(show_global_badge_notification: true).
where.not(status: %w[removed_from_channel left_channel]).
includes(%i[chat_channel user]).
order("chat_channel_memberships.updated_at DESC")
ChatChannelMembership.where(user_id: session_current_user_id)
.where(has_unopened_messages: true)
.where(show_global_badge_notification: true)
.where.not(status: %w[removed_from_channel left_channel])
.includes(%i[chat_channel user])
.order("chat_channel_memberships.updated_at DESC")
else
[]
end
@ -183,10 +183,10 @@ class ChatChannelsController < ApplicationController
def render_pending_json_response
@chat_channels_memberships = if current_user
current_user.
chat_channel_memberships.includes(:chat_channel).
where(status: "pending").
order("chat_channel_memberships.updated_at DESC")
current_user
.chat_channel_memberships.includes(:chat_channel)
.where(status: "pending")
.order("chat_channel_memberships.updated_at DESC")
else
[]
end
@ -194,25 +194,25 @@ class ChatChannelsController < ApplicationController
end
def render_unopened_ids_response
@unopened_ids = ChatChannelMembership.where(user_id: session_current_user_id).includes(:chat_channel).
where(has_unopened_messages: true).where.not(status: %w[removed_from_channel
left_channel]).pluck(:chat_channel_id)
@unopened_ids = ChatChannelMembership.where(user_id: session_current_user_id).includes(:chat_channel)
.where(has_unopened_messages: true).where.not(status: %w[removed_from_channel
left_channel]).pluck(:chat_channel_id)
render json: { unopened_ids: @unopened_ids }
end
def render_joining_request_json_response
requested_memberships_id = current_user.
chat_channel_memberships.
includes(:chat_channel).
where(chat_channels: { discoverable: true }, role: "mod").
pluck(:chat_channel_id).
map { |membership_id| ChatChannel.find_by(id: membership_id).requested_memberships }.
flatten.
map(&:id)
requested_memberships_id = current_user
.chat_channel_memberships
.includes(:chat_channel)
.where(chat_channels: { discoverable: true }, role: "mod")
.pluck(:chat_channel_id)
.map { |membership_id| ChatChannel.find_by(id: membership_id).requested_memberships }
.flatten
.map(&:id)
@chat_channels_memberships = ChatChannelMembership.
includes(%i[user chat_channel]).
where(id: requested_memberships_id)
@chat_channels_memberships = ChatChannelMembership
.includes(%i[user chat_channel])
.where(id: requested_memberships_id)
render "index.json"
end

View file

@ -35,28 +35,28 @@ class DashboardsController < ApplicationController
end
def following_tags
@followed_tags = @user.follows_by_type("ActsAsTaggableOn::Tag").
order("points DESC").includes(:followable).limit(@follows_limit)
@followed_tags = @user.follows_by_type("ActsAsTaggableOn::Tag")
.order("points DESC").includes(:followable).limit(@follows_limit)
end
def following_users
@follows = @user.follows_by_type("User").
order("created_at DESC").includes(:followable).limit(@follows_limit)
@follows = @user.follows_by_type("User")
.order("created_at DESC").includes(:followable).limit(@follows_limit)
end
def following_organizations
@followed_organizations = @user.follows_by_type("Organization").
order("created_at DESC").includes(:followable).limit(@follows_limit)
@followed_organizations = @user.follows_by_type("Organization")
.order("created_at DESC").includes(:followable).limit(@follows_limit)
end
def following_podcasts
@followed_podcasts = @user.follows_by_type("Podcast").
order("created_at DESC").includes(:followable).limit(@follows_limit)
@followed_podcasts = @user.follows_by_type("Podcast")
.order("created_at DESC").includes(:followable).limit(@follows_limit)
end
def followers
@follows = Follow.followable_user(@user.id).
includes(:follower).order("created_at DESC").limit(@follows_limit)
@follows = Follow.followable_user(@user.id)
.includes(:follower).order("created_at DESC").limit(@follows_limit)
end
def pro
@ -73,8 +73,8 @@ class DashboardsController < ApplicationController
def subscriptions
authorize @source
@subscriptions = @source.user_subscriptions.
includes(:subscriber).order(created_at: :desc).page(params[:page]).per(100)
@subscriptions = @source.user_subscriptions
.includes(:subscriber).order(created_at: :desc).page(params[:page]).per(100)
end
private

View file

@ -6,30 +6,30 @@ class FollowingsController < ApplicationController
TAGS_ATTRIBUTES_FOR_SERIALIZATION = [*ATTRIBUTES_FOR_SERIALIZATION, :points].freeze
def users
relation = current_user.follows_by_type("User").
select(ATTRIBUTES_FOR_SERIALIZATION).
order(created_at: :desc)
relation = current_user.follows_by_type("User")
.select(ATTRIBUTES_FOR_SERIALIZATION)
.order(created_at: :desc)
@follows = load_follows_and_paginate(relation)
end
def tags
relation = current_user.follows_by_type("ActsAsTaggableOn::Tag").
select(TAGS_ATTRIBUTES_FOR_SERIALIZATION).
order(points: :desc)
relation = current_user.follows_by_type("ActsAsTaggableOn::Tag")
.select(TAGS_ATTRIBUTES_FOR_SERIALIZATION)
.order(points: :desc)
@followed_tags = load_follows_and_paginate(relation)
end
def organizations
relation = current_user.follows_by_type("Organization").
select(ATTRIBUTES_FOR_SERIALIZATION).
order(created_at: :desc)
relation = current_user.follows_by_type("Organization")
.select(ATTRIBUTES_FOR_SERIALIZATION)
.order(created_at: :desc)
@followed_organizations = load_follows_and_paginate(relation)
end
def podcasts
relation = current_user.follows_by_type("Podcast").
select(ATTRIBUTES_FOR_SERIALIZATION).
order(created_at: :desc)
relation = current_user.follows_by_type("Podcast")
.select(ATTRIBUTES_FOR_SERIALIZATION)
.order(created_at: :desc)
@followed_podcasts = load_follows_and_paginate(relation)
end

View file

@ -52,70 +52,70 @@ module Internal
private
def articles_not_buffered(days_ago)
Article.published.
where(last_buffered: nil).
where("published_at > ? OR crossposted_at > ?", days_ago.days.ago, days_ago.days.ago).
includes(:user).
limited_columns_internal_select.
order("public_reactions_count DESC").
page(params[:page]).
per(50)
Article.published
.where(last_buffered: nil)
.where("published_at > ? OR crossposted_at > ?", days_ago.days.ago, days_ago.days.ago)
.includes(:user)
.limited_columns_internal_select
.order("public_reactions_count DESC")
.page(params[:page])
.per(50)
end
def articles_top(months_ago)
Article.published.
where("published_at > ?", months_ago).
includes(user: [:notes]).
limited_columns_internal_select.
order("public_reactions_count DESC").
page(params[:page]).
per(50)
Article.published
.where("published_at > ?", months_ago)
.includes(user: [:notes])
.limited_columns_internal_select
.order("public_reactions_count DESC")
.page(params[:page])
.per(50)
end
def articles_satellite
Article.published.where(last_buffered: nil).
includes(:user, :buffer_updates).
tagged_with(Tag.bufferized_tags, any: true).
limited_columns_internal_select.
order("hotness_score DESC").
page(params[:page]).
per(60)
Article.published.where(last_buffered: nil)
.includes(:user, :buffer_updates)
.tagged_with(Tag.bufferized_tags, any: true)
.limited_columns_internal_select
.order("hotness_score DESC")
.page(params[:page])
.per(60)
end
def articles_boosted_additional
Article.boosted_via_additional_articles.
includes(:user, :buffer_updates).
limited_columns_internal_select.
order("published_at DESC").
page(params[:page]).
per(100)
Article.boosted_via_additional_articles
.includes(:user, :buffer_updates)
.limited_columns_internal_select
.order("published_at DESC")
.page(params[:page])
.per(100)
end
def articles_chronological
Article.published.
includes(user: [:notes]).
limited_columns_internal_select.
order("published_at DESC").
page(params[:page]).
per(50)
Article.published
.includes(user: [:notes])
.limited_columns_internal_select
.order("published_at DESC")
.page(params[:page])
.per(50)
end
def articles_mixed
Article.published.
includes(user: [:notes]).
limited_columns_internal_select.
order("hotness_score DESC").
page(params[:page]).
per(30)
Article.published
.includes(user: [:notes])
.limited_columns_internal_select
.order("hotness_score DESC")
.page(params[:page])
.per(30)
end
def articles_featured
Article.published.or(Article.where(published_from_feed: true)).
where(featured: true).
where("featured_number > ?", Time.current.to_i).
includes(:user, :buffer_updates).
limited_columns_internal_select.
order("featured_number DESC")
Article.published.or(Article.where(published_from_feed: true))
.where(featured: true)
.where("featured_number > ?", Time.current.to_i)
.includes(:user, :buffer_updates)
.limited_columns_internal_select
.order("featured_number DESC")
end
def article_params

View file

@ -4,18 +4,18 @@ module Internal
def index
@comments = if params[:state]&.start_with?("toplast-")
Comment.
includes(:user).
includes(:commentable).
order("public_reactions_count DESC").
where("created_at > ?", params[:state].split("-").last.to_i.days.ago).
page(params[:page] || 1).per(50)
Comment
.includes(:user)
.includes(:commentable)
.order("public_reactions_count DESC")
.where("created_at > ?", params[:state].split("-").last.to_i.days.ago)
.page(params[:page] || 1).per(50)
else
Comment.
includes(:user).
includes(:commentable).
order("created_at DESC").
page(params[:page] || 1).per(50)
Comment
.includes(:user)
.includes(:commentable)
.order("created_at DESC")
.page(params[:page] || 1).per(50)
end
end

View file

@ -3,29 +3,29 @@ module Internal
layout "internal"
def index
@q = FeedbackMessage.includes(:reporter, :offender, :affected).
order(created_at: :desc).
ransack(params[:q])
@q = FeedbackMessage.includes(:reporter, :offender, :affected)
.order(created_at: :desc)
.ransack(params[:q])
@feedback_messages = @q.result.page(params[:page] || 1).per(5)
@feedback_type = params[:state] || "abuse-reports"
@status = params[:status] || "Open"
@email_messages = EmailMessage.find_for_reports(@feedback_messages)
@new_articles = Article.published.select(:title, :user_id, :path).includes(:user).
order(created_at: :desc).
where("score > ? AND score < ?", -10, 8).
limit(120)
@new_articles = Article.published.select(:title, :user_id, :path).includes(:user)
.order(created_at: :desc)
.where("score > ? AND score < ?", -10, 8)
.limit(120)
@possible_spam_users = User.registered.where(
"github_created_at > ? OR twitter_created_at > ? OR length(name) > ?",
50.hours.ago, 50.hours.ago, 30
).
where("created_at > ?", 48.hours.ago).
order(created_at: :desc).
select(:username, :name, :id).
where.not("username LIKE ?", "%spam_%").
limit(150)
)
.where("created_at > ?", 48.hours.ago)
.order(created_at: :desc)
.select(:username, :name, :id)
.where.not("username LIKE ?", "%spam_%")
.limit(150)
@vomits = get_vomits
end
@ -81,9 +81,9 @@ module Internal
private
def get_vomits
q = Reaction.includes(:user, :reactable).
select(:id, :user_id, :reactable_type, :reactable_id).
order(updated_at: :desc)
q = Reaction.includes(:user, :reactable)
.select(:id, :user_id, :reactable_type, :reactable_id)
.order(updated_at: :desc)
if params[:status] == "Open" || params[:status].blank?
q.where(category: "vomit", status: "valid")
elsif params[:status] == "Resolved"

View file

@ -8,8 +8,8 @@ module Internal
def index
@listings =
Listing.includes(%i[user listing_category]).
page(params[:page]).order("bumped_at DESC").per(50)
Listing.includes(%i[user listing_category])
.page(params[:page]).order("bumped_at DESC").per(50)
@listings = @listings.published unless include_unpublished?
@listings = @listings.in_category(params[:filter]) if params[:filter].present?

View file

@ -3,11 +3,11 @@ module Internal
layout "internal"
def index
@q = AuditLog.
includes(:user).
where(category: "moderator.audit.log").
order(created_at: :desc).
ransack(params[:q])
@q = AuditLog
.includes(:user)
.where(category: "moderator.audit.log")
.order(created_at: :desc)
.ransack(params[:q])
@moderator_actions = @q.result.page(params[:page] || 1).per(25)
end
end

View file

@ -3,11 +3,11 @@ module Internal
layout "internal"
def index
@users = User.with_role(:admin).
union(User.with_role(:super_admin)).
union(User.with_role(:single_resource_admin, :any)).
page(params[:page]).
per(50)
@users = User.with_role(:admin)
.union(User.with_role(:super_admin))
.union(User.with_role(:single_resource_admin, :any))
.page(params[:page])
.per(50)
end
end
end

View file

@ -6,10 +6,10 @@ module Internal
before_action :find_user, only: %i[remove_admin add_admin]
def index
@podcasts = Podcast.left_outer_joins(:podcast_episodes).
select("podcasts.*, count(podcast_episodes) as episodes_count").
group("podcasts.id").order("podcasts.created_at DESC").
page(params[:page]).per(50)
@podcasts = Podcast.left_outer_joins(:podcast_episodes)
.select("podcasts.*, count(podcast_episodes) as episodes_count")
.group("podcasts.id").order("podcasts.created_at DESC")
.page(params[:page]).per(50)
return if params[:search].blank?

View file

@ -5,12 +5,12 @@ module Internal
PRIVILEGED_REACTION_CATEGORIES = %i[thumbsup thumbsdown vomit].freeze
def index
@q = Reaction.
includes(:user,
:reactable).
where("category IN (?)", PRIVILEGED_REACTION_CATEGORIES).
order("reactions.created_at DESC").
ransack(params[:q])
@q = Reaction
.includes(:user,
:reactable)
.where("category IN (?)", PRIVILEGED_REACTION_CATEGORIES)
.order("reactions.created_at DESC")
.ransack(params[:q])
@privileged_reactions = @q.result.page(params[:page] || 1).per(25)
end
end

View file

@ -21,13 +21,13 @@ module Internal
@user = User.find(params[:id])
@organizations = @user.organizations.order(:name)
@notes = @user.notes.order(created_at: :desc).limit(10)
@organization_memberships = @user.organization_memberships.
joins(:organization).
order("organizations.name ASC").
includes(:organization)
@last_email_verification_date = @user.email_authorizations.
where.not(verified_at: nil).
order("created_at DESC").first&.verified_at || "Never"
@organization_memberships = @user.organization_memberships
.joins(:organization)
.order("organizations.name ASC")
.includes(:organization)
@last_email_verification_date = @user.email_authorizations
.where.not(verified_at: nil)
.order("created_at DESC").first&.verified_at || "Never"
end
def update

View file

@ -3,9 +3,9 @@ module Internal
layout "internal"
def index
@endpoints = Webhook::Endpoint.includes(:user).
page(params[:page]).per(50).
order("created_at desc")
@endpoints = Webhook::Endpoint.includes(:user)
.page(params[:page]).per(50)
.order("created_at desc")
end
end
end

View file

@ -38,10 +38,10 @@ class ListingsController < ApplicationController
@listings =
if params[:category].blank?
published_listings.
order("bumped_at DESC").
includes(:user, :organization, :taggings).
limit(12)
published_listings
.order("bumped_at DESC")
.includes(:user, :organization, :taggings)
.limit(12)
else
Listing.none
end
@ -74,13 +74,13 @@ class ListingsController < ApplicationController
end
def dashboard
listings = current_user.listings.
includes(:organization, :taggings)
listings = current_user.listings
.includes(:organization, :taggings)
@listings_json = listings.to_json(DASHBOARD_JSON_OPTIONS)
organizations_ids = current_user.organization_memberships.
where(type_of_user: "admin").
pluck(:organization_id)
organizations_ids = current_user.organization_memberships
.where(type_of_user: "admin")
.pluck(:organization_id)
orgs = Organization.where(id: organizations_ids)
@orgs_json = orgs.to_json(only: %i[id name slug unspent_credits_count])
org_listings = Listing.where(organization_id: organizations_ids)

View file

@ -12,9 +12,9 @@ class ModerationsController < ApplicationController
skip_authorization
return unless current_user&.trusted
articles = Article.published.
where("score > -5 AND score < 5").
order("published_at DESC").limit(70)
articles = Article.published
.where("score > -5 AND score < 5")
.order("published_at DESC").limit(70)
articles = articles.cached_tagged_with(params[:tag]) if params[:tag].present?
if params[:state] == "new-authors"
articles = articles.where("nth_published_by_author > 0 AND nth_published_by_author < 4 AND published_at > ?",

View file

@ -2,8 +2,8 @@ class NotificationSubscriptionsController < ApplicationController
def show
result = if current_user
NotificationSubscription.where(user_id: current_user.id, notifiable_id: params[:notifiable_id],
notifiable_type: params[:notifiable_type]).
first&.to_json(only: %i[config]) || { config: "not_subscribed" }
notifiable_type: params[:notifiable_type])
.first&.to_json(only: %i[config]) || { config: "not_subscribed" }
end
respond_to do |format|
format.json { render json: result }

View file

@ -87,8 +87,8 @@ class OrganizationsController < ApplicationController
end
def organization_params
params.require(:organization).permit(permitted_params).
transform_values do |value|
params.require(:organization).permit(permitted_params)
.transform_values do |value|
if value.class.name == "String"
ActionController::Base.helpers.strip_tags(value)
else

View file

@ -56,12 +56,12 @@ class PageViewsController < ApplicationMetalController
organic_count)
end
organic_count_past_week_count = page_views_from_google_com.
where("created_at > ?", 1.week.ago).sum(:counts_for_number_of_views)
organic_count_past_week_count = page_views_from_google_com
.where("created_at > ?", 1.week.ago).sum(:counts_for_number_of_views)
@article.update_column(:organic_page_views_past_week_count, organic_count_past_week_count)
organic_count_past_month_count = page_views_from_google_com.
where("created_at > ?", 1.month.ago).sum(:counts_for_number_of_views)
organic_count_past_month_count = page_views_from_google_com
.where("created_at > ?", 1.month.ago).sum(:counts_for_number_of_views)
@article.update_column(:organic_page_views_past_month_count, organic_count_past_month_count)
end
end

View file

@ -94,11 +94,11 @@ class PagesController < ApplicationController
def checkin
daily_thread =
Article.
published.
where(user: User.find_by(username: "codenewbiestaff")).
order("articles.published_at" => :desc).
first
Article
.published
.where(user: User.find_by(username: "codenewbiestaff"))
.order("articles.published_at" => :desc)
.first
if daily_thread
redirect_to daily_thread.path

View file

@ -6,9 +6,9 @@ class PodcastEpisodesController < ApplicationController
@podcast_index = true
@podcasts = Podcast.available.order("title asc")
@podcast_episodes = PodcastEpisodeDecorator.decorate_collection(PodcastEpisode.
available.
includes(:podcast).order("published_at desc").first(20))
@podcast_episodes = PodcastEpisodeDecorator.decorate_collection(PodcastEpisode
.available
.includes(:podcast).order("published_at desc").first(20))
if params[:q].blank?
surrogate_keys = ["podcast_episodes_all"] + @podcast_episodes.map(&:record_key)

View file

@ -13,8 +13,8 @@ class ReactionsController < ApplicationController
id = params[:article_id]
reactions = if session_current_user_id
Reaction.public_category.
where(
Reaction.public_category
.where(
reactable_id: id,
reactable_type: "Article",
user_id: session_current_user_id,
@ -25,9 +25,9 @@ class ReactionsController < ApplicationController
result = { article_reaction_counts: Reaction.count_for_article(id) }
else
comments = Comment.
where(commentable_id: params[:commentable_id], commentable_type: params[:commentable_type]).
select(%i[id public_reactions_count])
comments = Comment
.where(commentable_id: params[:commentable_id], commentable_type: params[:commentable_type])
.select(%i[id public_reactions_count])
reaction_counts = comments.map do |comment|
{ id: comment.id, count: comment.public_reactions_count }

View file

@ -12,9 +12,9 @@ class SitemapsController < ApplicationController
not_found
end
@articles = Article.published.
where("published_at > ? AND published_at < ? AND score > ?", date, date.end_of_month, 3).
pluck(:path, :last_comment_at)
@articles = Article.published
.where("published_at > ? AND published_at < ? AND score > ?", date, date.end_of_month, 3)
.pluck(:path, :last_comment_at)
set_surrogate_controls(date)
set_cache_control_headers(@max_age,

View file

@ -8,10 +8,10 @@ class SocialPreviewsController < ApplicationController
@tag_badges = Badge.where(id: Tag.where(name: @article.decorate.cached_tag_list_array).pluck(:badge_id))
not_found unless @article.published
template = @article.tags.
where.not(social_preview_template: nil).
where.not(social_preview_template: "article").
select(:social_preview_template).first&.social_preview_template
template = @article.tags
.where.not(social_preview_template: nil)
.where.not(social_preview_template: "article")
.select(:social_preview_template).first&.social_preview_template
# make sure that the template exists
template = "article" unless Tag.social_preview_templates.include?(template)

View file

@ -63,15 +63,15 @@ class StoriesController < ApplicationController
def assign_hero_html
return if SiteConfig.campaign_hero_html_variant_name.blank?
@hero_area = HtmlVariant.relevant.select(:name, :html).
find_by(group: "campaign", name: SiteConfig.campaign_hero_html_variant_name)
@hero_area = HtmlVariant.relevant.select(:name, :html)
.find_by(group: "campaign", name: SiteConfig.campaign_hero_html_variant_name)
@hero_html = @hero_area&.html
end
def get_latest_campaign_articles
campaign_articles_scope = Article.tagged_with(SiteConfig.campaign_featured_tags, any: true).
where("published_at > ? AND score > ?", 4.weeks.ago, 0).
order("hotness_score DESC")
campaign_articles_scope = Article.tagged_with(SiteConfig.campaign_featured_tags, any: true)
.where("published_at > ? AND score > ?", 4.weeks.ago, 0)
.order("hotness_score DESC")
requires_approval = SiteConfig.campaign_articles_require_approval?
campaign_articles_scope = campaign_articles_scope.where(approved: true) if requires_approval
@ -143,8 +143,8 @@ class StoriesController < ApplicationController
cached_tagged_count
end
@number_of_articles = user_signed_in? ? 5 : SIGNED_OUT_RECORD_COUNT
@stories = Articles::Feed.new(number_of_articles: @number_of_articles, tag: @tag, page: @page).
published_articles_by_tag
@stories = Articles::Feed.new(number_of_articles: @number_of_articles, tag: @tag, page: @page)
.published_articles_by_tag
@stories = @stories.where(approved: true) if @tag_model&.requires_approval
@ -194,17 +194,17 @@ class StoriesController < ApplicationController
def handle_podcast_index
@podcast_index = true
@list_of = "podcast-episodes"
@podcast_episodes = @podcast.podcast_episodes.
reachable.order("published_at DESC").limit(30).decorate
@podcast_episodes = @podcast.podcast_episodes
.reachable.order("published_at DESC").limit(30).decorate
set_surrogate_key_header "podcast_episodes"
render template: "podcast_episodes/index"
end
def handle_organization_index
@user = @organization
@stories = ArticleDecorator.decorate_collection(@organization.articles.published.
limited_column_select.
order("published_at DESC").page(@page).per(8))
@stories = ArticleDecorator.decorate_collection(@organization.articles.published
.limited_column_select
.order("published_at DESC").page(@page).per(8))
@organization_article_index = true
set_organization_json_ld
set_surrogate_key_header "articles-org-#{@organization.id}"
@ -288,9 +288,9 @@ class StoriesController < ApplicationController
# we need to make sure that articles that were cross posted after their
# original publication date appear in the correct order in the collection,
# considering non cross posted articles with a more recent publication date
@collection_articles = @article.collection.articles.
published.
order(Arel.sql("COALESCE(crossposted_at, published_at) ASC"))
@collection_articles = @article.collection.articles
.published
.order(Arel.sql("COALESCE(crossposted_at, published_at) ASC"))
end
@comments_to_show_count = @article.cached_tag_list_array.include?("discuss") ? 50 : 30
@ -313,21 +313,21 @@ class StoriesController < ApplicationController
def assign_user_comments
comment_count = params[:view] == "comments" ? 250 : 8
@comments = if @user.comments_count.positive?
@user.comments.where(deleted: false).
order("created_at DESC").includes(:commentable).limit(comment_count)
@user.comments.where(deleted: false)
.order("created_at DESC").includes(:commentable).limit(comment_count)
else
[]
end
end
def assign_user_stories
@pinned_stories = Article.published.where(id: @user.profile_pins.select(:pinnable_id)).
limited_column_select.
order("published_at DESC").decorate
@stories = ArticleDecorator.decorate_collection(@user.articles.published.
limited_column_select.
where.not(id: @pinned_stories.pluck(:id)).
order("published_at DESC").page(@page).per(user_signed_in? ? 2 : SIGNED_OUT_RECORD_COUNT))
@pinned_stories = Article.published.where(id: @user.profile_pins.select(:pinnable_id))
.limited_column_select
.order("published_at DESC").decorate
@stories = ArticleDecorator.decorate_collection(@user.articles.published
.limited_column_select
.where.not(id: @pinned_stories.pluck(:id))
.order("published_at DESC").page(@page).per(user_signed_in? ? 2 : SIGNED_OUT_RECORD_COUNT))
end
def assign_user_github_repositories
@ -336,8 +336,8 @@ class StoriesController < ApplicationController
def stories_by_timeframe
if %w[week month year infinity].include?(params[:timeframe])
@stories.where("published_at > ?", Timeframer.new(params[:timeframe]).datetime).
order("public_reactions_count DESC")
@stories.where("published_at > ?", Timeframer.new(params[:timeframe]).datetime)
.order("public_reactions_count DESC")
elsif params[:timeframe] == "latest"
@stories.where("score > ?", -20).order("published_at DESC")
else
@ -349,11 +349,11 @@ class StoriesController < ApplicationController
return unless user_signed_in?
num_hours = Rails.env.production? ? 24 : 2400
@podcast_episodes = PodcastEpisode.
includes(:podcast).
order("published_at desc").
where("published_at > ?", num_hours.hours.ago).
select(:slug, :title, :podcast_id, :image)
@podcast_episodes = PodcastEpisode
.includes(:podcast)
.order("published_at desc")
.where("published_at > ?", num_hours.hours.ago)
.select(:slug, :title, :podcast_id, :image)
end
def assign_listings

View file

@ -37,8 +37,8 @@ class TagsController < ApplicationController
def onboarding
skip_authorization
@tags = Tag.where(name: SiteConfig.suggested_tags).
select(ATTRIBUTES_FOR_SERIALIZATION)
@tags = Tag.where(name: SiteConfig.suggested_tags)
.select(ATTRIBUTES_FOR_SERIALIZATION)
set_surrogate_key_header Tag.table_key, @tags.map(&:record_key)
end

View file

@ -6,11 +6,11 @@ class VideosController < ApplicationController
def new; end
def index
@video_articles = Article.with_video.
includes([:user]).
select(:id, :video, :path, :title, :video_thumbnail_url, :user_id, :video_duration_in_seconds).
order("hotness_score DESC").
page(params[:page].to_i).per(24)
@video_articles = Article.with_video
.includes([:user])
.select(:id, :video, :path, :title, :video_thumbnail_url, :user_id, :video_duration_in_seconds)
.order("hotness_score DESC")
.page(params[:page].to_i).per(24)
set_surrogate_key_header "videos", Article.table_key, @video_articles.map(&:record_key)
end

View file

@ -28,21 +28,21 @@ class ArticleSuggester
def other_suggestions(max: 4, ids_to_ignore: [])
ids_to_ignore << article.id
Article.published.
where.not(id: ids_to_ignore).
where.not(user_id: article.user_id).
order("hotness_score DESC").
offset(rand(0..offset)).
first(max)
Article.published
.where.not(id: ids_to_ignore)
.where.not(user_id: article.user_id)
.order("hotness_score DESC")
.offset(rand(0..offset))
.first(max)
end
def suggestions_by_tag(max: 4)
Article.published.tagged_with(cached_tag_list_array, any: true).
where.not(user_id: article.user_id).
where("organic_page_views_past_month_count > 5").
order("hotness_score DESC").
offset(rand(0..offset)).
first(max)
Article.published.tagged_with(cached_tag_list_array, any: true)
.where.not(user_id: article.user_id)
.where("organic_page_views_past_month_count > 5")
.order("hotness_score DESC")
.offset(rand(0..offset))
.first(max)
end
def offset

View file

@ -18,9 +18,9 @@ module AssignTagModerator
add_trusted_role(user)
add_to_chat_channels(user, tag)
NotifyMailer.with(user: user, tag: tag, channel_slug: chat_channel_slug(tag)).
tag_moderator_confirmation_email.
deliver_now
NotifyMailer.with(user: user, tag: tag, channel_slug: chat_channel_slug(tag))
.tag_moderator_confirmation_email
.deliver_now
end
end

View file

@ -53,12 +53,12 @@ module BadgeRewarder
def self.award_tag_badges
Tag.where.not(badge_id: nil).find_each do |tag|
past_winner_user_ids = BadgeAchievement.where(badge_id: tag.badge_id).pluck(:user_id)
winning_article = Article.where("score > 100").
published.
where.not(user_id: past_winner_user_ids).
order(score: :desc).
where("published_at > ?", 7.5.days.ago). # More than seven days, to have some wiggle room.
cached_tagged_with(tag).first
winning_article = Article.where("score > 100")
.published
.where.not(user_id: past_winner_user_ids)
.order(score: :desc)
.where("published_at > ?", 7.5.days.ago) # More than seven days, to have some wiggle room.
.cached_tagged_with(tag).first
if winning_article
award_badges(
[winning_article.user.username],
@ -89,9 +89,9 @@ module BadgeRewarder
def self.award_streak_badge(num_weeks)
# No credit for super low quality
article_user_ids = Article.published.
where("published_at > ? AND score > ?", 1.week.ago, MINIMUM_QUALITY).
pluck(:user_id)
article_user_ids = Article.published
.where("published_at > ? AND score > ?", 1.week.ago, MINIMUM_QUALITY)
.pluck(:user_id)
message = if num_weeks == LONGEST_STREAK_WEEKS
LONGEST_STREAK_MESSAGE
else

View file

@ -76,8 +76,8 @@ module CacheBuster
bust("/videos?i=i")
end
TIMEFRAMES.each do |timestamp, interval|
if Article.published.where("published_at > ?", timestamp).
order("public_reactions_count DESC").limit(3).pluck(:id).include?(article.id)
if Article.published.where("published_at > ?", timestamp)
.order("public_reactions_count DESC").limit(3).pluck(:id).include?(article.id)
bust("/top/#{interval}")
bust("/top/#{interval}?i=i")
bust("/top/#{interval}/?i=i")
@ -99,8 +99,8 @@ module CacheBuster
bust("/t/#{tag}/latest?i=i")
end
TIMEFRAMES.each do |timestamp, interval|
if Article.published.where("published_at > ?", timestamp).tagged_with(tag).
order("public_reactions_count DESC").limit(3).pluck(:id).include?(article.id)
if Article.published.where("published_at > ?", timestamp).tagged_with(tag)
.order("public_reactions_count DESC").limit(3).pluck(:id).include?(article.id)
bust("/top/#{interval}")
bust("/top/#{interval}?i=i")
bust("/top/#{interval}/?i=i")
@ -110,8 +110,8 @@ module CacheBuster
end
end
if rand(2) == 1 &&
Article.published.tagged_with(tag).
order("hotness_score DESC").limit(2).pluck(:id).include?(article.id)
Article.published.tagged_with(tag)
.order("hotness_score DESC").limit(2).pluck(:id).include?(article.id)
bust("/t/#{tag}")
bust("/t/#{tag}?i=i")
end

View file

@ -33,23 +33,23 @@ class EmailLogic
experience_level_rating_min = experience_level_rating - 3.6
experience_level_rating_max = experience_level_rating + 3.6
@user.followed_articles.
where("published_at > ?", fresh_date).
where(published: true, email_digest_eligible: true).
where.not(user_id: @user.id).
where("score > ?", 12).
where("experience_level_rating > ? AND experience_level_rating < ?",
experience_level_rating_min, experience_level_rating_max).
order("score DESC").
limit(8)
@user.followed_articles
.where("published_at > ?", fresh_date)
.where(published: true, email_digest_eligible: true)
.where.not(user_id: @user.id)
.where("score > ?", 12)
.where("experience_level_rating > ? AND experience_level_rating < ?",
experience_level_rating_min, experience_level_rating_max)
.order("score DESC")
.limit(8)
else
Article.published.
where("published_at > ?", fresh_date).
where(featured: true, email_digest_eligible: true).
where.not(user_id: @user.id).
where("score > ?", 25).
order("score DESC").
limit(8)
Article.published
.where("published_at > ?", fresh_date)
.where(featured: true, email_digest_eligible: true)
.where.not(user_id: @user.id)
.where("score > ?", 25)
.order("score DESC")
.limit(8)
end
@ready_to_receive_email = false if articles.length < 3

View file

@ -6,11 +6,11 @@ class ReadingList
end
def get
Article.
joins(:reactions).
includes(:user).
where(reactions: reaction_criteria).
order("reactions.created_at DESC")
Article
.joins(:reactions)
.includes(:user)
.where(reactions: reaction_criteria)
.order("reactions.created_at DESC")
end
def cached_ids_of_articles

View file

@ -9,11 +9,11 @@ class StickyArticleCollection
end
def user_stickies
author.articles.published.
limited_column_select.
tagged_with(article_tags, any: true).
where.not(id: article.id).order("published_at DESC").
limit(3)
author.articles.published
.limited_column_select
.tagged_with(article_tags, any: true)
.where.not(id: article.id).order("published_at DESC")
.limit(3)
end
def suggested_stickies
@ -21,25 +21,25 @@ class StickyArticleCollection
end
def tag_articles
@tag_articles ||= Article.published.tagged_with(article_tags, any: true).
includes(:user).
where("public_reactions_count > ? OR comments_count > ?", reaction_count_num, comment_count_num).
where.not(id: article.id).where.not(user_id: article.user_id).
where("featured_number > ?", 5.days.ago.to_i).
order(Arel.sql("RANDOM()")).
limit(3)
@tag_articles ||= Article.published.tagged_with(article_tags, any: true)
.includes(:user)
.where("public_reactions_count > ? OR comments_count > ?", reaction_count_num, comment_count_num)
.where.not(id: article.id).where.not(user_id: article.user_id)
.where("featured_number > ?", 5.days.ago.to_i)
.order(Arel.sql("RANDOM()"))
.limit(3)
end
def more_articles
return [] if tag_articles.size > 6
Article.published.tagged_with(%w[career productivity discuss explainlikeimfive], any: true).
includes(:user).
where("comments_count > ?", comment_count_num).
where.not(id: article.id).where.not(user_id: article.user_id).
where("featured_number > ?", 5.days.ago.to_i).
order(Arel.sql("RANDOM()")).
limit(10 - tag_articles.size)
Article.published.tagged_with(%w[career productivity discuss explainlikeimfive], any: true)
.includes(:user)
.where("comments_count > ?", comment_count_num)
.where.not(id: article.id).where.not(user_id: article.user_id)
.where("featured_number > ?", 5.days.ago.to_i)
.order(Arel.sql("RANDOM()"))
.limit(10 - tag_articles.size)
end
def article_tags

View file

@ -1,8 +1,8 @@
class CodepenTag < LiquidTagBase
PARTIAL = "liquids/codepen".freeze
URL_REGEXP =
/\A(http|https):\/\/(codepen\.io|codepen\.io\/team)\/[a-zA-Z0-9_\-]{1,30}\/pen\/([a-zA-Z]{5,7})\/{0,1}\z/.
freeze
/\A(http|https):\/\/(codepen\.io|codepen\.io\/team)\/[a-zA-Z0-9_\-]{1,30}\/pen\/([a-zA-Z]{5,7})\/{0,1}\z/
.freeze
def initialize(_tag_name, link, _parse_context)
super

View file

@ -4,8 +4,8 @@ class CodesandboxTag < LiquidTagBase
/\A(initialpath=([a-zA-Z0-9\-_\/.@%])+)\Z|
\A(module=([a-zA-Z0-9\-_\/.@%])+)\Z|
\A(runonclick=((0|1){1}))\Z|
\Aview=(editor|split|preview)\Z/x.
freeze
\Aview=(editor|split|preview)\Z/x
.freeze
def initialize(_tag_name, id, _parse_context)
super

View file

@ -1,8 +1,8 @@
class GistTag < LiquidTagBase
PARTIAL = "liquids/gist".freeze
VALID_LINK_REGEXP =
/\Ahttps:\/\/gist\.github\.com\/([a-zA-Z0-9](-?[a-zA-Z0-9]){0,38})\/([a-zA-Z0-9]){1,32}(\/[a-zA-Z0-9]+)?\Z/.
freeze
/\Ahttps:\/\/gist\.github\.com\/([a-zA-Z0-9](-?[a-zA-Z0-9]){0,38})\/([a-zA-Z0-9]){1,32}(\/[a-zA-Z0-9]+)?\Z/
.freeze
def initialize(_tag_name, link, _parse_context)
super

View file

@ -67,9 +67,9 @@ class GithubTag
end
def sanitize_input(input)
ActionController::Base.helpers.strip_tags(input).
gsub(GITHUB_DOMAIN_REGEXP, "").
strip
ActionController::Base.helpers.strip_tags(input)
.gsub(GITHUB_DOMAIN_REGEXP, "")
.strip
end
def raise_error

View file

@ -31,8 +31,8 @@ class SoundcloudTag < LiquidTagBase
end
def valid_link?(link)
(link =~ /\Ahttps:\/\/soundcloud\.com\/([a-zA-Z0-9_\-]){3,25}\/(sets\/)?([a-zA-Z0-9_\-]){3,255}\Z/)&.
zero?
(link =~ /\Ahttps:\/\/soundcloud\.com\/([a-zA-Z0-9_\-]){3,25}\/(sets\/)?([a-zA-Z0-9_\-]){3,255}\Z/)
&.zero?
end
def raise_error

View file

@ -100,17 +100,17 @@ class Article < ApplicationRecord
scope :unpublished, -> { where(published: false) }
scope :admin_published_with, lambda { |tag_name|
published.
where(user_id: SiteConfig.staff_user_id).
order(published_at: :desc).
tagged_with(tag_name)
published
.where(user_id: SiteConfig.staff_user_id)
.order(published_at: :desc)
.tagged_with(tag_name)
}
scope :user_published_with, lambda { |user_id, tag_name|
published.
where(user_id: user_id).
order(published_at: :desc).
tagged_with(tag_name)
published
.where(user_id: user_id)
.order(published_at: :desc)
.tagged_with(tag_name)
}
scope :cached_tagged_with, ->(tag) { where("cached_tag_list ~* ?", "^#{tag},| #{tag},|, #{tag}$|^#{tag}$") }
@ -118,10 +118,10 @@ class Article < ApplicationRecord
scope :cached_tagged_by_approval_with, ->(tag) { cached_tagged_with(tag).where(approved: true) }
scope :active_help, lambda {
published.
cached_tagged_with("help").
order(created_at: :desc).
where("published_at > ? AND comments_count < ? AND score > ?", 12.hours.ago, 6, -4)
published
.cached_tagged_with("help")
.order(created_at: :desc)
.where("published_at > ? AND comments_count < ? AND score > ?", 12.hours.ago, 6, -4)
}
scope :limited_column_select, lambda {
@ -175,17 +175,17 @@ class Article < ApplicationRecord
}
scope :feed, lambda {
published.includes(:taggings).
select(
published.includes(:taggings)
.select(
:id, :published_at, :processed_html, :user_id, :organization_id, :title, :path, :cached_tag_list
)
}
scope :with_video, lambda {
published.
where.not(video: [nil, ""]).
where.not(video_thumbnail_url: [nil, ""]).
where("score > ?", -4)
published
.where.not(video: [nil, ""])
.where.not(video_thumbnail_url: [nil, ""])
.where("score > ?", -4)
}
scope :eager_load_serialized_data, -> { includes(:user, :organization, :tags) }
@ -201,11 +201,11 @@ class Article < ApplicationRecord
stories = if time_ago == "latest"
stories.order("published_at DESC").where("score > ?", -5)
elsif time_ago
stories.order("comments_count DESC").
where("published_at > ? AND score > ?", time_ago, -5)
stories.order("comments_count DESC")
.where("published_at > ? AND score > ?", time_ago, -5)
else
stories.order("last_comment_at DESC").
where("published_at > ? AND score > ?", (tags.present? ? 5 : 2).days.ago, -5)
stories.order("last_comment_at DESC")
.where("published_at > ? AND score > ?", (tags.present? ? 5 : 2).days.ago, -5)
end
stories = tags.size == 1 ? stories.cached_tagged_with(tags.first) : stories.tagged_with(tags)
stories.pluck(:path, :title, :comments_count, :created_at)
@ -218,11 +218,11 @@ class Article < ApplicationRecord
# Time ago sometimes is given as nil and should then be the default. I know, sloppy.
time_ago = 75.days.ago if time_ago.nil?
relation = Article.published.
order(organic_page_views_past_month_count: :desc).
where("score > ?", 8).
where("published_at > ?", time_ago).
limit(20)
relation = Article.published
.order(organic_page_views_past_month_count: :desc)
.where("score > ?", 8)
.where("published_at > ?", time_ago)
.limit(20)
fields = %i[path title comments_count created_at]
if tag
@ -233,10 +233,10 @@ class Article < ApplicationRecord
end
def self.search_optimized(tag = nil)
relation = Article.published.
order(updated_at: :desc).
where.not(search_optimized_title_preamble: nil).
limit(20)
relation = Article.published
.order(updated_at: :desc)
.where.not(search_optimized_title_preamble: nil)
.limit(20)
fields = %i[path search_optimized_title_preamble comments_count created_at]
if tag

View file

@ -59,9 +59,9 @@ class BufferUpdate < ApplicationRecord
def validate_body_text_recent_uniqueness
return if persisted?
relation = BufferUpdate.
where(body_text: body_text, article_id: article_id, tag_id: tag_id, social_service_name: social_service_name).
where("created_at > ?", 2.minutes.ago)
relation = BufferUpdate
.where(body_text: body_text, article_id: article_id, tag_id: tag_id, social_service_name: social_service_name)
.where("created_at > ?", 2.minutes.ago)
return unless relation.any?

View file

@ -179,8 +179,8 @@ class ChatChannel < ApplicationRecord
end
def channel_human_names
active_memberships.
order("last_opened_at DESC").limit(5).includes(:user).map do |membership|
active_memberships
.order("last_opened_at DESC").limit(5).includes(:user).map do |membership|
membership.user.name
end
end

View file

@ -80,9 +80,9 @@ class Comment < ApplicationRecord
end
def parent_type
parent_or_root_article.class.name.downcase.
gsub("article", "post").
gsub("podcastepisode", "episode")
parent_or_root_article.class.name.downcase
.gsub("article", "post")
.gsub("podcastepisode", "episode")
end
def id_code_generated

View file

@ -9,7 +9,7 @@ class EmailMessage < Ahoy::Message
end
def self.find_for_reports(feedback_message_ids)
select(:to, :subject, :content, :utm_campaign, :feedback_message_id).
where(feedback_message_id: feedback_message_ids)
select(:to, :subject, :content, :utm_campaign, :feedback_message_id)
.where(feedback_message_id: feedback_message_ids)
end
end

View file

@ -12,13 +12,13 @@ class Event < ApplicationRecord
before_validation :evaluate_markdown
scope :in_the_future_and_published, lambda {
where("starts_at > ?", Time.current).
where(published: true)
where("starts_at > ?", Time.current)
.where(published: true)
}
scope :in_the_past_and_published, lambda {
where("starts_at < ?", Time.current).
where(published: true)
where("starts_at < ?", Time.current)
.where(published: true)
}
private

View file

@ -61,8 +61,8 @@ class Follow < ApplicationRecord
def modify_chat_channel_status
return unless followable_type == "User" && followable.following?(follower)
channel = follower.chat_channels.
find_by("slug LIKE ? OR slug like ?", "%/#{followable.username}%", "%#{followable.username}/%")
channel = follower.chat_channels
.find_by("slug LIKE ? OR slug like ?", "%/#{followable.username}%", "%#{followable.username}/%")
channel&.update(status: "inactive")
end
end

View file

@ -15,10 +15,10 @@ class GithubRepo < ApplicationRecord
# Update existing repository or create a new one with given params.
# Repository is searched by either GitHub ID or URL.
def self.upsert(user, **params)
repo = user.github_repos.
where(github_id_code: params[:github_id_code]).
or(where(url: params[:url])).
first
repo = user.github_repos
.where(github_id_code: params[:github_id_code])
.or(where(url: params[:url]))
.first
repo ||= new(params.merge(user_id: user.id))
repo.update(params)

View file

@ -36,13 +36,13 @@ class HtmlVariant < ApplicationRecord
private
def find_top_for_test(tags_array, group)
where(group: group, approved: true, published: true, target_tag: tags_array).
order("success_rate DESC").limit(rand(1..20)).sample
where(group: group, approved: true, published: true, target_tag: tags_array)
.order("success_rate DESC").limit(rand(1..20)).sample
end
def find_random_for_test(tags_array, group)
where(group: group, approved: true, published: true, target_tag: tags_array).
order(Arel.sql("RANDOM()")).first
where(group: group, approved: true, published: true, target_tag: tags_array)
.order(Arel.sql("RANDOM()")).first
end
end

View file

@ -31,11 +31,11 @@ class Message < ApplicationRecord
end
def update_all_has_unopened_messages_statuses
chat_channel.
chat_channel_memberships.
where("last_opened_at < ?", 10.seconds.ago).
where.not(user_id: user_id).
update_all(has_unopened_messages: true)
chat_channel
.chat_channel_memberships
.where("last_opened_at < ?", 10.seconds.ago)
.where.not(user_id: user_id)
.update_all(has_unopened_messages: true)
end
def evaluate_markdown
@ -174,14 +174,14 @@ class Message < ApplicationRecord
# rubocop:enable Rails/OutputSafety
def cl_path(img_src)
ActionController::Base.helpers.
cl_image_path(img_src,
type: "fetch",
width: 725,
crop: "limit",
flags: "progressive",
fetch_format: "auto",
sign_url: true)
ActionController::Base.helpers
.cl_image_path(img_src,
type: "fetch",
width: 725,
crop: "limit",
flags: "progressive",
fetch_format: "auto",
sign_url: true)
end
def determine_user_validity
@ -223,8 +223,8 @@ class Message < ApplicationRecord
recipient = direct_receiver
return if !chat_channel.direct? ||
recipient.updated_at > 1.hour.ago ||
recipient.chat_channel_memberships.order("last_opened_at DESC").
first.last_opened_at > 15.hours.ago ||
recipient.chat_channel_memberships.order("last_opened_at DESC")
.first.last_opened_at > 15.hours.ago ||
chat_channel.last_message_at > 30.minutes.ago ||
recipient.email_connect_messages == false

View file

@ -29,9 +29,9 @@ class Podcast < ApplicationRecord
alias_attribute :name, :title
def existing_episode(item)
episode = PodcastEpisode.where(media_url: item.enclosure_url).
or(PodcastEpisode.where(title: item.title)).
or(PodcastEpisode.where(guid: item.guid.to_s)).presence
episode = PodcastEpisode.where(media_url: item.enclosure_url)
.or(PodcastEpisode.where(title: item.title))
.or(PodcastEpisode.where(guid: item.guid.to_s)).presence
# if unique_website_url? is set to true (the default value), we try to find an episode by website_url as well
# if unique_website_url? is set to false it usually means that website_url is the same for different episodes
episode ||= PodcastEpisode.where(website_url: item.link).presence if item.link.present? && unique_website_url?

View file

@ -102,9 +102,9 @@ class PodcastEpisode < ApplicationRecord
def process_html_and_prefix_all_images
return if body.blank?
self.processed_html = body.
gsub("\r\n<p>&nbsp;</p>\r\n", "").gsub("\r\n<p>&nbsp;</p>\r\n", "").
gsub("\r\n<h3>&nbsp;</h3>\r\n", "").gsub("\r\n<h3>&nbsp;</h3>\r\n", "")
self.processed_html = body
.gsub("\r\n<p>&nbsp;</p>\r\n", "").gsub("\r\n<p>&nbsp;</p>\r\n", "")
.gsub("\r\n<h3>&nbsp;</h3>\r\n", "").gsub("\r\n<h3>&nbsp;</h3>\r\n", "")
self.processed_html = "<p>#{processed_html}</p>" unless processed_html.include?("<p>")
@ -116,15 +116,15 @@ class PodcastEpisode < ApplicationRecord
quality = "auto"
quality = 66 if img_src.include?(".gif")
cloudinary_img_src = ActionController::Base.helpers.
cl_image_path(img_src,
type: "fetch",
width: 725,
crop: "limit",
quality: quality,
flags: "progressive",
fetch_format: "auto",
sign_url: true)
cloudinary_img_src = ActionController::Base.helpers
.cl_image_path(img_src,
type: "fetch",
width: 725,
crop: "limit",
quality: quality,
flags: "progressive",
fetch_format: "auto",
sign_url: true)
self.processed_html = processed_html.gsub(img_src, cloudinary_img_src)
end
end

View file

@ -34,15 +34,15 @@ class Sponsorship < ApplicationRecord
private
def validate_tag_uniqueness
return unless self.class.where(sponsorable: sponsorable, level: :tag).
where("expires_at > ? AND id != ?", Time.current, id.to_i).exists?
return unless self.class.where(sponsorable: sponsorable, level: :tag)
.where("expires_at > ? AND id != ?", Time.current, id.to_i).exists?
errors.add(:level, "The tag is already sponsored")
end
def validate_level_uniqueness
return unless self.class.where(organization: organization).
where("level IN (?) AND expires_at > ? AND id != ?", METAL_LEVELS, Time.current, id.to_i).exists?
return unless self.class.where(organization: organization)
.where("level IN (?) AND expires_at > ? AND id != ?", METAL_LEVELS, Time.current, id.to_i).exists?
errors.add(:level, "You can have only one sponsorship of #{METAL_LEVELS.join(', ')}")
end

View file

@ -97,12 +97,12 @@ class Tag < ActsAsTaggableOn::Tag
end
def calculate_hotness_score
self.hotness_score = Article.tagged_with(name).
where("articles.featured_number > ?", 7.days.ago.to_i).
map do |article|
self.hotness_score = Article.tagged_with(name)
.where("articles.featured_number > ?", 7.days.ago.to_i)
.map do |article|
(article.comments_count * 14) + article.score + rand(6) + ((taggings_count + 1) / 2)
end.
sum
end
.sum
end
def bust_cache

View file

@ -216,9 +216,9 @@ class User < ApplicationRecord
end
def followed_articles
Article.tagged_with(cached_followed_tag_names, any: true).
union(Article.where(user_id: cached_following_users_ids)).
where(language: preferred_languages_array, published: true)
Article.tagged_with(cached_followed_tag_names, any: true)
.union(Article.where(user_id: cached_following_users_ids))
.where(language: preferred_languages_array, published: true)
end
def cached_following_users_ids

View file

@ -14,8 +14,8 @@ module Internal
role_id_for(:trusted),
).order("users.comments_count DESC")
else
relation.joins(:roles).
where(users_roles: { role_id: role_id_for(state) })
relation.joins(:roles)
.where(users_roles: { role_id: role_id_for(state) })
end
relation = search_relation(relation, search) if search.presence

View file

@ -18,9 +18,9 @@ module Search
attribute :tags, &:tag_list
attribute :author do |cl|
ListingAuthorSerializer.new(cl.author).
serializable_hash.
dig(:data, :attributes)
ListingAuthorSerializer.new(cl.author)
.serializable_hash
.dig(:data, :attributes)
end
end
end

View file

@ -80,13 +80,13 @@ class AnalyticsService
end
# prepare relations for metrics
@comment_data = Comment.
where(commentable_id: article_ids, commentable_type: "Article").
where("score > 0")
@follow_data = Follow.
where(followable_type: user_or_org.class.name, followable_id: user_or_org.id)
@reaction_data = Reaction.public_category.
where(reactable_id: article_ids, reactable_type: "Article")
@comment_data = Comment
.where(commentable_id: article_ids, commentable_type: "Article")
.where("score > 0")
@follow_data = Follow
.where(followable_type: user_or_org.class.name, followable_id: user_or_org.id)
@reaction_data = Reaction.public_category
.where(reactable_id: article_ids, reactable_type: "Article")
@page_view_data = PageView.where(article_id: article_ids)
# filter data by date if needed

View file

@ -40,17 +40,17 @@ class ArticleApiIndexService
end
if (user = User.find_by(username: username))
user.articles.published.
includes(:organization).
order("published_at DESC").
page(page).
per(per_page || num)
user.articles.published
.includes(:organization)
.order("published_at DESC")
.page(page)
.per(per_page || num)
elsif (organization = Organization.find_by(slug: username))
organization.articles.published.
includes(:user).
order("published_at DESC").
page(page).
per(per_page || num)
organization.articles.published
.includes(:user)
.order("published_at DESC")
.page(page)
.per(per_page || num)
else
Article.none
end
@ -62,8 +62,8 @@ class ArticleApiIndexService
articles = if Tag.find_by(name: tag)&.requires_approval
articles.where(approved: true).order("featured_number DESC")
elsif top.present?
articles.where("published_at > ?", top.to_i.days.ago).
order("public_reactions_count DESC")
articles.where("published_at > ?", top.to_i.days.ago)
.order("public_reactions_count DESC")
else
articles.order("hotness_score DESC")
end
@ -72,10 +72,10 @@ class ArticleApiIndexService
end
def top_articles
Article.published.includes(:user, :organization).
where("published_at > ?", top.to_i.days.ago).
order("public_reactions_count DESC").
page(page).per(per_page || DEFAULT_PER_PAGE)
Article.published.includes(:user, :organization)
.where("published_at > ?", top.to_i.days.ago)
.order("public_reactions_count DESC")
.page(page).per(per_page || DEFAULT_PER_PAGE)
end
def state_articles(state)
@ -98,20 +98,20 @@ class ArticleApiIndexService
end
def collection_articles(collection_id)
Article.published.
where(collection_id: collection_id).
includes(:user, :organization).
order("published_at").
page(page).
per(per_page || DEFAULT_PER_PAGE)
Article.published
.where(collection_id: collection_id)
.includes(:user, :organization)
.order("published_at")
.page(page)
.per(per_page || DEFAULT_PER_PAGE)
end
def base_articles
Article.published.
where(featured: true).
includes(:user, :organization).
order("hotness_score DESC").
page(page).
per(per_page || DEFAULT_PER_PAGE)
Article.published
.where(featured: true)
.includes(:user, :organization)
.order("hotness_score DESC")
.page(page)
.per(per_page || DEFAULT_PER_PAGE)
end
end

View file

@ -27,23 +27,23 @@ module Articles
end
def published_articles_by_tag
articles = Article.published.limited_column_select.
includes(top_comments: :user).
page(@page).per(@number_of_articles)
articles = Article.published.limited_column_select
.includes(top_comments: :user)
.page(@page).per(@number_of_articles)
articles = articles.cached_tagged_with(@tag) if @tag.present? # More efficient than tagged_with
articles
end
# Timeframe values from Timeframer::DATETIMES
def top_articles_by_timeframe(timeframe:)
published_articles_by_tag.where("published_at > ?", Timeframer.new(timeframe).datetime).
order("score DESC").page(@page).per(@number_of_articles)
published_articles_by_tag.where("published_at > ?", Timeframer.new(timeframe).datetime)
.order("score DESC").page(@page).per(@number_of_articles)
end
def latest_feed
published_articles_by_tag.order("published_at DESC").
where("featured_number > ? AND score > ?", 1_449_999_999, -20).
page(@page).per(@number_of_articles)
published_articles_by_tag.order("published_at DESC")
.where("featured_number > ? AND score > ?", 1_449_999_999, -20)
.page(@page).per(@number_of_articles)
end
def default_home_feed_and_featured_story(user_signed_in: false, ranking: true)
@ -236,9 +236,9 @@ module Articles
end
def globally_hot_articles(user_signed_in)
hot_stories = published_articles_by_tag.
where("score > ? OR featured = ?", 7, true).
order("hotness_score DESC")
hot_stories = published_articles_by_tag
.where("score > ? OR featured = ?", 7, true)
.order("hotness_score DESC")
featured_story = hot_stories.where.not(main_image: nil).first
if user_signed_in
hot_story_count = hot_stories.count
@ -246,9 +246,9 @@ module Articles
i < hot_story_count
end.sample # random offset, weighted more towards zero
hot_stories = hot_stories.offset(offset)
new_stories = Article.published.
where("score > ?", -15).
limited_column_select.includes(top_comments: :user).order("published_at DESC").limit(rand(15..80))
new_stories = Article.published
.where("score > ?", -15)
.limited_column_select.includes(top_comments: :user).order("published_at DESC").limit(rand(15..80))
hot_stories = hot_stories.to_a + new_stories.to_a
end
[featured_story, hot_stories.to_a]

View file

@ -38,8 +38,8 @@ module Exporter
attributes_to_select = %i[id commentable_id commentable_type] + allowed_attributes
comments.includes(:commentable).select(attributes_to_select).find_each do |comment|
# merge final json with the path of the commentable
comments_to_jsonify << comment.as_json(only: allowed_attributes).
merge(commentable_path: comment.commentable&.path)
comments_to_jsonify << comment.as_json(only: allowed_attributes)
.merge(commentable_path: comment.commentable&.path)
end
comments_to_jsonify.to_json

View file

@ -21,8 +21,8 @@ module Mentions
def users_mentioned_in_text_excluding_author
mentioned_usernames = extract_usernames_from_mentions_in_text
collect_existing_users(mentioned_usernames).
yield_self do |existing_mentioned_users|
collect_existing_users(mentioned_usernames)
.yield_self do |existing_mentioned_users|
reject_notifiable_author(existing_mentioned_users)
end
end

View file

@ -4,9 +4,9 @@ module Notifications
SUPPORTED = [Comment].freeze
def self.available_moderators
User.with_role(:trusted).
where("last_moderation_notification < ?", MODERATORS_AVAILABILITY_DELAY.ago).
where(mod_roundrobin_notifications: true)
User.with_role(:trusted)
.where("last_moderation_notification < ?", MODERATORS_AVAILABILITY_DELAY.ago)
.where(mod_roundrobin_notifications: true)
end
end
end

View file

@ -54,9 +54,9 @@ module Notifications
attr_reader :comment
def user_ids_for(config_name)
NotificationSubscription.
where(notifiable_id: comment.commentable_id, notifiable_type: "Article", config: config_name).
pluck(:user_id)
NotificationSubscription
.where(notifiable_id: comment.commentable_id, notifiable_type: "Article", config: config_name)
.pluck(:user_id)
end
def comment_user_ids

View file

@ -24,8 +24,8 @@ module Notifications
end
def call
recent_follows = Follow.where(followable_type: followable_type, followable_id: followable_id).
where("created_at > ?", 24.hours.ago).order("created_at DESC")
recent_follows = Follow.where(followable_type: followable_type, followable_id: followable_id)
.where("created_at > ?", 24.hours.ago).order("created_at DESC")
notification_params = { action: "Follow" }
if followable_type == "User"

View file

@ -23,10 +23,10 @@ module Notifications
return unless receiver.is_a?(User) || receiver.is_a?(Organization)
reaction_siblings = Reaction.public_category.where(reactable_id: reaction.reactable_id,
reactable_type: reaction.reactable_type).
where.not(reactions: { user_id: reaction.reactable_user_id }).
preload(:reactable).includes(:user).where.not(users: { id: nil }).
order("reactions.created_at DESC")
reactable_type: reaction.reactable_type)
.where.not(reactions: { user_id: reaction.reactable_user_id })
.preload(:reactable).includes(:user).where.not(users: { id: nil })
.order("reactions.created_at DESC")
aggregated_reaction_siblings = reaction_siblings.map do |reaction|
{ category: reaction.category, created_at: reaction.created_at, user: user_data(reaction.user) }

View file

@ -41,10 +41,10 @@ class RssReader
cleaned_content = HtmlCleaner.new.clean_html(get_content)
cleaned_content = thorough_parsing(cleaned_content, @feed.url)
content = ReverseMarkdown.
convert(cleaned_content, github_flavored: true).
gsub("```\n\n```", "").
gsub(/&nbsp;|\u00A0/, " ")
content = ReverseMarkdown
.convert(cleaned_content, github_flavored: true)
.gsub("```\n\n```", "")
.gsub(/&nbsp;|\u00A0/, " ")
content.gsub!(/{%\syoutube\s(.{11,18})\s%}/) do |tag|
tag.gsub("\\_", "_")

View file

@ -8,11 +8,11 @@ module Suggester
def suggest
if user.decorate.cached_followed_tag_names.any?
(recent_producers(3) - [user]).
sample(50).uniq
(recent_producers(3) - [user])
.sample(50).uniq
else
(recent_commenters(4, 30) + recent_top_producers - [user]).
uniq.sample(50)
(recent_commenters(4, 30) + recent_top_producers - [user])
.uniq.sample(50)
end
end
@ -21,13 +21,13 @@ module Suggester
attr_reader :user, :attributes_to_select
def tagged_article_user_ids(num_weeks = 1)
Article.published.
tagged_with(user.decorate.cached_followed_tag_names, any: true).
where("score > ? AND published_at > ?", article_reaction_count, num_weeks.weeks.ago).
pluck(:user_id).
each_with_object(Hash.new(0)) { |value, counts| counts[value] += 1 }.
sort_by { |_key, value| value }.
map { |arr| arr[0] }
Article.published
.tagged_with(user.decorate.cached_followed_tag_names, any: true)
.where("score > ? AND published_at > ?", article_reaction_count, num_weeks.weeks.ago)
.pluck(:user_id)
.each_with_object(Hash.new(0)) { |value, counts| counts[value] += 1 }
.sort_by { |_key, value| value }
.map { |arr| arr[0] }
end
def recent_producers(num_weeks = 1)

View file

@ -23,12 +23,12 @@ module Suggester
end
def active_authors_for_given_tags
@active_authors_for_given_tags ||= Article.published.tagged_with([given_tag], any: true).
where("public_reactions_count >= ?", minimum_reaction_count).
where("published_at > ?", 4.months.ago).
where("user_id != ?", user.id).
where.not(user_id: user.following_by_type("User")).
pluck(:user_id)
@active_authors_for_given_tags ||= Article.published.tagged_with([given_tag], any: true)
.where("public_reactions_count >= ?", minimum_reaction_count)
.where("published_at > ?", 4.months.ago)
.where("user_id != ?", user.id)
.where.not(user_id: user.following_by_type("User"))
.pluck(:user_id)
end
def reputable_user_ids

View file

@ -4,9 +4,9 @@ module Follows
sidekiq_options queue: :medium_priority, retry: 10
def perform(follow_id)
follow = Follow.
includes(:follower, :followable).
find_by(id: follow_id, follower_type: "User", followable_type: "User")
follow = Follow
.includes(:follower, :followable)
.find_by(id: follow_id, follower_type: "User", followable_type: "User")
return unless follow&.followable&.following?(follow.follower)
ChatChannel.create_with_users(users: [follow.followable, follow.follower])

View file

@ -7,9 +7,9 @@ module Follows
follow = Follow.find_by(id: follow_id, followable_type: "User")
return unless follow&.followable.present? && follow.followable.receives_follower_email_notifications?
return if EmailMessage.where(user_id: follow.followable_id).
where("sent_at > ?", rand(15..35).hours.ago).
where("subject LIKE ?", "%#{NotifyMailer::SUBJECTS[:new_follower_email]}").exists?
return if EmailMessage.where(user_id: follow.followable_id)
.where("sent_at > ?", rand(15..35).hours.ago)
.where("subject LIKE ?", "%#{NotifyMailer::SUBJECTS[:new_follower_email]}").exists?
mailer.constantize.with(follow: follow).new_follower_email.deliver_now
end

View file

@ -19,9 +19,9 @@ module Metrics
def perform
# Welcome Notification click events created in the past day, logged by title.
EVENT_TITLES.each do |title|
event = Ahoy::Event.where(name: "Clicked Welcome Notification").
where("time > ?", 1.day.ago).
where("properties->>'title' = ?", title)
event = Ahoy::Event.where(name: "Clicked Welcome Notification")
.where("time > ?", 1.day.ago)
.where("properties->>'title' = ?", title)
DatadogStatsClient.count(
"ahoy_events",

View file

@ -13,9 +13,9 @@ module Metrics
)
# Articles published in the past 24 hours with at least 15 "score" (positive/negative reactions)
articles_min_15_comment_score_past_24h = Article.published.
where("comment_score >= ? AND published_at > ?", 15, 1.day.ago).
size
articles_min_15_comment_score_past_24h = Article.published
.where("comment_score >= ? AND published_at > ?", 15, 1.day.ago)
.size
DatadogStatsClient.count(
"articles.min_15_comment_score_past_24h",
articles_min_15_comment_score_past_24h,
@ -57,10 +57,10 @@ module Metrics
def get_days_active_past_week_counts
ids_by_day = []
7.times do |i|
id = PageView.
where("created_at > ? AND created_at < ?", (i + 1).days.ago, i.days.ago).
where.not(user_id: nil).
pluck(:user_id).uniq
id = PageView
.where("created_at > ? AND created_at < ?", (i + 1).days.ago, i.days.ago)
.where.not(user_id: nil)
.pluck(:user_id).uniq
ids_by_day << id
end
flat_id_list = ids_by_day.flatten.uniq

View file

@ -5,10 +5,10 @@ module Search
sidekiq_options queue: :high_priority, lock: :until_executing
def perform(object_class, ids)
data_hashes = object_class.constantize.
eager_load_serialized_data.
where(id: ids).
find_each.map(&:serialized_search_hash)
data_hashes = object_class.constantize
.eager_load_serialized_data
.where(id: ids)
.find_each.map(&:serialized_search_hash)
search_class = object_class.constantize::SEARCH_CLASS

View file

@ -21,8 +21,8 @@ module Users
private
def determine_weekly_pageview_goal(user, experiment)
past_week_page_view_counts = user.page_views.where("created_at > ?", 7.days.ago).
group("DATE(created_at)").count.values
past_week_page_view_counts = user.page_views.where("created_at > ?", 7.days.ago)
.group("DATE(created_at)").count.values
past_week_page_view_counts.delete(0)
return unless past_week_page_view_counts.size > 3
@ -31,8 +31,8 @@ module Users
# Almost repeat of above method, but rule of threes dictates this is fine duplication for now.
def determine_daily_pageview_goal(user, experiment)
past_day_page_view_counts = user.page_views.where("created_at > ?", 24.hours.ago).
group("DATE_PART('hour', created_at)").count.values
past_day_page_view_counts = user.page_views.where("created_at > ?", 24.hours.ago)
.group("DATE_PART('hour', created_at)").count.values
past_day_page_view_counts.delete(0)
return unless past_day_page_view_counts.size > 3

View file

@ -15,8 +15,8 @@ end
SitemapGenerator::Sitemap.default_host = "#{ApplicationConfig['APP_PROTOCOL']}#{ApplicationConfig['APP_DOMAIN']}"
SitemapGenerator::Sitemap.create do
Article.published.where("score > ? OR featured = ?", 12, true).
limit(38_000).find_each do |article|
Article.published.where("score > ? OR featured = ?", 12, true)
.limit(38_000).find_each do |article|
add article.path, lastmod: article.last_comment_at, changefreq: "daily"
end

View file

@ -179,8 +179,8 @@ RSpec.describe ArticleDecorator, type: :decorator do
body_markdown = "---\ntitle: Title\npublished: false\ndescription:\ntags: heytag\n---\n\nHey this is the article"
search_optimized_description_replacement = "Hey this is the expected result"
expect(create_article(body_markdown: body_markdown,
search_optimized_description_replacement: search_optimized_description_replacement).
description_and_tags).to eq(search_optimized_description_replacement)
search_optimized_description_replacement: search_optimized_description_replacement)
.description_and_tags).to eq(search_optimized_description_replacement)
end
end
end

View file

@ -14,8 +14,8 @@ RSpec.describe ListingDecorator, type: :decorator do
end
it "returns the category's social preview descripton if available" do
expect(decorated_listing.social_preview_category).
to eq(category.social_preview_description)
expect(decorated_listing.social_preview_category)
.to eq(category.social_preview_description)
end
end
@ -23,20 +23,20 @@ RSpec.describe ListingDecorator, type: :decorator do
it "returns the default color if social preview color is blank" do
allow(category).to receive(:social_preview_color).and_return(nil)
expect(decorated_listing.social_preview_color).
to eq(ListingDecorator::DEFAULT_COLOR)
expect(decorated_listing.social_preview_color)
.to eq(ListingDecorator::DEFAULT_COLOR)
end
it "returns the category's social preview color if available" do
expect(decorated_listing.social_preview_color).
to eq(category.social_preview_color)
expect(decorated_listing.social_preview_color)
.to eq(category.social_preview_color)
end
it "can modify the brightness" do
color = category.social_preview_color
expect(decorated_listing.social_preview_color(brightness: 0.8)).
to eq(HexComparer.new([color]).brightness(0.8))
expect(decorated_listing.social_preview_color(brightness: 0.8))
.to eq(HexComparer.new([color]).brightness(0.8))
end
end
end

View file

@ -56,8 +56,8 @@ describe ArticlesHelper do
describe "#utc_iso_timestamp" do
it "correctly formats the date when present" do
expect(helper.utc_iso_timestamp(Time.current)).
to match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/)
expect(helper.utc_iso_timestamp(Time.current))
.to match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/)
end
it "returns nil if there is no timestamp" do

View file

@ -31,8 +31,8 @@ describe ApplicationConfig do
def setup_app_domain(app_domain)
# No #and_return for #have_received.
# rubocop:disable RSpec/MessageSpies
expect(ApplicationConfig).to receive(:[]).with("APP_DOMAIN").
and_return(app_domain)
expect(ApplicationConfig).to receive(:[]).with("APP_DOMAIN")
.and_return(app_domain)
# rubocop:enable RSpec/MessageSpies
end
end

View file

@ -72,24 +72,24 @@ RSpec.describe MailchimpBot, type: :labor do
it "unsubscribes properly" do
user.update(email_newsletter: false)
described_class.new(user).upsert_to_newsletter
expect(my_gibbon_client).to have_received(:upsert).
with(hash_including(body: hash_including(status: "unsubscribed")))
expect(my_gibbon_client).to have_received(:upsert)
.with(hash_including(body: hash_including(status: "unsubscribed")))
end
it "subscribes properly" do
user.update(email_newsletter: false)
user.update(email_newsletter: true)
described_class.new(user).upsert_to_newsletter
expect(my_gibbon_client).to have_received(:upsert).
with(hash_including(body: hash_including(status: "subscribed")))
expect(my_gibbon_client).to have_received(:upsert)
.with(hash_including(body: hash_including(status: "subscribed")))
end
it "updates email properly" do
user.update(email: Faker::Internet.email)
user.confirm
described_class.new(user).upsert_to_newsletter
expect(my_gibbon_client).to have_received(:upsert).
with(hash_including(body: hash_including(email_address: user.email)))
expect(my_gibbon_client).to have_received(:upsert)
.with(hash_including(body: hash_including(email_address: user.email)))
end
it "tries to resubscribe the user if the user has previously been subscribed" do
@ -115,12 +115,12 @@ RSpec.describe MailchimpBot, type: :labor do
user.update(email_community_mod_newsletter: true)
user.add_role :trusted
described_class.new(user).manage_community_moderator_list
expect(my_gibbon_client).to have_received(:upsert).
with(hash_including(
body: hash_including(
status: "subscribed",
),
))
expect(my_gibbon_client).to have_received(:upsert)
.with(hash_including(
body: hash_including(
status: "subscribed",
),
))
end
end
@ -133,12 +133,12 @@ RSpec.describe MailchimpBot, type: :labor do
user.update(email_tag_mod_newsletter: true)
user.add_role(:tag_moderator, tag)
described_class.new(user).manage_tag_moderator_list
expect(my_gibbon_client).to have_received(:upsert).
with(hash_including(
body: hash_including(
status: "subscribed",
),
))
expect(my_gibbon_client).to have_received(:upsert)
.with(hash_including(
body: hash_including(
status: "subscribed",
),
))
end
end
@ -148,8 +148,8 @@ RSpec.describe MailchimpBot, type: :labor do
it "unsubscribes the user from the weekly newsletter" do
described_class.new(user).unsubscribe_all_newsletters
expect(my_gibbon_client).to have_received(:update).
with(hash_including(body: hash_including(status: "unsubscribed")))
expect(my_gibbon_client).to have_received(:update)
.with(hash_including(body: hash_including(status: "unsubscribed")))
end
end
end

View file

@ -62,23 +62,23 @@ RSpec.describe MarkdownFixer, type: :labor do
it "does not escape a description that came pre-wrapped in single quotes" do
legacy_description = "'#{sample_text}'"
result = described_class.
add_quotes_to_description(front_matter(description: legacy_description))
result = described_class
.add_quotes_to_description(front_matter(description: legacy_description))
expect(result).to eq(front_matter(description: legacy_description))
end
it "does not escape a description that came pre-wrapped in double quotes" do
legacy_description = "\"#{sample_text}\""
result = described_class.
add_quotes_to_description(front_matter(description: legacy_description))
result = described_class
.add_quotes_to_description(front_matter(description: legacy_description))
expect(result).to eq(front_matter(description: legacy_description))
end
it "handles a complex description" do
legacy_description = %(Book review: "#{sample_text}", part 1 I'm #testing)
expected_description = "\"Book review: \\\"#{sample_text}\\\", part 1 I'm #testing\""
result = described_class.
add_quotes_to_description(front_matter(description: legacy_description))
result = described_class
.add_quotes_to_description(front_matter(description: legacy_description))
expect(result).to eq(front_matter(description: expected_description))
end
@ -100,16 +100,16 @@ RSpec.describe MarkdownFixer, type: :labor do
describe "::fix_all" do
it "escapes title and description" do
result = described_class.
fix_all(front_matter(title: sample_text, description: sample_text))
result = described_class
.fix_all(front_matter(title: sample_text, description: sample_text))
expected_result = front_matter(title: %("#{sample_text}"), description: %("#{sample_text}"))
expect(result).to eq(expected_result)
end
context "when description is empty" do
it "escapes title and description" do
result = described_class.
fix_all("---\ntitle: #{sample_text}\ndescription:\ntags: \n---\n")
result = described_class
.fix_all("---\ntitle: #{sample_text}\ndescription:\ntags: \n---\n")
expected_result = "---\ntitle: \"#{sample_text}\"\ndescription: \"\"\ntags: \n---\n"
expect(result).to eq(expected_result)
end
@ -118,8 +118,8 @@ RSpec.describe MarkdownFixer, type: :labor do
describe "::fix_for_preview" do
it "escapes title and description" do
result = described_class.
fix_for_preview(front_matter(title: sample_text, description: sample_text))
result = described_class
.fix_for_preview(front_matter(title: sample_text, description: sample_text))
expected_result = front_matter(title: %("#{sample_text}"), description: %("#{sample_text}"))
expect(result).to eq(expected_result)
end

View file

@ -259,8 +259,8 @@ RSpec.describe MarkdownParser, type: :labor do
end
it "wraps the image with Cloudinary" do
expect(generate_and_parse_markdown(markdown_with_img)).
to include("https://res.cloudinary.com")
expect(generate_and_parse_markdown(markdown_with_img))
.to include("https://res.cloudinary.com")
end
end

View file

@ -3,19 +3,19 @@ require "rails_helper"
RSpec.describe HtmlCssToImage, type: :lib do
describe ".url" do
it "returns the url to the created image" do
stub_request(:post, /hcti.io/).
to_return(status: 200,
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
headers: { "Content-Type" => "application/json" })
stub_request(:post, /hcti.io/)
.to_return(status: 200,
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
headers: { "Content-Type" => "application/json" })
expect(described_class.url(html: "test")).to eq("https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1")
end
it "returns fallback image if the request fails" do
stub_request(:post, /hcti.io/).
to_return(status: 429,
body: '{ "error": "Plan limit exceeded" }',
headers: { "Content-Type" => "application/json" })
stub_request(:post, /hcti.io/)
.to_return(status: 429,
body: '{ "error": "Plan limit exceeded" }',
headers: { "Content-Type" => "application/json" })
expect(described_class.url(html: "test")).to eq described_class::FALLBACK_IMAGE
end
@ -28,10 +28,10 @@ RSpec.describe HtmlCssToImage, type: :lib do
end
it "caches the image url when successful" do
stub_request(:post, /hcti.io/).
to_return(status: 200,
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
headers: { "Content-Type" => "application/json" })
stub_request(:post, /hcti.io/)
.to_return(status: 200,
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
headers: { "Content-Type" => "application/json" })
expected_url = "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1"
expect(described_class.fetch_url(html: "test")).to eq(expected_url)
@ -40,22 +40,22 @@ RSpec.describe HtmlCssToImage, type: :lib do
it "cache has a long expiration" do
# Images are expensive to generate, make sure we don't expire them too quickly.
stub_request(:post, /hcti.io/).
to_return(status: 200,
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
headers: { "Content-Type" => "application/json" })
stub_request(:post, /hcti.io/)
.to_return(status: 200,
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
headers: { "Content-Type" => "application/json" })
expected_url = "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1"
expect(described_class.fetch_url(html: "test")).to eq(expected_url)
expect(Rails.cache).to have_received(:write).
with(anything, anything, expires_in: HtmlCssToImage::CACHE_EXPIRATION).once
expect(Rails.cache).to have_received(:write)
.with(anything, anything, expires_in: HtmlCssToImage::CACHE_EXPIRATION).once
end
it "does not cache errors" do
stub_request(:post, /hcti.io/).
to_return(status: 429,
body: '{ "error": "Plan limit exceeded" }',
headers: { "Content-Type" => "application/json" })
stub_request(:post, /hcti.io/)
.to_return(status: 429,
body: '{ "error": "Plan limit exceeded" }',
headers: { "Content-Type" => "application/json" })
expect(described_class.fetch_url(html: "test")).to eq described_class::FALLBACK_IMAGE
expect(Rails.cache).not_to have_received(:write)

View file

@ -69,8 +69,8 @@ RSpec.describe LinkTag, type: :liquid_tag do
end
it "does not raise an error when invalid" do
expect { generate_new_liquid("fake_username/fake_article_slug") }.
not_to raise_error("Invalid link URL or link URL does not exist")
expect { generate_new_liquid("fake_username/fake_article_slug") }
.not_to raise_error("Invalid link URL or link URL does not exist")
end
it "renders a proper link tag" do

View file

@ -98,8 +98,8 @@ RSpec.describe ListingTag, type: :liquid_tag do
end
it "raises an error when invalid" do
expect { generate_new_liquid("/listings/fakecategory/fakeslug") }.
to raise_error("Invalid URL or slug. Listing not found.")
expect { generate_new_liquid("/listings/fakecategory/fakeslug") }
.to raise_error("Invalid URL or slug. Listing not found.")
end
it "displays expired message when listing is expired" do

View file

@ -15,8 +15,8 @@ RSpec.describe ChatChannelMembership, type: :model do
# rubocop:disable RSpec/NamedSubject
it {
expect(subject).to validate_inclusion_of(:status).
in_array(%w[active inactive pending rejected left_channel removed_from_channel joining_request])
expect(subject).to validate_inclusion_of(:status)
.in_array(%w[active inactive pending rejected left_channel removed_from_channel joining_request])
}
# rubocop:enable RSpec/NamedSubject

View file

@ -9,13 +9,13 @@ RSpec.describe FeedbackMessage, type: :model do
it { is_expected.to validate_length_of(:message).is_at_most(2500) }
it do
expect(feedback_message).to validate_inclusion_of(:category).
in_array(["spam", "other", "rude or vulgar", "harassment", "bug"])
expect(feedback_message).to validate_inclusion_of(:category)
.in_array(["spam", "other", "rude or vulgar", "harassment", "bug"])
end
it do
expect(feedback_message).to validate_inclusion_of(:status).
in_array(%w[Open Invalid Resolved])
expect(feedback_message).to validate_inclusion_of(:status)
.in_array(%w[Open Invalid Resolved])
end
describe "validations for an abuse report" do

View file

@ -57,79 +57,79 @@ RSpec.describe User, type: :model do
# rubocop:disable RSpec/NamedSubject
it do
expect(subject).to have_many(:access_grants).
class_name("Doorkeeper::AccessGrant").
with_foreign_key("resource_owner_id").
dependent(:delete_all)
expect(subject).to have_many(:access_grants)
.class_name("Doorkeeper::AccessGrant")
.with_foreign_key("resource_owner_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:access_tokens).
class_name("Doorkeeper::AccessToken").
with_foreign_key("resource_owner_id").
dependent(:delete_all)
expect(subject).to have_many(:access_tokens)
.class_name("Doorkeeper::AccessToken")
.with_foreign_key("resource_owner_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:affected_feedback_messages).
class_name("FeedbackMessage").
with_foreign_key("affected_id").
dependent(:nullify)
expect(subject).to have_many(:affected_feedback_messages)
.class_name("FeedbackMessage")
.with_foreign_key("affected_id")
.dependent(:nullify)
end
it do
expect(subject).to have_many(:authored_notes).
class_name("Note").
with_foreign_key("author_id").
dependent(:delete_all)
expect(subject).to have_many(:authored_notes)
.class_name("Note")
.with_foreign_key("author_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:backup_data).
class_name("BackupData").
with_foreign_key("instance_user_id").
dependent(:delete_all)
expect(subject).to have_many(:backup_data)
.class_name("BackupData")
.with_foreign_key("instance_user_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:blocked_blocks).
class_name("UserBlock").
with_foreign_key("blocked_id").
dependent(:delete_all)
expect(subject).to have_many(:blocked_blocks)
.class_name("UserBlock")
.with_foreign_key("blocked_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:blocker_blocks).
class_name("UserBlock").
with_foreign_key("blocker_id").
dependent(:delete_all)
expect(subject).to have_many(:blocker_blocks)
.class_name("UserBlock")
.with_foreign_key("blocker_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:created_podcasts).
class_name("Podcast").
with_foreign_key(:creator_id).
dependent(:nullify)
expect(subject).to have_many(:created_podcasts)
.class_name("Podcast")
.with_foreign_key(:creator_id)
.dependent(:nullify)
end
it do
expect(subject).to have_many(:offender_feedback_messages).
class_name("FeedbackMessage").
with_foreign_key(:offender_id).
dependent(:nullify)
expect(subject).to have_many(:offender_feedback_messages)
.class_name("FeedbackMessage")
.with_foreign_key(:offender_id)
.dependent(:nullify)
end
it do
expect(subject).to have_many(:reporter_feedback_messages).
class_name("FeedbackMessage").
with_foreign_key(:reporter_id).
dependent(:nullify)
expect(subject).to have_many(:reporter_feedback_messages)
.class_name("FeedbackMessage")
.with_foreign_key(:reporter_id)
.dependent(:nullify)
end
it do
expect(subject).to have_many(:webhook_endpoints).
class_name("Webhook::Endpoint").
dependent(:delete_all)
expect(subject).to have_many(:webhook_endpoints)
.class_name("Webhook::Endpoint")
.dependent(:delete_all)
end
# rubocop:enable RSpec/NamedSubject

View file

@ -16,8 +16,8 @@ RSpec.describe UserSubscription, type: :model do
# rubocop:disable RSpec/NamedSubject
it {
expect(subject).to validate_uniqueness_of(:subscriber_id).
scoped_to(%i[subscriber_email user_subscription_sourceable_type user_subscription_sourceable_id])
expect(subject).to validate_uniqueness_of(:subscriber_id)
.scoped_to(%i[subscriber_email user_subscription_sourceable_type user_subscription_sourceable_id])
}
# rubocop:enable RSpec/NamedSubject

View file

@ -53,8 +53,8 @@ RSpec.describe CommentPolicy, type: :policy do
it { is_expected.to permit_actions(%i[create moderator_create]) }
it do
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_moderator_create).
for_action(:moderator_create)
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_moderator_create)
.for_action(:moderator_create)
end
end
@ -64,8 +64,8 @@ RSpec.describe CommentPolicy, type: :policy do
it { is_expected.to permit_actions(%i[create moderator_create]) }
it do
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_moderator_create).
for_action(:moderator_create)
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_moderator_create)
.for_action(:moderator_create)
end
end
end
@ -111,8 +111,8 @@ RSpec.describe CommentPolicy, type: :policy do
it do
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_update).for_action(:update)
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_moderator_create).
for_action(:moderator_create)
expect(comment_policy).to permit_mass_assignment_of(valid_attributes_for_moderator_create)
.for_action(:moderator_create)
end
end
end

View file

@ -140,27 +140,27 @@ RSpec.configure do |config|
stub_request(:any, /emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/).to_rack("stubbed-emoji")
stub_request(:post, /api.fastly.com/).
to_return(status: 200, body: "".to_json, headers: {})
stub_request(:post, /api.fastly.com/)
.to_return(status: 200, body: "".to_json, headers: {})
stub_request(:post, /api.bufferapp.com/).
to_return(status: 200, body: { fake_text: "so fake" }.to_json, headers: {})
stub_request(:post, /api.bufferapp.com/)
.to_return(status: 200, body: { fake_text: "so fake" }.to_json, headers: {})
# for twitter image cdn
stub_request(:get, /twimg.com/).
to_return(status: 200, body: "", headers: {})
stub_request(:get, /twimg.com/)
.to_return(status: 200, body: "", headers: {})
stub_request(:any, /api.mailchimp.com/).
to_return(status: 200, body: "", headers: {})
stub_request(:any, /api.mailchimp.com/)
.to_return(status: 200, body: "", headers: {})
stub_request(:any, /dummyimage.com/).
to_return(status: 200, body: "", headers: {})
stub_request(:any, /dummyimage.com/)
.to_return(status: 200, body: "", headers: {})
stub_request(:post, "http://www.google-analytics.com/collect").
to_return(status: 200, body: "", headers: {})
stub_request(:post, "http://www.google-analytics.com/collect")
.to_return(status: 200, body: "", headers: {})
stub_request(:any, /robohash.org/).
with(headers:
stub_request(:any, /robohash.org/)
.with(headers:
{
"Accept" => "*/*",
"Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",

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