Before I begin, I'm still learning the whole MVC frame work so please be understanding in your explanations.
I am making a call to the Twitter API using the Twitter Gem. Im gathering all of my followers and returning their names and gender using the genderize.io ruby gem extension. I am displaying the names and percentage of genders "male, female, unknown" on my index view.
My final bit of code returns the breakdown into a JSON object.
"{\"male\":{\"count\":59,\"percent\":0.46},\"female\":{\"count\":31,\"percent\":0.24},\"unknown gender\":{\"count\":38,\"percent\":0.3}}"
My question is how do I refactor this long index method and break this down so that the model can store the data that I am getting back from the API and the gender breakdown? In other words I need to store the Screename (screen_name), list of followers (@user_name), and gender percentage (@gender_percentage).
If anyone has any idea of how to begin breaking this down and where to being storing the data please let me know
My code is displayed here.
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