Module: Yt::Modules::Reports

Included in:
Yt::Models::Channel
Defined in:
lib/yt/modules/reports.rb

Overview

Provides methods to to access the analytics reports of a resource.

YouTube resources with reports are: channels.

Instance Method Summary collapse

Instance Method Details

#has_report(metric) ⇒ Object

Defines two public instance methods to access the reports of a resource for a specific metric.

Examples:

Adds earnings and earnings_on on a Channel resource.

class Channel < Resource
  has_report :earnings
end

Parameters:

  • metric (Symbol)

    the metric to access the reports of.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/yt/modules/reports.rb', line 28

def has_report(metric)
  define_method "#{metric}_on" do |date|
    send(metric, from: date, to: date).values.first
  end

  define_method metric do |options = {}|
    from = options[:since] || options[:from] || 5.days.ago
    to = options[:until] || options[:to] || 1.day.ago
    range = Range.new *[from, to].map(&:to_date)

    ivar = instance_variable_get "@#{metric}"
    instance_variable_set "@#{metric}", ivar || {}

    Hash[*range.flat_map do |date|
      [date, instance_variable_get("@#{metric}")[date] ||= send("range_#{metric}", range)[date]]
    end]
  end

  define_method "range_#{metric}" do |date_range|
    ivar = instance_variable_get "@range_#{metric}"
    instance_variable_set "@range_#{metric}", ivar || {}
    instance_variable_get("@range_#{metric}")[date_range] ||= send("all_#{metric}").within date_range
  end
  private "range_#{metric}"

  define_method "all_#{metric}" do
    # @note Asking for the "earnings" metric of a day in which a channel
    # made 0 USD returns the wrong "nil". But adding to the request the
    # "estimatedMinutesWatched" metric returns the correct value 0.
    query = metric
    query = "estimatedMinutesWatched,#{metric}" if metric == :earnings
    Collections::Reports.of(self).tap{|reports| reports.metric = query}
  end
  private "all_#{metric}"
end