csv - Can someone help me understand this code regarding twitter api and ruby? It is a method that retrieves all followers based on twitter handle -


what csv do? (i know gem)

what slice_size? (line 13)

why csv insided straight braces?(line 16) csv |csv|

can explain whole lines 17, 18, 19?i lost on that?

-----------------code--------------------------------------------------

    require 'twitter'     require 'csv'     def twitter_client         @twitter_client ||= twitter::rest::client.new |config|             config.consumer_key = ""             config.consumer_secret = ""             config.access_token = ""             config.access_token_secret = ""        end    end     slice_size = 100     def fetch_all_friends(twitter_username)        csv do|csv|            twitter_client.follower_ids(twitter_username).each_slice            (slice_size).with_index |slice, i|                   twitter_client.users(slice).each_with_index |f, j|                        csv << [i * slice_size + j + 1, f.name,                        f.screen_name]                  end            end        end    end 

csv class, implementing handling of csv data, as follows documentation.

each_slice method of enumerable takes many elements source collection per each iteration. done reduce memory requirements of computation or, possibly, delay fetching more data until current chunk processed, example. slice_size value how many elements take.

csv |csv| initializes csv object , passes down block parameter. way organize code e.g. initialization separate business logic of block. block delimited do , end keywords.

the next 2 lines single statement:

twitter_client.follower_ids(twitter_username).each_slice(slice_size).with_index |slice, i| 

it takes collection of follower ids of twitter_username twitter api, takes elements there in chunks of slice_size , passes each chunk , index block. contents of block executed many times there chunks of slice_size in follower_ids.

the next line

twitter_client.users(slice).each_with_index |f, j| 

works on element of current chunk. takes each element of chunk , passes along index within chunk yet block.

up point it's more of collection handling actual business logic.

the inner statement

csv << [i * slice_size + j + 1, f.name, f.screen_name] 

creates array of 3 fields: index of sort, twitter-supplied name , screen_name. array represents csv line. << operator pushes array csv object mentioned before. csv object adds has collected time.

when code finishes have csv object filled data received twitter api , ready saved disk.


Comments