How to use dual-purpose accessors in Ruby to create a DSL

Ruby posted 29 days ago by christian

Instead of this:

   1  Sitemap('public/sitemap.xml') do
   2    self.stylesheet = 'public/sitemap.xls'  
   3    self.ping = ['http://www.google.com', 'http://www.google.com']  
   4  end

You could write this:

   1  Sitemap('public/sitemap.xml') do
   2    stylesheet 'public/sitemap.xls'  
   3    ping ['http://www.google.com', 'http://www.google.com']  
   4  end

Using dual-purpose accessors:

   1  class Sitemap
   2    def stylesheet(path = nil) 
   3      return @path unless path
   4     @path = path
   5    end
   6    alias_method :stylesheet=, :stylesheet 
   7    ...
   8  end

Tagged ruby, dsl

How to get ActiveRecord and Rails to print SQL to the production log

Ruby posted 29 days ago by christian

Add to the end of config/environment.rb:

   1  ActiveRecord::Base.logger.level = Logger::DEBUG

Config/environments/production.rb might also work.

Tagged sql, production, activerecord, rails, logging

How to customize Hirb output

Ruby posted 3 months ago by christian

Only print id, created_at and title for FeedItem class:

   1  Hirb.disable
   2    Hirb.enable :output => {
   3      "FeedItem"=>{
   4        :options=>{
   5          :fields=>%w{id created_at title}
   6        }
   7      }
   8    }

Tagged hirb, irb, console, rails

How to scrape a Amazon Listmania list with Hpricot and Ruby

Ruby posted 3 months ago by christian

   1  html =  open('http://www.amazon.com/Nick-Hornby-and-Company/lm/1X1GGDBXARHZ6/ref=cm_lm_toplist_fullview_1')
   2  
   3  page = Hpricot(html)
   4  
   5  xpath = "td[@class='listItem']//input[@name='asin.1']"
   6  
   7  page.search(xpath).each do |book|
   8    puts book['value']
   9  end

Tagged amazon, hpricot, scrape

How to access Amazon product data with Ruby/AWS and the Amazon Associates Web Services API

Ruby posted 3 months ago by christian

First you need to decide which of the following Ruby libraries you want to use:

You can also find the code on GitHub.

In this example I’ve decided to go with Ruby/AWS because [insert reason here].

Installing Ruby/AWS

   1  curl -O http://www.caliban.org/files/ruby/ruby-aws-0.7.0.tar.gz
   2  tar zxvf ruby-aws-0.7.0.tar.gz
   3  cd ruby-aws-0.7.0
   4  ruby setup.rb config
   5  ruby setup.rb setup
   6  sudo ruby setup.rb install

Using Ruby/AWS

With Ruby/AWS installed you can now run this code:

   1  #!/usr/bin/ruby -w
   2  
   3  require 'amazon/aws'
   4  require 'amazon/aws/search'
   5   
   6  include Amazon::AWS
   7  include Amazon::AWS::Search
   8  
   9  # Example of a batch operation, using the ASIN as the shared ID.
  10  #
  11  # The MerchantId restriction is to ensure that we retrieve only items that
  12  # are for sale by Amazon. This is important when we later want to retrieve the
  13  # availability status.
  14  #
  15  il = ItemLookup.new( 'ASIN', { 'ItemId' => 'B000AE4QEC', 'MerchantId' => 'Amazon' })
  16   
  17  # You can have multiple response groups.
  18  #
  19  rg = ResponseGroup.new( 'Medium', 'Offers', 'Reviews' )
  20   
  21  req = Request.new()
  22  req.locale = 'uk'
  23   
  24  resp = req.search( il, rg )
  25  item_sets = resp.item_lookup_response[0].items
  26   
  27  item_sets.each do |item_set|
  28    item_set.item.each do |item|
  29      attribs = item.item_attributes[0]
  30      puts attribs.label
  31      if attribs.list_price
  32        puts attribs.title, attribs.list_price[0].formatted_price
  33      end
  34    
  35      # Availability has become a cumbersome thing to retrieve in AWSv4.
  36      #
  37      puts 'Availability: %s' %
  38        [ item.offers[0].offer[0].offer_listing[0].availability ]
  39      puts 'Average rating: %s' % [ item.customer_reviews[0].average_rating ]
  40      puts 'Reviewed by %s customers.' %
  41        [ item.customer_reviews[0].total_reviews ]
  42    
  43      puts 'Customers said:'
  44      item.customer_reviews[0].review.each do |review|
  45        puts ' %s (%s votes)' % [ review.summary, review.total_votes ]
  46      end
  47    
  48      puts
  49    end
  50  end

You’ll get this error:

   1  /opt/local/lib/ruby/site_ruby/1.8/amazon/aws.rb:138:in `get_page': HTTP response code 400 (Amazon::AWS::HTTPError)

You probably ran the code after August 2009 which is when Amazon started requiring signed requests.

Now if you run the code with ruby -d code.rb you’ll see that the request signature is missing:

   1  <?xml version="1.0"?>
   2  <ItemSearchErrorResponse xmlns="http://ecs.amazonaws.com/doc/2008-08-19/"><Error><Code>MissingParameter</Code><Message>The request must contain the parameter Signature.</Message></Error><RequestID>13563d70-7696-4b8f-afa3-064184874620</RequestID></ItemSearchErrorResponse>

This takes us to the next topic.

Configuring Ruby/AWS

Create a file called ~/.amazonrc and put the following in it:

   1  key_id = 'xxx'
   2  secret_key_id = 'xxx'
   3  associate = 'xxx-20'
   4  cache = false
   5  locale = 'uk'
   6  encoding = 'iso-8859-15'

Next sign up you need to:

That’s it. If you want, have a look at the examples

Tagged ruby-aws, amazon-ecs, amazon