Search code examples
ruby-on-railstumblr

How to get the latest two posts with images


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?


Solution

  • 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 :)