Skip to content

Commit

Permalink
server: general cleanup to solve rubocop complaints
Browse files Browse the repository at this point in the history
  • Loading branch information
NuckChorris committed Jul 6, 2016
1 parent 805df0e commit 4031ecd
Show file tree
Hide file tree
Showing 52 changed files with 363 additions and 337 deletions.
4 changes: 2 additions & 2 deletions server/app/models/concerns/age_ratings.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module AgeRatings
extend ActiveSupport::Concern

AGE_RATINGS = %i[G PG R R18]
SAFE_AGE_RATINGS = %w[G PG R]
AGE_RATINGS = %i[G PG R R18].freeze
SAFE_AGE_RATINGS = %w[G PG R].freeze

# SFW-ness is whitelist, not blacklist
def sfw?
Expand Down
4 changes: 3 additions & 1 deletion server/app/models/concerns/episodic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ def recalculate_episode_length!
# Try for the statistical mode (most common value) of episode lengths
length, num = episodes.length_mode.values_at(:mode, :count)
# If it's less than half of episodes, use average instead
length = episodes.length_average if episode_count && num < (episode_count / 2)
if episode_count && num < (episode_count / 2)
length = episodes.length_average
end

update(episode_length: length)
end
Expand Down
13 changes: 7 additions & 6 deletions server/app/models/concerns/rateable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,26 @@ module Rateable

def calculate_rating_frequencies
base = LibraryEntry::VALID_RATINGS.map { |r| [r, 0] }.to_h
freqs = LibraryEntry.where(media: self).group(:rating).count.
transform_keys(&:to_f).slice(*LibraryEntry::VALID_RATINGS)
freqs = LibraryEntry.where(media: self).group(:rating).count
.transform_keys(&:to_f)
.slice(*LibraryEntry::VALID_RATINGS)
base.merge(freqs)
end

def calculate_rating_frequencies!
self.update_attribute(:rating_frequencies, calculate_rating_frequencies)
update_attribute(:rating_frequencies, calculate_rating_frequencies)
end

