docbrown/app/services/article_api_index_service.rb
Abraham Williams 9cb40e546b Enables Rails cops (#2186)
* Enable Rails cops

* Fix Rails/DynamicFindBy

* Fix Rails/HttpStatus

* Fix Rails/Blank

* Fix Rails/RequestReferer

* Fix Rails/ActiveRecordAliases

* Fix Rails/FindBy

* Fix Rails/Presence

* Fix Rails/Delegate

* Fix Rails/Validation

* Fix Rails/PluralizationGrammar

* Fix Rails/Present

* Fix Rails/Output

* Fix Rails/Blank

* Fix Rails/FilePath

* Fix Rails/InverseOf

* Fix Rails/LexicallyScopedActionFilter

* Add Rails/OutputSafety to TODO

* Add Rails/HasManyOrHasOneDependent to TODO

* Add Rails/SkipsModelValidations to TODO
2019-03-25 09:25:55 -04:00

103 lines
2.6 KiB
Ruby

class ArticleApiIndexService
attr_accessor :tag, :username, :page, :state, :top
def initialize(params)
@page = params[:page]
@tag = params[:tag]
@username = params[:username]
@state = params[:state]
@top = params[:top]
end
def get
articles = if tag.present?
tag_articles
elsif username.present?
username_articles
elsif state.present?
state_articles(state)
else
base_articles
end
articles.
decorate
end
private
def username_articles
num = if @state == "all"
1000
else
30
end
if (user = User.find_by(username: username))
user.articles.
where(published: true).
includes(:user).
order("published_at DESC").
page(page).
per(num)
elsif (organization = Organization.find_by(slug: username))
organization.articles.
where(published: true).
includes(:user).
order("published_at DESC").
page(page).
per(num)
else
not_found
end
end
def tag_articles
if Tag.find_by(name: tag)&.requires_approval
Article.
where(published: true, approved: true).
order("featured_number DESC").
includes(:user).
includes(:organization).
page(page).
per(30).
cached_tagged_with(tag)
elsif top.present?
Article.
where(published: true).
order("positive_reactions_count DESC").
where("published_at > ?", top.to_i.days.ago).
includes(:user).
includes(:organization).
page(page).
per(30).
cached_tagged_with(tag)
else
Article.
where(published: true).
order("hotness_score DESC").
includes(:user).
includes(:organization).
page(page).
per(30).
cached_tagged_with(tag)
end
end
def state_articles(state)
if state == "fresh"
Article.where(published: true).
where("positive_reactions_count < ? AND featured_number > ? AND score > ?", 2, 7.hours.ago.to_i, -2)
elsif state == "rising"
Article.where(published: true).
where("positive_reactions_count > ? AND positive_reactions_count < ? AND featured_number > ?", 19, 33, 3.days.ago.to_i)
end
end
def base_articles
Article.
where(published: true, featured: true).
order("hotness_score DESC").
includes(:user).
includes(:organization).
page(page).
per(30)
end
end