How to get the latest two posts with images - ruby-on-rails

We're using the tumblr gem to get posts from our blog. We get the posts like this:
client = Tumblr::Client.new
posts = client.posts("blog_url", :type => "text", :limit => 2)["posts"] #gets a posts array
In Tumblr the images are stored in the post body, so you have to search the post body for img tags, for example, the following query gets the image from the first post:
posts = client.posts("blog_url", :type => "text", :limit => 2)["posts"][0]["body"][/<img.*/]
But what if there isn't an imageā€¦ It returns nil and doesn't display an image.
I want to find the two most recent posts with images, how would I do that? Any ideas?

Make the :limit more than 2 (the documented limit is up to 20 at a time, undocumented limit seems to be 50). You can use :offset to retrieve in batches. Ignore returns of nil until you have collected two valid image posts.
As an aside you say "In Tumblr the images are stored in the post body". This is true if posts are of the type text. But there are also photo type posts. I assume you are aware of this?
The reason I ask is if you are only posting photos, or photos with brief notes. You could make photo posts with captions. You would then be able to request :type=>"photo" with :limit=>2
Alternatively - you could tag all your image blog posts with for example "image". You can then run your :limit=>2 search with :tag=>"image"
Hope that helps in some way :)

Related

Selecting content to feature

in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.
This is what I'm using to select posts at the moment:
posts_controller.rb
favorite_post_ids = [8,2,5]
#favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
#new_posts = Post.find(new_post_ids)
and then in the view I loop over them to display the posts.
However, once a post is deleted and the controller can no longer find it, I get an error that says
Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)
What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.
UPDATE :
I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.
How would you solve this problem?
Make your posts have flag favorite of type boolean. Then you'd select them like this:
#favorite_posts = Post.where(favorite: true).limit(3)
And for new posts, you can use the timestamp
#new_posts = Post.order(created_at: :desc).limit(3)
Look, no hardcoding!
I dont encourage hardcoding. But still if that is your requirement, try
favorite_post_ids = [8,2,5]
#favorite_posts = Post.where(:id => favorite_post_ids)
new_post_ids = [1,2,5]
#new_posts = Post.where(:id => new_post_ids)

Timeline of search/tweets and next_results and refresh_url fileds

My web application should have next/previous results for navigating the search timeline. I already made it by using field next_resultsfor next, and pushing refresh_url into javascript array for "previous" navigating. And it worked then (3-4) days ago. After 1-2 days api calls were not returning field next_results, omitted completely, and today that field is returning same value for all "next" calls, so you are hitting next and you are refreshing the page basically. There are also fields since_id for newer and max_id for older results in search_metadata node, so I can make queries using that values... I could also get those id's from returned tweet objects, and use them, not relying on api search_metadata completely...
So I'm asking if someone already dealt with this, what is the best way to do it, not having to check code every day what twitter-api is returning? I know there is twitter support, I think there are people on this site that has done this. I also have read docs on this.
https://dev.twitter.com/docs/working-with-timelines
https://dev.twitter.com/docs/api/1.1/get/search/tweets
Here is search_metadata node example to ilustrate.
[search_metadata] => Array
(
[completed_in] => 0.057
[max_id] => 4.1747346982858E+17
[max_id_str] => 417473469828583425
[next_results] => ?max_id=416844457594855423&q=place&result_type=mixed
[query] => place
[refresh_url] => ?since_id=417473469828583425&q=place&result_type=mixed
[count] => 15
[since_id] => 0
[since_id_str] => 0
)
Ime Ime, "what is the best way to do it", not sure but this is how I used max_id
present in next_results to fetch tweets from timeline.
Twython search API with next_results
Hope it helps.

Is it possible to use more_like_this across different data types?

