Created
April 1, 2013 15:04
-
-
Save valachi/5285436 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Show < ActiveRecord::Base | |
has_many :videos, inverse_of: :show | |
has_many :subscriptions | |
has_many :missing_episodes, dependent: :destroy | |
validates :name, uniqueness: true, presence: true | |
include Show::Details | |
include Show::ExternalData | |
mount_uploader :poster, PosterUploader | |
FUZZY_ALIASES = { | |
"donttrustthebinapartment23" => "donttrustthebitchinapartment23", | |
"merlin2008" => "merlin", | |
"theofficeus" => "theoffice", | |
"beautyandthebeast2012" => "beautyandthebeast", | |
"hawaiifive02010" => "hawaiifive0", | |
"nashville2012" => "nashville", | |
"mikemolly" => "mikeandmolly", | |
"shamelessus" => "shameless", | |
"castle2009" => "castle", | |
"spartacus" => "spartacusbloodandsand", | |
"spartacuswarofthedamned" => "spartacusbloodandsand", | |
"beinghuman" => "beinghumanuk", | |
"theamericans2013" => "theamericans", | |
"blackmirror2011" => "blackmirror" | |
} | |
class << self | |
# Search show by name without punctuation | |
def fuzzy_name(show) | |
if FUZZY_ALIASES.has_key? only_letters(show) | |
show = FUZZY_ALIASES[only_letters(show)] | |
end | |
where("#{only_letters_sql('name')} = #{only_letters_sql('?')}", show).first | |
end | |
def translated_genres | |
genres.map{|g| [I18n.t("genres.#{g}"), g.downcase]} | |
end | |
def countries | |
pluck(:country).map{ |country| country.split(', ') }.flatten.uniq | |
end | |
private | |
# sql to return only letters for given string | |
def only_letters_sql(string) | |
"lower(regexp_replace(#{string}, '[^[:alnum:]]', '', 'g'))" | |
end | |
def only_letters(string) | |
string.gsub(/[^[:alnum:]]/, '').downcase | |
end | |
def genres | |
pluck(:genres).map{|genres| genres.split }.flatten.uniq | |
end | |
end | |
def newest_episode | |
videos.where("videos.progress = ?", 100).maximum :created_at | |
end | |
def to_param | |
slug | |
end | |
# convert attributes to string before saving as show attribute | |
def genres=(value) | |
write_attribute :genres, value.join(' ') | |
end | |
def country=(value) | |
write_attribute :country, value.join(', ') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment