<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sean Cook on Medium]]></title>
        <description><![CDATA[Stories by Sean Cook on Medium]]></description>
        <link>https://medium.com/@amco_sean?source=rss-2a48119b116b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*A0taz6avMnaR6tUa.</url>
            <title>Stories by Sean Cook on Medium</title>
            <link>https://medium.com/@amco_sean?source=rss-2a48119b116b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:32:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amco_sean/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Refactoring Similar Nested Hash Iterations with Lambdas]]></title>
            <link>https://medium.com/amco/refactoring-similar-nested-hash-iterations-with-lambdas-58381a47021a?source=rss-2a48119b116b------2</link>
            <guid isPermaLink="false">https://medium.com/p/58381a47021a</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Sean Cook]]></dc:creator>
            <pubDate>Wed, 29 Nov 2017 18:49:44 GMT</pubDate>
            <atom:updated>2017-12-14T21:31:32.708Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I had the opportunity to write a rake task that iterated through a few CouchDB document nested hashes. The task was simple enough; I had to remove some properties that were rendered redundant by a recent refactor in one of our applications. Pay close attention to similarities in each nested iteration as the data in the hash is more or less irrelevant to this refactor. Here is a slice of the code that was in the first version.</p><pre>pub.doc[&#39;programs&#39;].each do |program, grades|<br>  next if program == &#39;_order&#39;<br>  grades.delete &#39;icons&#39;<br>  grades[&#39;grades&#39;].each do |grade, units|<br>    next if grade == &#39;_order&#39;<br>    units.delete &#39;icons&#39;<br>    units[&#39;units&#39;].each do |unit, urls|<br>      next if unit == &#39;_order&#39;<br>      urls.delete &#39;icons&#39;<br>    end<br>  end<br>end</pre><p>I ran the task with a few put statements, felt relatively satisfied with the result, deleted the put statements, and then began to notice that each nested iteration seems very similar. As a thought challenge, I pondered how I could DRY this up. First, since each iteration had two arguments I knew I had to look for a lambda solution. I took my first stab at it my trying to replicate the innermost block.</p><pre>pub.doc[&#39;programs&#39;].each do |program, grades|<br>  next if program == &#39;_order&#39;<br>  grades.delete &#39;icons&#39;<br>  grades[&#39;grades&#39;].each do |grade, units|<br>    next if grade == &#39;_order&#39;<br>    units.delete &#39;icons&#39;<br>    units[&#39;units&#39;].each &amp;remove_icons<br>  end<br>end</pre><pre>def remove_icons<br>  lambda do |key, value|<br>    next if key == &#39;_order&#39;<br>    value.delete &#39;icons&#39;<br>  end<br>end</pre><p>This worked, but the next two nested hash iterations proved to be a bit more challenging. I had to figure out how to access the hash `units` with the key ‘units’. I took a few minutes to muck with the syntax, and I ended up with the following approach to DRY the next nested iteration.</p><pre>pub.doc[‘programs’].each do |program, grades|<br>  next if program == ‘_order’<br>  grades.delete ‘icons’<br>  grades[‘grades’].each &amp;remove_icons(‘units’)<br>end</pre><pre>def remove_icons value_key=nil<br>  lambda do |key, value|<br>    next if key == ‘_order’<br>    value.delete ‘icons’<br>    value[value_key].each(&amp;remove_icons) if value_key<br>  end<br>end</pre><p>With a small bit of rearranging that includes a new block argument we can further update this method to handle any scenario in which the nested hashes have same keys with a recursive API.</p><pre>pub.doc[‘programs’].each &amp;remove_icons(‘grades’, &amp;remove_icons(‘units’))</pre><pre>def remove_icons value_key=nil, &amp;block<br>  lambda do |key, value|<br>    next if key == ‘_order’<br>    value.delete ‘icons’<br>    if value_key<br>      value[value_key].each(&amp;block) if block_given?<br>      value[value_key].each(&amp;remove_icons) unless block_given?<br>    end<br>  end<br>end</pre><p>This is overkill for a one-off data migration task, however if you find yourself needing to modify your data’s nested hashes in a similar fashion in each iteration with the business logic is prevalent in your code, this could prove to be a relatively convenient way to DRY up your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58381a47021a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amco/refactoring-similar-nested-hash-iterations-with-lambdas-58381a47021a">Refactoring Similar Nested Hash Iterations with Lambdas</a> was originally published in <a href="https://medium.com/amco">Amco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sidekiq Tricks: Don’t do the same work twice]]></title>
            <link>https://medium.com/amco/sidekiq-tricks-dont-do-the-same-work-twice-378d4ee4c2d8?source=rss-2a48119b116b------2</link>
            <guid isPermaLink="false">https://medium.com/p/378d4ee4c2d8</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Sean Cook]]></dc:creator>
            <pubDate>Tue, 31 May 2016 21:26:59 GMT</pubDate>
            <atom:updated>2016-06-01T00:50:13.239Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Sidekiq Tricks: Don’t do the same work twice</strong></p><p>Here at <a href="http://www.amco.me/">Amco</a> we make extensive use of <a href="http://sidekiq.org/">Sidekiq</a> for background processing. Background jobs are useful for delaying code execution until the server can handle the load. This lends itself well to things like sending emails and scheduling tasks to run later. We leverage the asynchronous nature of Sidekiq jobs — through the use of batches — to create an extensive network of jobs that, with a touch of synchronicity, makes easy work of our processing needs. In order to serve our Editorial department, we developed the method I will discuss today for our app in order to delay processing of content until our editorial department has everything prepared.</p><p>The trick to managing this large queue of asynchronous jobs is to add a touch of order when enqueuing tasks.</p><p>The principle I will cover today is simple:</p><p><em>Don’t do the same work twice.</em></p><p>The old joke goes, “programmers are lazy” (or efficient, if you so desire); we don’t like to do the same work twice. That’s what the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> principle is all about. The same idea can be applied to your background jobs. When you use “#perform_async”, it will add the Sidekiq job directly to the queue, and it will run whenever resources are available. These jobs are difficult to cancel as the delay between Redis and Sidekiq could cause the job to be canceled without enqueuing the new job. This technique focuses on limiting the jobs in the scheduled and retry queues.</p><pre>class FunWorker<br>  include Sidekiq::Worker</pre><pre>  def perform fun_thing_id<br>    fun_thing = FunThing.find fun_thing_id<br>    fun_thing.have_fun!<br>  end<br>end</pre><p>Adding in delays are useful if you expect there to be frequent changes, only allowing the job to be executed when all the changes have completed. Let’s say that your application schedules a job of the FunWorker class to be added to the queue 5 minutes after the user clicks a button.</p><pre>FunWorker.perform_in(5.minutes, some.id)</pre><p>That job will be sitting in the ScheduledSet for five minutes. Now, say that same user clicked the button an extra time, thinking that the first attempt didn’t go through. Another job of the same class, with the same arguments, is put into the ScheduledSet.</p><p>If your jobs are truly idempotent, then isn’t a stretch to say that you’ve scheduled the two jobs to do the same work. This can be a nuisance, as you’d like your resources to be free to handle other requests. Our custom module Cancelerizer to come to save the day.</p><pre>module Cancelerizer<br>  extend ActiveSupport::Concern<br>  module ClassMethods</pre><pre>    def cancel_perform *args<br>      sleep rand(1..9)<br>      Sidekiq::ScheduledSet.new.each { |job| job.delete if same_job?(job, args) }<br>      Sidekiq::Queue.new.each { |job| job.delete if same_job?(job, args) }<br>    end</pre><pre>    alias_method :cancel_it, :cancel_perform</pre><pre>    private</pre><pre>    def same_job? job, args<br>      return false unless job.args.count == args.count<br>      arg_pairings = job.args.zip args<br>      self.name == job.klass &amp;&amp; arg_pairings.all? { |job_arg, arg| job_arg == arg }<br>    end<br>  end<br>end</pre><p>This lightweight module can give your Workers the flexibility to kill a job and re-queue it back with the original delay. This can be useful for designing self-healing systems, which delay the work until everything is ready to be processed finally. In order to benefit from the Cancelerizer code we must use a proxy to the perform method. My team favors the use of “#process”, but use whatever works best for your team. Let’s take a look.</p><pre>class FunWorker<br>  include Sidekiq::Worker<br>  include Cancelerizer</pre><pre>  DELAY = 5.minutes</pre><pre>  class &lt;&lt; self<br>    def process fun_thing_id<br>      cancel_perform fun_thing_id<br>      perform_in DELAY, fun_thing_id<br>    end<br>  end</pre><pre>  def perform fun_thing_id<br>    fun_thing = FunThing.find fun_thing_id<br>    fun_thing.have_fun!<br>  end<br>end</pre><p>Excellent! Now we can schedule our jobs without fear of doing the same work twice. Mission Accomplished!</p><p>Let’s explore the ramifications out in the real world. The most obvious benefit, as mentioned above, is that you free up resources to do other meaningful work. This in and of itself is incredibly useful for almost any use case.</p><p>A second, less obvious, benefit comes when your solution requires that you wait for all of the information to do the work. The strategy here is to delay all the work until everything is ready. As described above, we use this technique to delay all of the big work until editorial has prepared all of the content. We need to wait until all of the audio files related to a certain build have completed. However, since these audio files are not originally part of a batch, we can’t use “#on_success” calls do something afterwards. In order to mimic this functionality, we queue up another job (FinalJob) at the end of each of the current audio job’s execution. When the processing of the audio files is complete, they will cancel any previous FinalJobs in the queue with the same arguments, and then add it back to the ScheduledSet. This allows our editorial department to change files around and get the content just right before the system finalizes the build.</p><p>I hope this improves your Sidekiq Experience™.</p><p>In the next installment, I will explore how to integrate this technique in conjunction with Sidekiq Batches for even more control over your background processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=378d4ee4c2d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amco/sidekiq-tricks-dont-do-the-same-work-twice-378d4ee4c2d8">Sidekiq Tricks: Don’t do the same work twice</a> was originally published in <a href="https://medium.com/amco">Amco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>