Google Base on Rails
I was surprised to come up empty handed when searching for a Google Base Rails plugin. I wanted something that would allow me to easily create a feed into Google Base using their API. I didn’t find anything so I took the quick and short term solution and created my own Google Base xml feed. Its based on RSS 2.0 so its not incredibly difficult but I could have saved a few minutes if it was already written for me so here it is. My Google Base xml generator in Ruby on Rails. Its not complete and only has the fields that I specifically wanted for my products. Your feed will likely contain other fields so check the Google Base docs for more information on customizing it. You’ll notice that I thought Google Base was going to pull my xml feed when I initially wrote this but it turns out I have to use the API and this is just good for generating the xml file which you then have to manually upload to Google Base.
First, I added this to route.rb
map.connect ‘google-base.xml’,
:controller => ‘google’,
:action => ‘base_feed’
Then I created controllers/google_controller.rb
class GoogleController < ApplicationController
def base_feed
@products = Product.find(:all)
end
end
And finally, I create views/google/base_feed.rxml
xml.instruct! :xml, :version=>"1.0"
xml.rss(:version=>"2.0", ‘xmlns:g’ => "http://base.google.com/ns/1.0"){
xml.channel{
xml.title("My Site products")
xml.link("http://brianmcquay.com/google-base.xml")
xml.description("My products are better than yours. You can touch them but I have to charge.")
xml.language(‘en-us’)
for product in @products
xml.item do
xml.title(product.name)
xml.link(product_url(product.id.to_s))
xml.description(product.description)
for photo in product.pictures
xml.tag! "g:image_link", photo_url(photo.id)
end
for category in product.categories
xml.tag! "g:product_type", category.name
end
xml.tag! "g:price", product.retail_price.to_s
xml.tag! "g:id", product.id.to_s
xml.tag! "g:payment_accepted", "Visa"
xml.tag! "g:payment_accepted", "MasterCard"
xml.tag! "g:tax_region", "Hawaii"
end
end
}
}
There are obviously calls to helper methods in the base_feed.rxml file like product_url and photo_url. I use those so I can easily generate pretty seo urls anywhere I need them. You’ll need to replace those with however you create your urls.
This should suffice for at most 31 days when all the products I just added will expire in Google Base. I doubt I’ll bother creating a Google Base Rails plugin unless I see a noticeable increase in traffic and sales so don’t hold your breath.
March 27th, 2008 at 12:42 am
Looks great! Can you publish the second part where you actually use the API to publish the feed? I can’t seem to find any rails code that works with Google Base.
Thanks!