简体   繁体   中英

Where in Rails Project to Place Code

I am attempting to classify whether or not tweets are geo-tagged based on certain keywords using the Ruby Twitter Gem. I can do this just fine from the rails console, but I went to reflect my findings in a view, and I just don't know how to do that.

Here is what I am doing on the command line:

I begin by setting up my streaming client:

client = Twitter::Streaming::Client.new do |config|
  config.consumer_key        = "MYCODE"
  config.consumer_secret     = "NOTYOURS"
  config.access_token        = "HANSHOT"
  config.access_token_secret = "FIRST"
end

Then I initialize my counts:

count = 0
geo = 0

And finally I paste in my brief script and run enter:

client.filter(:track => "cat") do |tweet|
    count += 1

    if(tweet.place.nil?)
      # Do nothing
    else
      geo += 1
    end
end

To access my results, I need to Ctrl+C and type 'geo' or 'count' into the console.

In an ideal world, I'd have a view that displayed the count and geo numbers. Said view would refresh with the updated numbers whenever I refreshed the view.

I tried throwing this in a controller, but then the page never loads, because presumably, the controller is infinitely parsing the stream and never gets a chance to render.

I stuck it in a model file, but that also did nothing.

So, am I going about this the totally wrong way? Is getting these numbers impossible from anywhere but the IRB?

There's a few things you need to keep in mind when creating controller code:

  • Everything you want to appear in a view must be provided by a database call, a helper method or an instance variable.
  • The controller must complete whatever operation it's scheduled to perform in a timely manner. Infinite loops and long running operations taking several minutes are severely problematic.
  • Views can do their own computation, generally they're free to run arbitrary Ruby code, but it's considered bad form to do the heavy lifting there as that's the primary responsibility of the controller.

So in general terms, your controller code might look like:

def index
  @client = Twitter::Streaming::Client.new do |config|
    # ... (Configuration)
  end

  @count = 0
  @geo = 0

  client.filter(track: "cat") do |tweet|
    @count += 1

    if (tweet.place)
      @geo += 1
    end

    break if (@count > 10)
  end
end

This presumes the client.filter operation can produce ten results in a short period of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM