Module: Yt::Modules::Associations

Included in:
Yt::Models::Base
Defined in:
lib/yt/modules/associations.rb

Overview

Associations are a set of macro-like class methods to express relationship between YouTube resources like “Channel has many Videos” or “Account has one Id”. They are inspired by ActiveRecord::Associations.

Instance Method Summary collapse

Instance Method Details

#has_many(attributes) ⇒ Object

Examples:

Adds the videos method to the Channel resource.

class Channel < Resource
  has_many :videos
end


15
16
17
18
19
20
# File 'lib/yt/modules/associations.rb', line 15

def has_many(attributes)
  require "yt/collections/#{attributes}"
  collection_name = attributes.to_s.sub(/.*\./, '').camelize.pluralize
  collection = "Yt::Collections::#{collection_name}".constantize
  define_memoized_method(attributes) { collection.of self }
end

#has_one(attribute) ⇒ Object

Examples:

Adds the status method to the Video resource.

class Video < Resource
  has_one :status
end


26
27
28
29
30
# File 'lib/yt/modules/associations.rb', line 26

def has_one(attribute)
  attributes = attribute.to_s.pluralize
  has_many attributes
  define_memoized_method(attribute) { send(attributes).first! }
end