I’m trying to learn the koala gem to link Facebook with my Ruby on Rails application. I’m starting to get the hang of it, but I’m running into some serious mental blocks!
def friends
facebook.fql_query("SELECT uid,username, is_app_user, name, pic_square FROM user WHERE uid IN(SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user=1");
rescue Koala::Facebook::APIError => e
logger.info e.to_s
nil
end
So, firstly, I’m using the FQL to search through a users friends. It returns a hash of details of users who are friends of current_user, the one signed into the app, and that have also connected with my application.
def friends_realname
names = friends.select {|f| f["is_app_user"] }.map {|f| f["name"]}
names.each { |name| puts name}
end
I’m selecting the above “user’s friends also using my app’s” names – and mapping them into an array. This returns an array: ["friend1's name", "friend2's name"]:
def friends_avatars
@avatars = friends.select {|f| f["is_app_user"] }.map {|f| f["pic_square"]}
end
I’m trying to do the same, but returning the URLs of the profile pictures of those same users. It returns an array:
["http://www.example.com/example.jpg", "http://www.example2.com/example2.jpg"]
I want to format the information from the returned arrays. So, for the real names, instead of returning the actual array, I want to return a list of names. And, obviously for the images, instead of returning an array of image urls, I actually want to ‘puts’ those images out in the view.
I’m thinking that I need to iterate through each of these arrays, and then use the each method to do something with each string in the array, e.g., puts img_tag?
Would something like this be possible?:
def friends_avatars
@avatars = friends.select {|f| f["is_app_user"] }.map {|f| f["pic_square"]}
@avatars.each { |avatar| puts image_tag "#{avatar}}"}
end
Just realised that image_tag is a helper method, so I can’t use it there.
I’ve also tried this in a view file:
<% for url in @avatars do %>
<%= puts "#{url}" %>
<% end %>
Which returns:
undefined method `each' for nil:NilClass
Anytime I try to return the strings within an array, they just return an array. Not really sure where to go from here.
This creates an array of two-element arrays, i.e.
Then you can iterate these in parallel:
Note that you don’t use
putsin your views, as this function outputs information to the console. Instead, you just use<%= ... %>to coerce Ruby code to be a string value and inject it at the appropriate spot in your output.Your original code is nice (insofar as you’ve wrapped your code in nicely-named methods) but does a little too much.
There is no need to
putsthe names here. The method only happens to return the correct value becauseeachreturns the item that was just iterated. Your methods can be written just as effectively as:If you happen to want to keep these methods, you can combine two arrays into one by using
Array#zip: