Twitter integration rails 4 app

雨燕双飞 提交于 2019-12-10 00:10:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19057123/twitter-integration-rails-4-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!