在开始之前,我还在学习整个 MVC 框架,所以请理解你的解释。
我正在使用 Twitter Gem 调用 Twitter API。我收集了我所有的追随者,并使用genderize.io ruby gem 扩展返回他们的姓名和性别。我在我的索引视图中显示性别“男性、女性、未知”的名称和百分比。
我的最后一段代码将分解返回一个 JSON 对象。
"{\"male\":{\"count\":59,\"percent\":0.46},\"female\":{\"count\":31,\"percent\":0.24},\"unknown gender\":{\"count\":38,\"percent\":0.3}}"
我的问题是如何重构这个长索引方法并将其分解,以便模型可以存储我从 API 和性别分解中返回的数据?换句话说,我需要存储 Screename (screen_name)、关注者列表 (@user_name) 和性别百分比 (@gender_percentage)。
如果有人知道如何开始分解以及将数据存储在哪里,请告诉我
我的代码显示在这里。
class TwitterController < ApplicationController
require 'twitter'
require 'json'
def index
client = Twitter::REST::Client.new do |config|
config.consumer_key = '************'
config.consumer_secret = '************'
config.access_token = '************'
config.access_token_secret = '************'
end
screen_name = 'myscreenname'
follower_ids = client.follower_ids(screen_name)
user_name = []
follower_ids.each_slice(100) do |slice|
begin
client.users(slice).each do |user|
user_name << user.name
end
end
end
@user_name = user_name
c = user_name.map{|str| str.split.first}
gen = []
gir = GenderizeIoRb.new
c.each do |res|
begin
res = gir.info_for_name(res)
gen << "#{res[:result].gender}"
rescue
res = "GenderizeIoRb::Errors::NameNotFound"
gen << "uknown gender"
end
end
hash = Hash.new 0
gen.each do |mfg|
hash[mfg] += 1
end
count = hash.to_a
sum = 0
count.each { |_, v| sum += v }
gender_percentage = []
count.each do |k, v|
gender_percentage << [k, ((v.to_f / sum) * 100).round]
end
@gender_percentage = gender_percentage
total = count.map { |elt| elt[1] }.reduce { |x, y| x + y }
hsh = {}
count.each do |label, n|
hsh[label] = {}
hsh[label]['count'] = n
hsh[label]['percent'] = (n.to_f / total.to_f).round(2)
end
hsh.to_json
end
end