feature/share-libs
rb 76 lines 1.94 KB
Raw
1 require 'action_view'
2 require 'action_view/helpers'
3
4 # Our representation of a song.
5 # Not to be confused with a song from a provider.
6 class Song < ApplicationRecord
7 include ActionView::Helpers::DateHelper
8 include Rails.application.routes.url_helpers
9
10 belongs_to :album, optional: true
11 belongs_to :user
12
13 has_many :song_artists, dependent: :destroy
14 has_many :artists, through: :song_artists
15 has_many :song_chord_plea, dependent: :destroy
16 has_many :users, through: :song_chord_plea
17
18 accepts_nested_attributes_for :song_artists, allow_destroy: true
19
20 has_many :lyrics, dependent: :destroy
21 has_many :chords, dependent: :destroy
22
23 has_many :comments, as: :commentable
24
25 # Song providers
26 has_many :song_providers
27 has_many :youtubes, -> { where(provider_type: :youtube) }, class_name: 'SongProvider'
28 has_many :spotifies, -> { where(provider_type: :spotify) }, class_name: 'SongProvider'
29
30 # More than one user may upload the same file from a song.
31 has_many :audio_file
32
33 has_many :audio_files
34
35 validates_length_of :album, presence: true, allow_blank: false
36 validates_length_of :name, presence: true, allow_blank: false
37 validates_length_of :description, presence: true, allow_blank: false
38
39 def as_json(options = {})
40 options[:methods] = %i[songwriters path type created]
41 super
42 end
43
44 def title_link
45 _title_link = name
46 _title_link += " #{album.artists.first.name}" if album&.artists&.first&.present?
47 _title_link += " #{album.name}" if album.present?
48 _title_link
49 end
50
51 def slug
52 _slug = name
53 _slug += "-#{album.artists.first.name}" if album&.artists&.first&.present?
54 _slug += "-#{album.name}" if album.present?
55 _slug += "-#{id}"
56 _slug.downcase.parameterize
57 end
58
59 private
60
61 def songwriters
62 artists.as_json(only: %i[id name])
63 end
64
65 def created
66 "#{time_ago_in_words(created_at)} #{I18n.t('ago')}"
67 end
68
69 def path
70 song_detail_path(slug)
71 end
72
73 def type
74 I18n.t(self.class.name)
75 end
76 end