Posting with the Ruby HTTPClient


We’ve arrived at the final piece of the puzzle when it comes to the latest WP MU mass posting addition to SEO tools.

In other words, it’s time to start posting articles to our blogs.

Using HTTPClient is kids play like with so much else in Ruby, as usual the author has put a lot of effort into ease of use. This is something I really appreciate when it comes to the Ruby community, the attention to clean interfaces.

Let’s list the code and talk some more below the listing.

def push_articles
    require 'httpclient'
    @msg = ""
    clnt = HTTPClient.new
    t = Time.new
    tnow = t.strftime("%Y-%m-%d %H:%M:%S")
    WpArticle.find(:all, :conditions => "published = 0").each do |a|
      pdata = {
        "post_title"        => a.subject,
        "post_content"      => a.content,
        "tags"              => a.tags,
        "categories"        => a.categories,
        "domain"            => a.wp_site.url,
        "passwd"            => "somepass",
        "post_author"       => 1,
        "post_date"         => tnow,
        "post_date_gmt"     => tnow,
        "post_status"       => "publish",
        "comment_status"    => "closed",
        "ping_status"       => "closed",
        'post_modified'     => tnow,
        'post_modified_gmt' => tnow,
        'post_type'         => 'post'
      }

      res = clnt.post(a.wp_site.wp_mu.url + "/wp_insert.php", pdata)
      @msg += "Posted <b>#{a.subject}</b> to <b>#{a.wp_site.name}</b>, the result: <b>#{res.inspect}</b><br><br>"
      if res
        a.published = 1
        a.save
      end
    end
  end

So we use ActiveRecord to fetch all unposted articles. Our earlier setup of foreign relations in the AR models serves us well here, for instance when we fetch the domain (a.wp_site.url) of the blog the article is to be posted to. The URL to post to is set in the MU object which we breezily access through a.wp_site.wp_mu.url.

Finally, if we were successful in posting the article we set it to published and save it.

I think the above example is a very good example of how RoR (AR to be specific) makes web development truly painless.


Related Posts

Tags: , , ,