def update_rating_frequency(rating, diff)
return if rating.nil?
update_query = <<-EOF
rating_frequencies = rating_frequencies
|| hstore('#{rating.to_s}', (
|| hstore('#{rating}', (
COALESCE(rating_frequencies->'#{rating}', '0')::integer + #{diff}
)::text)
EOF
self.class.where(id: self.id).update_all(update_query)
self.touch
self.class.where(id: id).update_all(update_query)
touch
end

def decrement_rating_frequency(rating)
Expand Down
8 changes: 3 additions & 5 deletions server/app/models/library_entry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class LibraryEntry < ActiveRecord::Base
# TODO: apply this globally so that we can easily update it to add the
# totally definitely happening 1000-point scale. Or just because it's good
# practice.
VALID_RATINGS = (0.5..5).step(0.5).to_a
VALID_RATINGS = (0.5..5).step(0.5).to_a.freeze

belongs_to :user, touch: true
belongs_to :media, polymorphic: true
Expand All @@ -37,7 +37,7 @@ class LibraryEntry < ActiveRecord::Base

validates :user, :media, :status, :progress, :reconsume_count,
presence: true
validates :user_id, uniqueness: { scope: [:media_type, :media_id] }
validates :user_id, uniqueness: { scope: %i[media_type media_id] }
validates :rating, numericality: {
greater_than: 0,
less_than_or_equal_to: 5
Expand All @@ -64,9 +64,7 @@ def progress_limit
def rating_on_halves
return unless rating

unless rating % 0.5 == 0.0
errors.add(:rating, 'must be a multiple of 0.5')
end
errors.add(:rating, 'must be a multiple of 0.5') unless rating % 0.5 == 0.0
end

after_save do
Expand Down
4 changes: 2 additions & 2 deletions server/app/models/list_import.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ def apply

yield({ status: :running, total: count, current: 0 })
LibraryEntry.transaction do
self.each.with_index do |media, data, index|
each.with_index do |media, data, index|
entry = LibraryEntry.where(user: user, media: media).first_or_create
merged_entry(entry, data, strategy).save!
yield({ status: :running, total: count, current: index + 1 })
end
end
yield({ status: :completed, total: count, current: count })
rescue Exception => e
rescue StandardError
yield({ status: :error, total: count })
raise
end
Expand Down
2 changes: 1 addition & 1 deletion server/app/models/mapping.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Mapping < ActiveRecord::Base

validates :external_site, :external_id, presence: true
# Right now, we want to ensure only one external id per media per site
validates :media_id, uniqueness: { scope: [:media_type, :external_site] }
validates :media_id, uniqueness: { scope: %i[media_type external_site] }

def self.lookup(site, id)
find_by(external_site: site, external_id: id).try(:media)
Expand Down
4 changes: 2 additions & 2 deletions server/app/models/pro_membership_plan.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
#

class ProMembershipPlan < ActiveRecord::Base
scope :recurring, ->{ where(recurring: true) }
scope :nonrecurring, ->{ where(recurring: false) }
scope :recurring, -> { where(recurring: true) }
scope :nonrecurring, -> { where(recurring: false) }
end
4 changes: 2 additions & 2 deletions server/app/models/role.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class Role < ActiveRecord::Base
belongs_to :resource, polymorphic: true

validates :resource_type,
inclusion: { in: Rolify.resource_types },
allow_nil: true
inclusion: { in: Rolify.resource_types },
allow_nil: true

scopify
end
2 changes: 1 addition & 1 deletion server/app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class User < ActiveRecord::Base
PAST_NAMES_LIMIT = 10

devise :database_authenticatable, :registerable, :recoverable,
:validatable, :confirmable, :async
:validatable, :confirmable, :async
rolify

belongs_to :pro_membership_plan
Expand Down
2 changes: 1 addition & 1 deletion server/app/policies/application_policy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def show?
end
alias_method :index?, :show?

def is_admin?
def is_admin? # rubocop:disable Style/PredicateName
user && user.has_role?(:admin, model_class)
end
alias_method :create?, :is_admin?
Expand Down
8 changes: 4 additions & 4 deletions server/app/resources/concerns/authenticated_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ def policy

# Raise a Pundit::NotAuthorizedError for the given query
def not_authorized!(query)
fail Pundit::NotAuthorizedError, query: query,
record: @model,
policy: pundit.policy
raise Pundit::NotAuthorizedError, query: query,
record: @model,
policy: pundit.policy
end

# Limit scope of relations based on policies
Expand All @@ -39,7 +39,7 @@ def records_for(relation_name)

# Limit scope of finders based on policy
class_methods do
def records(options = {context: {}})
def records(options = { context: {} })
current_user = options[:context][:current_user]
policy = Pundit::PolicyFinder.new(_model_class.all)
scope = policy.scope.new(current_user, _model_class)
Expand Down
26 changes: 11 additions & 15 deletions server/app/resources/concerns/searchable_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def index(index)
def inherited(subclass)
subclass.instance_variable_set(:@chewy_index, @chewy_index.deep_dup)
subclass.instance_variable_set(:@queryable_fields,
@queryable_fields.deep_dup)
@queryable_fields.deep_dup)
super
end

Expand All @@ -30,9 +30,7 @@ def query(field, opts = {})
# array all at once, or to modify values.
filter field, verify: opts[:verify] || -> (values, context) {
if opts[:valid]
if values.all? { |v| opts[:valid].call(v, context) }
values
end
values if values.all? { |v| opts[:valid].call(v, context) }
else
values
end
Expand All @@ -51,15 +49,15 @@ def should_query?(filters)
def search(filters, opts = {})
context = opts[:context]

return [] if filters.values.any? { |f| f.nil? }
return [] if filters.values.any?(&:nil?)

# Apply scopes, load, and wrap
apply_scopes(filters, opts).load.map { |result| new(result, context) }
end

# Count all search results
def search_count(filters, opts = {})
return 0 if filters.values.any? { |f| f.nil? }
return 0 if filters.values.any?(&:nil?)
apply_scopes(filters, opts).total_count
end

Expand All @@ -71,12 +69,10 @@ def sortable_fields(context = nil)
private

def apply_scopes(filters, opts = {})
context = opts[:context]

# Generate query
query = generate_query(filters)
query = query.reduce(@chewy_index) do |scope, query|
scope.public_send(*query.values_at(:mode, :query))
query = query.reduce(@chewy_index) do |scope, subquery|
scope.public_send(*subquery.values_at(:mode, :query))
end
# Pagination
query = opts[:paginator].apply(query, {}) if opts[:paginator]
Expand All @@ -98,24 +94,24 @@ def generate_query(filters)
filter = filters[field]
filter = opts[:apply].call(filter, {}) if opts[:apply]

{mode: opts[:mode] || :filter, query: auto_query(field, filter)}
{ mode: opts[:mode] || :filter, query: auto_query(field, filter) }
end
queries.compact
end

def auto_query(field, value)
case value
when String, Fixnum, Float, Date
{match: {field => value}}
{ match: { field => value } }
when Range
{range: {field => {gte: value.min, lte: value.max}}}
{ range: { field => { gte: value.min, lte: value.max } } }
when Array
# Array<String|Fixnum|Float> get shorthanded to a single match query
if value.all? { |v| v.is_a?(String) || v.is_a?(Fixnum) || v.is_a?(Float) }
if value.all? { |v| v.is_a?(String) || v.is_a?(Numeric) }
auto_query(field, value.join(' '))
else
matchers = value.map { |v| auto_query(field, v) }
{bool: {should: matchers}}
{ bool: { should: matchers } }
end
else
value
Expand Down
2 changes: 1 addition & 1 deletion server/app/resources/library_entry_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class LibraryEntryResource < BaseResource
attributes :status, :progress, :reconsuming, :reconsume_count, :notes,
:private, :rating, :updated_at
:private, :rating, :updated_at

filters :user_id, :media_id, :media_type, :status

Expand Down
29 changes: 16 additions & 13 deletions server/app/resources/media_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ class MediaResource < BaseResource
# This regex accepts a numerical range or single number
# $1 = start, $2 = dot representing closed/open, $3 = end
NUMBER = /(\d+(?:\.\d+)?)/
NUMERIC_RANGE = %r{\A#{NUMBER}(?:(?:\.\.(\.)?)#{NUMBER})?\z}
NUMERIC_RANGE = /\A#{NUMBER}(?:(?:\.\.(\.)?)#{NUMBER})?\z/
NUMERIC_QUERY = {
valid: -> (value, _ctx) { NUMERIC_RANGE.match(value) },
apply: -> (values, _ctx) {
Expand All @@ -17,17 +17,17 @@ class MediaResource < BaseResource
end
end
}
}
}.freeze

attributes :slug, :synopsis,
# Images
:poster_image, :cover_image, :cover_image_top_offset,
# Titles
:titles, :canonical_title, :abbreviated_titles,
# Ratings
:average_rating, :rating_frequencies,
# Dates
:start_date, :end_date
# Images
:poster_image, :cover_image, :cover_image_top_offset,
# Titles
:titles, :canonical_title, :abbreviated_titles,
# Ratings
:average_rating, :rating_frequencies,
# Dates
:start_date, :end_date

has_many :genres
has_many :castings
Expand All @@ -42,9 +42,10 @@ class MediaResource < BaseResource
query :user_count, NUMERIC_QUERY
query :genres,
apply: -> (values, _ctx) {
{match: {genres: {query: values.join(' '), operator: 'and'}}}
{ match: { genres: { query: values.join(' '), operator: 'and' } } }
}
query :text, mode: :query,
query :text,
mode: :query,
apply: -> (values, _ctx) {
{
function_score: {
Expand All @@ -54,7 +55,9 @@ class MediaResource < BaseResource
},
query: {
multi_match: {
fields: %w[titles.* abbreviated_titles synopsis actors characters],
fields: %w[
titles.* abbreviated_titles synopsis actors characters
],
query: values.join(','),
fuzziness: 2,
max_expansions: 15,
Expand Down
10 changes: 5 additions & 5 deletions server/app/resources/user_resource.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class UserResource < BaseResource
PRIVATE_FIELDS = %i[email password]
PRIVATE_FIELDS = %i[email password].freeze

attributes :name, :past_names, :avatar, :cover_image, :about, :bio,
:about_formatted, :location, :website, :waifu_or_husbando,
:rating_system, :to_follow, :followers_count, :following_count,
:onboarded, :life_spent_on_anime
:about_formatted, :location, :website, :waifu_or_husbando, :rating_system,
:to_follow, :followers_count, :following_count, :onboarded,
:life_spent_on_anime

attributes *PRIVATE_FIELDS
attributes(*PRIVATE_FIELDS)

filter :name, apply: -> (records, value, _o) { records.by_name(value.first) }
filter :self, apply: -> (_r, _v, options) {
Expand Down
4 changes: 2 additions & 2 deletions server/config/environments/development.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@

# Enable CORS in Development so Ember can access Rails on a different port
config.middleware.insert_before 0, 'Rack::Cors',
debug: true,
logger: -> { Rails.logger } do
debug: true,
logger: -> { Rails.logger } do
allow do
origins '*'
resource '*', headers: :any,
Expand Down
5 changes: 3 additions & 2 deletions server/config/initializers/rolify.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# By default ORM adapter is ActiveRecord. uncomment to use mongoid
# config.use_mongoid

# Dynamic shortcuts for User class (user.is_admin? like methods). Default is: false
# Dynamic shortcuts for User class (user.is_admin? like methods).
# Default is: false
# config.use_dynamic_shortcuts
end
end
3 changes: 2 additions & 1 deletion server/lib/data_import/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def initialize
end

private

def queued
hydra.queued_requests
end
Expand All @@ -26,7 +27,7 @@ def parallel_get(urls, opts = {})
return urls.each_with_index do |url, i|
get(url, opts) do |res|
results[i] = res
yield *results if results.compact.length == urls.length
yield(*results) if results.compact.length == urls.length
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions server/lib/data_import/media.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ def get_multiple_media(external_ids)
#
# @param [String] external ID to load
# @return [Media] a hash of standardized attributes
def get_media(external_id)
fail 'Override DataImport::Media#get_media with your own implementation'
def get_media(*)
raise 'Override DataImport::Media#get_media with your own implementation'
end
end
end
Loading

0 comments on commit 4031ecd

Please sign in to comment.