Eventmachine gem - > spawn_threadpool中的块

时间:2012-03-24 20:12:40

标签: ruby rubygems eventmachine tweets amazon-dynamodb

按照本教程(http://arfon.org/twitter-streaming-with-eventmachine-and-dynamodb)试图启动亚马逊听力环境。接收特定的推文并将它们添加到dynamo db(通过新线程)。一切正常,但是当使用eventmachine生成线程时,我得到以下结果:

require 'aws-sdk'
require 'eventmachine'
require 'tweetstream'

AWS_ACCESS_KEY = 'HERE IT IS'
AWS_SECRET_KEY = 'YES HERE'


dynamo_db = AWS::DynamoDB.new(:access_key_id => AWS_ACCESS_KEY, :secret_access_key => AWS_SECRET_KEY)

table = dynamo_db.tables['tweets']
table.load_schema

TweetStream.configure do |config|
  config.username = 'geezlouis'
  config.password = 'password'
  config.auth_method = :basic
end

EM.run{
  client = TweetStream::Client.new

  def write_to_dynamo(status)
    EM.defer do
      tweet_hash = {:user_id => status.user.id, 
                    :created_at => status.created_at,
                    :id => status.id,
                    :screen_name => status.user.screen_name}

      begin
        table.items.create(tweet_hash)
      rescue Exception => e  
        puts e.message  
        puts e.backtrace.inspect
      end
    end
  end

  client.track("Romney", "Gingrich") do |status|
    write_to_dynamo(status)
  end  
}  
  

未定义的局部变量或方法`table'for main:Object

["tweets.rb:31:in `block in write_to_dynamo'", "/.rvm/gems/ruby-1.9.3-p125/gems/eventmachine-0.12.10/lib/eventmachine.rb:1060:in
     spawn_threadpool中的

call'", "/.rvm/gems/ruby-1.9.3-p125/gems/eventmachine-0.12.10/lib/eventmachine.rb:1060:in 块“”]

1 个答案:

答案 0 :(得分:0)

table是一个局部变量,因此您无法从方法范围访问它。

您需要以下内容:

require 'aws-sdk'
require 'eventmachine'
require 'tweetstream'

AWS_ACCESS_KEY = 'HERE IT IS'
AWS_SECRET_KEY = 'YES HERE'


dynamo_db = AWS::DynamoDB.new(:access_key_id => AWS_ACCESS_KEY, :secret_access_key => AWS_SECRET_KEY)

table = dynamo_db.tables['tweets']
table.load_schema

TweetStream.configure do |config|
  config.username = 'geezlouis'
  config.password = 'password'
  config.auth_method = :basic
end

EM.run{
  client = TweetStream::Client.new

  def write_to_dynamo(status, table)
    EM.defer do
      tweet_hash = {:user_id => status.user.id, 
                    :created_at => status.created_at,
                    :id => status.id,
                    :screen_name => status.user.screen_name}

      begin
        table.items.create(tweet_hash)
      rescue Exception => e  
        puts e.message  
        puts e.backtrace.inspect
      end
    end
  end

  client.track("Romney", "Gingrich") do |status|
    write_to_dynamo(status, table)
  end  
}

您也可能想要停止捕获“异常”并改为捕获“StandardError”,否则您将无法使用例如CTRL + C程序。