metrika icon indicating copy to clipboard operation
metrika copied to clipboard

Request table data

Open glafir opened this issue 8 years ago • 1 comments

How I can request table data https://api-metrika.yandex.ru/stat/v1/data

glafir avatar Jun 28 '16 19:06 glafir

Поскольку авторизация в Яндекс метрике у этого гема работает нормально и устарело только используемое api, я сделал себе такой модуль, может кому-то это сэкономит время:

# config/initializers/metrika.rb
module Metrika

  class MyClient < Client

    def initialize(*args)
      opts = args.extract_options!
      super(*args)

      @default_params = {
          date1: opts.fetch(:date1, Rails.application.config.socials[:yandex_metrika_date1]),
          id: opts.fetch(:counter_id, Rails.application.config.socials[:yandex_metrika_counter_id])
      }
      @api_path = '/stat/v1/data'

      access_token = opts.fetch(:access_token, Rails.application.config.socials[:yandex_metrika_access_token])
      @token = self.restore_token(access_token)
    end

    # public get
    def pget(path, params = {}, options = {})
      self.get(path, params, options)
    end

    def all_pageviews(path)
      params = {
          metrics: 'ym:pv:pageviews',
          dimensions: 'ym:pv:URLPath',
          limit: 1,
          filters: "ym:pv:URLPath=='#{path}'"
      }
      params.reverse_merge! @default_params

      response_hash = self.get @api_path, params
      if response_hash['data'].present?
        response_hash['data'][0]['metrics'][0].to_i
      else
        0
      end
    rescue Metrika::Errors::MetrikaError
      0
    end

  end

end

Metrika.configure do |config|
  config.application_id = Rails.application.config.socials[:yandex_metrika_id]
  config.application_password = Rails.application.config.socials[:yandex_metrika_password]
end

# app/helpers/blog_helper.rb
module BlogHelper

  def all_pageviews(path)
    Rails.cache.fetch("all_pageviews#{path}", expires_in: 1.minute) do
      client = Metrika::MyClient.new
      views = client.all_pageviews path
      I18n.t('all_pageviews', count: views)
    end
  end

end

Мне по сути нужна была только функция, которая забирает сумму показов для конкретной страницы. :)

Ну и пару ссылок на api вам в помощь:

arturaum avatar Mar 24 '17 14:03 arturaum