Search code examples
ruby-on-railstwittertwitter-oauthomniauth

Pass devise current_user to a method in a lib file


I am trying to pass the devise @current_user from my application_controller to a class method in a library file. This is to use the Twitter API. I can get it working by writing the various twitter methods in the application_controller file, but I was wondering how I would do it using a separate lib. file and class instead? The code is as follows:

lib/twitter_api.rb

class TwitterApi

def self.our_public_tweets
  client.user_timeline('BBCNews', count: 1, exclude_replies: true, include_rts: false)
end

def self.followers
  client.followers.take(5)
end

def self.client
  @client ||= Twitter::REST::Client.new do |config|
   config.consumer_key        = Rails.application.secrets.twitter_api_key
   config.consumer_secret     = Rails.application.secrets.twitter_api_secret
   config.access_token        = current_user.token
   config.access_token_secret = current_user.secret
    end
  end
end

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

view file: index.html.erb

  <%= TwitterApi.our_public_tweets.each do |tweet| %>
    <%= tweet.text %>
  <% end %>

  <%= TwitterApi.followers.each do |follower| %>
    <%= follower.name %>
  <% end %>

Solution

  • I woudl make an instance of the class rather than using class methods.

    class UserTwitter
      def initialize(user)
        @user = user
      end
    
      def our_public_tweets
        client.user_timeline('BBCNews', count: 1, exclude_replies: true, include_rts: false)
      end
    
      def followers
        client.followers.take(5)
      end
    
      private
    
      attr_reader :user
    
      def client
        @client ||= Twitter::REST::Client.new do |config|
          config.consumer_key = Rails.application.secrets.twitter_api_key
          config.consumer_secret = Rails.application.secrets.twitter_api_secret
          config.access_token = user.token
          config.access_token_secret = user.secret
        end
      end
    end
    

    Then in your controller

    def index
      @user_twitter = UserTwitter.new(current_user)
    end
    

    Which then means in your view

    <% @user_twitter.our_public_tweets.each do |tweet| %>
      <%= tweet.text %>
    <% end %>
    
    <% @user_twitter.followers.each do |follower| %>
      <%= follower.name %>
    <% end %>