0

按照本教程 (http://arfon.org/twitter-streaming-with-eventmachine-and-dynamodb) 尝试启动 Amazon 监听环境。接收特定的推文并将它们添加到发电机数据库(通过新线程)。一切正常,但是当使用 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  
}  

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

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

4

1 回答 1

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  
}

您可能还想停止捕获“异常”,而是捕获“标准错误”,否则您将无法使用 CTRL+C 等程序。

于 2012-03-28T02:59:13.340 回答