The documentation for more_like_this shows how you can use it to get more of the same type of content that is similar based on a criteria:
class Post < ActiveRecord::Base
searchable do
# The :more_like_this option must be set to true
text :body, :more_like_this => true
end
end
post = Post.first
results = Sunspot.more_like_this(post) do
fields :body
minimum_term_frequency 5
end
I'm wondering if it's possible to return related items that are a different data type. For example, Videos that are related/similar to Articles.
I guess this depends on whether more_like_this is operating along the lines of "more Articles that are similar to this Article based on a set of criteria" or if it's operating along the lines of "more things that are similar to this Article based on a set of criteria"...
My use-case for this would be if I'm displaying an Article, and I want to show related content on the side of the page - things that might be other Articles, Videos in the same category, or Events on related topics, etc.
http://sunspot.github.com/sunspot/docs/Sunspot.html#more_like_this-class_method
+ (Object) more_like_this(object, *types, &block) Initiate a MoreLikeThis search. MoreLikeThis is a special type of search that
finds similar documents using fulltext comparison. The fields to be
compared are text fields set up with the :more_like_this option
set to true. By default, more like this returns objects of the same
type as the object used for comparison, but a list of types can
optionally be passed to this method to return similar documents of
other types. This will only work for types that have common fields.
example:
post = Post.first
Sunspot.more_like_this(post, Post, Page) do
fields :title, :body
with(:updated_at).greater_than(1.month.ago)
facet(:category_ids)
end
see also: http://sunspot.github.com/sunspot/docs/Sunspot/Query/MoreLikeThis.html

Creating Table Filters

I have a simple table with 3 columns like so
table
thead
th Element
th Owner
th Progress
tbody
== render :partial => "element_row" :collection => #elements :as => table_element
Each element is unique, and one owner may have several elements. There are a few different types of "progress" e.g. "started", "not started", and "completed".
I want to create a few links that filter the table. For example, I want to create an started link where when the user clicks on the link, the table is filtered down to only show rows where "started" is displayed. Another example of a filter is by owner.
Does anyone have any suggestions for how to do this?
If you're looking for a gem to help you, Ransack is a great, popular, and active project for searching (and by extension, filtering) ActiveRecord data.
If you check out Ernie's demo site you can see how the search parameters modify the URL through GET queries. You could easily create links like your desired started link to mock these GET form requests.
If you want to do this on the server side, add a filter method to the controller that uses link parameters to filter the #elements.
If you selecting #elements from the database using ActiveRecord, you could do:
#elements = Element.where(progress: params[:progress])
If you just want to filter the #elements in memory, you could do:
#elements = #elements.select{ |element| element.progress == params[:progress] }

how to store facebook friends to DB (newbie)

i'm creating a facebook-app for university project and i'm trying to store all my friends in the DB.
By using the API-syntax "me/friends" i get a facebook-respond looking like this:
{"data"=>[{"name"=>"Albert Einstein", "id"=>"11111111"}, {"name"=>"Max Mustermann", "id"=>"222222222"}, {"name"=>"Just Another Name", "id"=>"333333333"}]}
I believe its a json-object, but i'm not sure.
Question: How can i save the data, i need a DB with all the User-IDs of my friends.
Thx!
Edit:
Hey, this is what i have searched for. But i still get an error and don't know why.
My code:
def insert_1
fb_friends = rest_graph.get('me/friends')
fb_friends[:data].each do |f|
#friend = Model.new(:name => f["name"] )
#friend.save
end
end
I get an Heroku error (We're sorry, but something went wrong.)
You have two options -
Option 1-
You can create a friends table which will belong to users table. If a user has 200 friends, it will create 200 entries in friends table all belonging to the user via has_many-belongs_to relationship. For storing data, you just have to iterate over facebook friends hash and then save each of them separately
Pros : You can search for any friend separately.
Cons : There will be so many of friend entries. Saving them will take time, if somebody has many friends(say 500-700). Repeating entries will be created for mutual friends.
Options 2
You can add a friends column in your users table and declare this in your user.rb
serialize :friends
This way, you just have to pass a hash object to friends attribute of user table, and rails will save that in yaml format for you. When you will do #user.friends, rails will again convert that yaml formatted data to hash object and return it.
Pros : There will be only one query to save all users. You can iterate through this hash to show list of all friends.
Cons : You can't update them separately, you will update all together. Not good if you want to store some other information in relation to user's friends.
Update
as per your code example above
fb_friends = #your logic to get data as shown above.
fb_friends[:data].each do |f|
#friend = Friend.new(:name => f["name"],:fb_user_id => f["id"] )#creating Friend model obj.
#friend.save
end

Resources