Module: Yt::Associations::HasReports
- Included in:
- Models::Base
- Defined in:
- lib/yt/associations/has_reports.rb
Overview
Provides methods to to access the analytics reports of a resource.
YouTube resources with reports are: channels and
{Yt::Models::Channel videos}.
Instance Method Summary collapse
-
#has_report(metric) ⇒ Object
Defines two public instance methods to access the reports of a resource for a specific metric.
Instance Method Details
#has_report(metric) ⇒ Object
Defines two public instance methods to access the reports of a resource for a specific metric.
27 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 63 |
# File 'lib/yt/associations/has_reports.rb', line 27 def has_report(metric) require 'yt/collections/reports' define_method "#{metric}_on" do |date| send(metric, from: date, to: date).values.first end define_method metric do | = {}| from = [:since] || [:from] || 5.days.ago to = [:until] || [: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 |