Ruby哈希中的相同键

时间:2013-09-10 21:05:08

标签: ruby-on-rails ruby google-adwords

我有一个简单的应用程序,旨在提取Adwords帐户指标(通过adwordsapi)并将其呈现给Rails视图中的表中的用户。除了一个问题之外,它正在正确地拉下多个广告系列的所有信息。

我无法获得每个字段的总计(总费用,总展示次数等)。我可以为帐户中的每个广告系列投放展示次数,但无法获得该帐户的总计。

我提前道歉要遵循noob代码:)

这是adwordscampaign_controller.rb

class AdwordscampaignController < ApplicationController

PAGE_SIZE = 50

def index()
@selected_account = selected_account

if @selected_account
  response = request_campaigns_list()
  if response
    @campaigns = Adwordscampaign.get_campaigns_list(response)
    @campaign_count = response[:total_num_entries]
    @start = params[:start]
    @end = params[:end]

    @myhash = Adwordscampaign.get_campaigns_list(response)

  end
 end
end

private

def request_campaigns_list()

# Prepare start and end date for the last week.

if params[:start].nil?
start_date = DateTime.parse((Date.today - 7).to_s).strftime("%Y%m%d")
end_date = DateTime.parse((Date.today - 1).to_s).strftime("%Y%m%d")
else
start_date = params[:start]
end_date = params[:end]
end

api = get_adwords_api()
service = api.service(:CampaignService, get_api_version())
selector = {
  :fields => ['Id', 'Name', 'Status', 'Cost', 'Impressions', 'Clicks', 'Ctr', 'Conversions', 'Amount'],
  :ordering => [{:field => 'Id', :sort_order => 'ASCENDING'}],
  :date_range => {:min => start_date, :max => end_date},
  :paging => {:start_index => 0, :number_results => PAGE_SIZE}
}
result = nil


begin
  result = service.get(selector)
rescue AdwordsApi::Errors::ApiException => e
  logger.fatal("Exception occurred: %s\n%s" % [e.to_s, e.message])
  flash.now[:alert] =
      'API request failed with an error, see logs for details'
end
return result
end
end

相关模型:adwordscampaign.rb

class Adwordscampaign
  attr_reader :id
  attr_reader :name
  attr_reader :status
  attr_reader :cost
  attr_reader :impressions
  attr_reader :clicks
  attr_reader :ctr
  attr_reader :costdecimal
  attr_reader :costperconversiondecimal


def initialize(api_campaign)
  @id = api_campaign[:id]
  @name = api_campaign[:name]
  @status = api_campaign[:status]

  budget = api_campaign[:budget]

  stats = api_campaign[:campaign_stats]

  @cost = (stats[:cost][:micro_amount] / 10000)
  @costdecimal = (@cost * 10000).round.to_f / 1000000
  @impressions = stats[:impressions]
  @clicks = stats[:clicks]
  @ctr = (stats[:ctr] * 100)

end


def self.get_campaigns_list(response)
  result = {}
  if response[:entries]
    response[:entries].each do |api_campaign|
      campaign = Adwordscampaign.new(api_campaign)
      result[campaign.id] = campaign
    end
  end
  return result
end
end

来自views \ adwordscampaign \ index.html.erb

的表格
<table class="table table-striped table-bordered">
  <tr>
    <th>ID
    <th>Name
    <th>Status
    <th>Impressions
    <th>Clicks
    <th>CTR
    <th>Cost

<% @campaigns.each do |id, campaign| %>
  <tr>
    <td><%= campaign.id %></td>
    <td><%= campaign.name %></td>
    <td><%= campaign.status %></td>
    <td><%= number_with_delimiter(campaign.impressions) %></td>
    <td><%= number_with_delimiter(campaign.clicks) %></td>
    <td><%= number_with_precision(campaign.ctr, precision: 2) %>%</td>
    <td>$<%= number_with_delimiter(campaign.costdecimal) %></td>



<% end %>     

<td><%= @campaigns %></td>

</table>

我在视图中(在底部)扔了@campaigns所以我可以看到它的输出是什么。语法对我来说有点陌生,但它看起来是嵌套在哈希中的哈希(正确吗?)

在视图中输出@campaigns

{109886905=>#<Adwordscampaign:0x4528ba0 @id=109879905, @name="Upholstery Cleaning",     @status="ACTIVE", @cost=2702, @costdecimal=27.02, @impressions=824, @clicks=7, @ctr=0.8495145631067961>, 103480025=>#<Adwordscampaign:0x7028b28 @id=109880025, @name="Carpet Cleaning", @status="ACTIVE", @cost=16739, @costdecimal=167.39, @impressions=4457, @clicks=29, @ctr=0.6506618801884676>, 104560145=>#<Adwordscampaign:0x3e9ibac8 @id=109880145, @name="Competitors", @status="ACTIVE", @cost=1596, @costdecimal=15.96, @impressions=515, @clicks=5, @ctr=0.9708737864077669>

最后回答问题 - 如何获得此处找到的3个广告系列中的每个广告系列的@clicks总数(或@impressions,@cost等)?

我一直在搜索“如何将相同的哈希键/值相加”或“如何合并嵌套哈希”之类的内容无效。

提前致谢!

1 个答案:

答案 0 :(得分:0)

@campaigns看起来像{id - &gt;的简单哈希Adwordscampaign}。 #<ObjectName:data>表示法是Ruby尽最大努力为您提供该对象的可读性。

例如,总和点击次数是一个简单的map-reduce:

total_clicks = @campaigns.map { |id, campaign| campaign.clicks } .reduce(&:+)

这将创建一个包含所有campaign.clicks值的数组,然后使用+运算符将它们组合在一起。

这假设这些对象上有#clicks。如果没有,请相应调整。

如果你所做的只是总结各种属性,你可以多次简化它的使用:

camp_list = @campaigns.map { |id, campaign| campaign }
total_clicks      = camp_list.map(&:clicks).reduce(&:+)
total_cost        = camp_list.map(&:cost).reduce(&:+)
total_impressions = camp_list.map(&:impressions).reduce(&:+)

进一步减少它是读者的一项练习。 :)