参考サイトを元にRailsアプリからGoogle Analytics APIを叩いてPVランキングを作成する機能を実装しました。
下記のエラーが出てしまうのですが、これはなぜでしょうか?
require 'date'が機能していないのでしょうか?
Parameter 'start-date' has an invalid value: 2015/07/10. Must match: /^[0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo)$/.
get_pvrankingの "start-date" => "#{Date.today.to_s}",
ちなみに"start-date" => "2014-01-01",のようにすればエラーは出ません
lang
1#lib/google_api.rb 2 3require 'google/api_client' 4require 'date' 5 6class GoogleApi 7 API_VERSION = 'v3' 8 CACHED_API_FILE = "#{Rails.root}/certificate/analytics-#{API_VERSION}.cache" 9 10 SERVICE_ACCOUNT_EMAIL = ENV['GAPI_EMAIL_ADDRESS'] #適宜変更 11 KEY_FILE = "#{Rails.root}/certificate/gapi_privatekey.p12" #適宜変更 12 KEY_SECRET = ENV['GAPI_KEY_SECRET'] #適宜変更 13 VIEW_ID = ENV['GAPI_VIEW_ID'] #適宜変更 14 15 def initialize 16 @client = Google::APIClient.new( 17 application_name: 'Sample App', #適宜変更 18 application_version: '1.0.0' #適宜変更 19 ) 20 end 21 22 def api 23 analytics = nil 24 if File.exists? CACHED_API_FILE 25 File.open(CACHED_API_FILE) do |file| 26 analytics = Marshal.load(file) 27 end 28 else 29 analytics = @client.discovered_api('analytics', API_VERSION) 30 File.open(CACHED_API_FILE, 'w') do |file| 31 Marshal.dump(analytics, file) 32 end 33 end 34 analytics 35 end 36 37 def signing_key 38 return if @signing_key 39 @signing_key = Google::APIClient::KeyUtils.load_from_pkcs12(KEY_FILE, KEY_SECRET) 40 end 41 42 def authorize! 43 @client.authorization = Signet::OAuth2::Client.new( 44 token_credential_uri: 'https://accounts.google.com/o/oauth2/token', 45 audience: 'https://accounts.google.com/o/oauth2/token', 46 scope: 'https://www.googleapis.com/auth/analytics.readonly', 47 issuer: SERVICE_ACCOUNT_EMAIL, 48 signing_key: signing_key 49 ) 50 @client.authorization.fetch_access_token! 51 end 52 53 54 def get_pvranking(options = {}) 55 @client.execute( 56 api_method: api.data.ga.get, 57 parameters: { 58 "ids" => "ga:#{VIEW_ID}", 59 "start-date" => "#{Date.today.to_s}", #適宜変更 60 "end-date" => "#{Date.yesterday.to_s}", #適宜変更 61 "metrics" => "ga:pageviews", #適宜変更 62 "dimensions" => "ga:pagePath", #適宜変更 63 'filters' => 'ga:pagePath=@/blogs;', #適宜変更 64 "sort" => "-ga:pageviews", #適宜変更 65 "max-results" => options[:max_results], 66 } 67 ) 68 end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/07/09 23:28
2015/07/10 00:15