Last active
December 28, 2015 09:29
-
-
Save stevenharman/7479046 to your computer and use it in GitHub Desktop.
Creating boundaries and pushing for objects to be context-free (or at least as low context) goes a long way. Here is an example of the kind of background jobs/workers I tend to write in Ruby/Ruby on Rails apps. This particular example is pulled straight from the http://brewdega.com source code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sidekiq' | |
module Import | |
class MatchJob | |
include Sidekiq::Worker | |
attr_reader :agent, :ledgers | |
# A facade for consumers, keeping them divorced from the Sidekiq API | |
def self.match(import_ledger) | |
job_id = perform_async(import_ledger.id) | |
import_ledger.attach_job(job_id) | |
end | |
# In production, this results in the collaborators being these real objects, | |
# but in tests I inject my own, stubbed, collaborators. Easy peasy! | |
def initialize(ledgers: Ledger, agent: Agent) | |
@ledgers = ledgers | |
@agent = agent | |
end | |
def perform(import_ledger_id) | |
ledger = ledgers.find(import_ledger_id) | |
agent.match(ledger) # All of the real work is delegated to `Import::Agent`! | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: The comments are not in the real source, I added them here to provide some insight into my aesthetic.