Domanda

I'm attempting to integrate a twitter feed into my Rails 4 application using this gem.

I've read the documentation on the github page but I'm running into a problem when trying to use a method in my view.

I have the following in an initializer file named twitter_init.rb (with my auth info):

client = Twitter::Streaming::Client.new do |config|
  config.consumer_key        = "YOUR_CONSUMER_KEY"
  config.consumer_secret     = "YOUR_CONSUMER_SECRET"
  config.access_token        = "YOUR_ACCESS_TOKEN"
  config.access_token_secret = "YOUR_ACCESS_SECRET"
end

When trying to use the following code in my view I receive the error undefined local variable or method 'client' for class#<#<class...>:...>:

<% client.sample do |tweet| %>
   <%= tweet.text %>
 <% end %>

Is there another step to exposing the client variable or maybe I didn't initialize it correctly?

È stato utile?

Soluzione

When you set client to the Twitter::Streaming::Client.new in you initiate file you created a local variable. This variable lost scope and is long gone by the time you get to your view.

To get it working remove twitter_init.rb

Then in the controller action that is being executed

@client = Twitter::Streaming::Client.new do |config|
  config.consumer_key        = "YOUR_CONSUMER_KEY"
  config.consumer_secret     = "YOUR_CONSUMER_SECRET"
  config.access_token        = "YOUR_ACCESS_TOKEN"
  config.access_token_secret = "YOUR_ACCESS_SECRET"
end

Then in the view

<% @client.sample do |tweet| %>
  <%= tweet.text %>
<% end %>

Notice the @ symbols.

This does however violate the skinny controller thick model convention and should be initialized elsewhere like in a service.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top