Search code examples
ruby-on-railsrubysidekiq

Proper way to organize blocks of code within a class?


I have a class in a Sidekiq worker that has blocks of code that I'd love to move into separate files for organizational purposes. How would I do that?

# /app/workers/pull_data_worker.rb
class PullDataWorker
  include Sidekiq::Worker

  def perform(account_id)
    account = Account.find(account_id)

    # Chunk A
    # block of code that does something

    # Chunk B
    # block of code that does something

    # Chunk C
    # block of code that does something
  end
end

Each of those "chunks" is just various blocks of code that process some data. They aren't methods are anything. Just basic things that loop through some data pulled from different third-party APIs.

So, what's the proper way to separate those?

Running Ruby 2.0.0 on a Rails 4.0.1 app.


Solution

  • You have at least the choice of extract into methods, classes or modules. All this falls into the task of refactoring, for which nice tutorials and books are written, giving rationales about which path to choose.

    In my opinion, start extracting methods and see what consequences it has. Its hard to judge based on your limited example. Given robbrits answer, you could also define the method for the very same class (PullDataWorker) in another file - for sake of maintainability I would not do that though - somebody might end up not knowing that additional methods are defined somewhere else.

    class PullDataWorker
      include Sidekiq::Worker
      include ThisProject::ChunkC
    
     def perform(account_id)
        account = Account.find(account_id)
    
        # Extracted method, see below.
        do_chunk_a account
    
        # From other class, see below.
        ChunkBDoer.new.do_stuff
    
        # From module ThisProject::ChunkC .
        chunkC_do_stuff
      end
    
      private
    
      def do_chunk_a(account)
      end
    end
    
    class ChunkBDoer
      def do_stuff
      end
    end