<?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 Leticia Esperon on Medium]]></title>
        <description><![CDATA[Stories by Leticia Esperon on Medium]]></description>
        <link>https://medium.com/@esperonleticia?source=rss-d7d993b6e198------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WcboXLbVQr0yAZQvarokBQ.png</url>
            <title>Stories by Leticia Esperon on Medium</title>
            <link>https://medium.com/@esperonleticia?source=rss-d7d993b6e198------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:03:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@esperonleticia/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[Why Rails’ destroy_async isn't orth the Hype]]></title>
            <link>https://medium.com/@esperonleticia/why-rails-destroy-async-isnt-orth-the-hype-81730d95e34d?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/81730d95e34d</guid>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 13:52:39 GMT</pubDate>
            <atom:updated>2024-08-07T13:57:12.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Rails’ destroy_async isn&#39;t worth the hype</h3><p>Rails 6.1 introduced the destroy_async feature to improve performance by offloading the deletion of associated records to background jobs. You can read more about this feature in the Rails <a href="https://guides.rubyonrails.org/6_1_release_notes.html#destroy-associations-async">release notes</a>, official <a href="https://edgeguides.rubyonrails.org/association_basics.html#options-for-belongs-to-dependent">documentation</a> and <a href="https://github.com/rails/rails/pull/40157">PR</a>.</p><p>The idea is simple: when you delete a parent record with an associated defined withdependent: :destroy_async keyword, Rails will delete the record immediately (synchronously), and then enqueues a job to destroy the associated records. This way, if the associated records are too many (N) , the main process doesn’t stall while the N “delete” DB requests are performed.</p><h3>Destroy_async doesn’t work if you are using Foreign Keys</h3><p>In most applications, <strong>data integrity </strong>is often prioritized over performance or developer convenience. Most smaller apps use foreign keys to ensure referential integrity in the database. Here’s the problem: if you have foreign keys, destroy_async can cause your deletion process to fail.</p><h3>Example Scenario</h3><p>Consider the following setup:</p><pre>class User &lt; ApplicationRecord<br>  has_many :learners, foreign_key: :user_id, dependent: :destroy_async<br>end</pre><p>When you try to delete a user, it outputs:</p><pre>user = FactoryBot.create(:user)<br>learner = FactoryBot.create(:learner, user: user)<br>user.destroy!</pre><pre>TRANSACTION (0.3ms)  BEGIN<br> Learner Load (0.3ms)  SELECT &quot;learners&quot;.* FROM &quot;learners&quot; WHERE &quot;learners&quot;.&quot;user_id&quot; = $1  [[&quot;user_id&quot;, 936]]<br> DELETE FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;id&quot; = $1  [[&quot;id&quot;, 936]]<br>ROLLBACK<br><br>ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table &quot;users&quot; violates foreign key constraint &quot;fk_rails_13700b5326&quot; on table &quot;learners&quot;<br>DETAIL:  Key (id)=(936) is still referenced from table &quot;learners&quot;.</pre><p>Here’s what happens under the hood:</p><ol><li>The user record is deleted.</li><li>The database transaction tries to commit, but it fails due to the foreign key constraint.</li><li>Resonably, the job to delete the associations is not enqueued since the parent record could not be deleted.</li></ol><h3>Error Output</h3><pre>TRANSACTION (0.3ms)  BEGIN<br>Post Load (0.3ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;user_id&quot; = $1  [[&quot;user_id&quot;, 936]]<br>DELETE FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;id&quot; = $1  [[&quot;id&quot;, 936]]<br>ROLLBACK<br><br>ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table &quot;users&quot; violates foreign key constraint &quot;fk_rails_13700b5326&quot; on table &quot;posts&quot;<br>DETAIL:  Key (id)=(936) is still referenced from table &quot;posts&quot;.</pre><h3>Conclusion</h3><p>I’m having a hard time understanding in what cases destroy_async is useful, since the feature doesn&#39;t play well with foreign keys, which I’m not ready to give up that easily.</p><p>If you value data integrity over performance, stick with one of the classic options:</p><ul><li>Using destroy_all to synchronously delete everything, at the peril of blocking the main thread for too long. (Not recommended when the associated count can be indefinitely large).</li><li>Using destroy_allbut trigger the deletion of the record itself from a background job.</li><li>Using delete_all so that deleting the associated rows is done in a single DB query, instead of one per each record. But keep in mind you will be bypassing the associated model callbacks and model validations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81730d95e34d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional Uniqueness Validations in Rails Models: the right way]]></title>
            <link>https://medium.com/@esperonleticia/conditional-uniqueness-validations-in-rails-models-the-right-way-3824fccc2d41?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/3824fccc2d41</guid>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Fri, 24 May 2024 16:45:15 GMT</pubDate>
            <atom:updated>2024-08-02T14:16:44.303Z</atom:updated>
            <content:encoded><![CDATA[<p>I had been writing some conditional uniqueness validations in my Rails models the wrong way for a long time.</p><p>When you’re dealing with partial indexes in PostgreSQL, getting your Rails application validations to be perfectly aligned with the database integrity validations is key to preventing bugs.</p><p><strong>If you’re using conditional uniqueness validations in your DB indexes, it might not be obvious how to properly define the matching Rails model validation.</strong></p><h4>The Scenario</h4><p>Imagine you have a <strong>partial index</strong> to ensure you <strong>can’t have two active discounts with the same code</strong>:</p><pre>index_discount_codes_on_code (code) UNIQUE WHERE (active = true)</pre><p>You would have created such index by writing a migration such as this:</p><pre>class ImproveDiscountCodes &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    add_index :discount_codes, :code, unique: true, where: &quot;active = true&quot;<br>  end<br>end</pre><p>This index means code must be unique, but only among other active discounts. In other words, there can’t be two active discounts with the same code.</p><h4>The Incorrect Approach</h4><p>You might think this validation will do the trick:</p><pre>class DiscountCode &lt; ApplicationRecord<br>  validates :code, uniqueness: true, if: :active<br>end</pre><p>While it seems right, this approach will be more restrictive than your index intends. This is because if: :active skips the validation if active is false, but <strong>it doesn’t limit the scope to only active records</strong> when checking uniqueness. This means you will <strong>never be able to create a discount with a taken code, even if that code is only used by inactive discounts.</strong></p><p>Here’s an example:</p><pre># 1. A discount code is created and at some point marked inactive:<br>DiscountCode.create!(code: &quot;SUMMER&quot;, active: false) <br><br># 2. An active discount code with the same code is then created:<br>DiscountCode.create!(code: &quot;SUMMER&quot;, active: true) # Should be valid</pre><p>This will fail the model validation even though it should be allowed because it’s the only active record with the SUMMER code.</p><h4>The Right Approach</h4><p>To make sure the validation works as expected, you can use theif option to make sure the validation only kicks in when the discount code is active, and set a scope so that the uniqueness has to match both the code as well as the value of active :</p><pre>class DiscountCode &lt; ApplicationRecord<br>  # Instead of: <br>  validates :code, uniqueness: true, if: :active<br><br>  # Do: <br>  validates :code, uniqueness: { scope: :active }, if: :active<br>end</pre><p>Another option which might be clearer is to use the conditions instead of scope:</p><pre>class DiscountCode &lt; ApplicationRecord<br>  validates :code, uniqueness: { <br>    conditions: -&gt; { where(active: true) } <br>  }, if: -&gt; { active }<br>end</pre><p>The conditions option ensures the uniqueness check only looks at active discount codes.</p><h4>Wrapping Up</h4><p>Always make sure your <strong>validations are explicitly defined to match your database constraints</strong>. This will save you from headaches down the road.</p><p>Use ifand either scopeor conditions together in your Rails model validations if you have conditional uniqueness indexes in your database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3824fccc2d41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VSCode shortcut to run or create test file for Rails and Rspec]]></title>
            <link>https://medium.com/@esperonleticia/vscode-shortcut-to-run-or-create-test-file-for-rails-and-rspec-cfcf3a4019da?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfcf3a4019da</guid>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Tue, 14 May 2024 18:36:08 GMT</pubDate>
            <atom:updated>2024-05-17T10:13:02.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><p>Let’s say that you added a new service object inside app/concepts/shop/orders/refunds/initiator.rb . These folders didn’t exist before so you have to manually go replicate the same folder structure inside the spec folder and then create your file manually. Too much work considering you will do this thousands of times.</p><p>This shows a way to configure your VSCode so that when you do Cmd+Shift+T (or whatever keyboard shortcut you want), it executes a custom command. Particularly, it will either run the spec file (if exists), or create the spec file in the right folder path.</p><h3>Assumptions</h3><p>You’re using:</p><ul><li>RSpec</li><li>MacOS</li><li>zsh</li><li>VSCode</li></ul><h3>Step 1: Define the Function in .zshrc</h3><p>First, we’ll create a function in our ~/.zshrc file to handle the logic of checking, creating, and running spec files.</p><ol><li>Open your ~/.zshrc file:</li></ol><pre>code ~/.zshrc</pre><p>2. Define a function called run_or_create_spec that given a ruby class path, it will run or create its corresponding spec file:</p><pre># Function to check or create and run spec file for a Rails app using RSpec,<br># used from VSCode shortcut (configured from Terminal-&gt;Configure Tasks)<br>run_or_create_spec() {<br>  # Get the file path from the argument<br>  original_file_path=&quot;$1&quot;<br><br>  # Construct the spec file path<br>  # Replace &quot;app/&quot; with &quot;spec/&quot;:<br>  modified_file_path=&quot;${original_file_path//app\//spec/}&quot;<br>  # Add &quot;_spec&quot; before the extension:<br>  modified_file_path=&quot;${modified_file_path%.*}_spec.${original_file_path##*.}&quot;<br><br>  # Convert the absolute path to a relative path<br>  relative_modified_file_path=$(echo &quot;$modified_file_path&quot; | sed &quot;s|^$(pwd)/||&quot;)<br><br>  # Check if the spec file exists<br>  if [ -f &quot;$modified_file_path&quot; ]; then<br>    echo &quot;Running spec file: $relative_modified_file_path&quot;<br>    bundle exec rspec &quot;$modified_file_path&quot;<br>  else<br>    echo &quot;Spec file does not exist. Creating: $relative_modified_file_path&quot;<br>    mkdir -p &quot;$(dirname &quot;$modified_file_path&quot;)&quot;<br>    touch &quot;$modified_file_path&quot;<br>    echo &quot;# frozen_string_literal: true&quot; &gt;&gt; &quot;$modified_file_path&quot;<br><br>    # Open the file in Visual Studio Code:<br>    code &quot;$modified_file_path&quot;<br>  fi<br>}</pre><p>3. Save and reload .zshrc:</p><pre>source ~/.zshrc</pre><h3>Step 2: Configure Visual Studio Code Task</h3><p>Next, we’ll set up a Visual Studio Code task that utilizes this function.</p><ol><li>Create or open tasks.json:</li></ol><pre>mkdir -p .vscode; code .vscode/tasks.json</pre><p>(You can also do this from Terminal &gt; Configure Tasks...&gt; Create tasks.json file from template &gt; Others )</p><p>2. Add a new task configuration:</p><pre>{<br>  &quot;version&quot;: &quot;2.0.0&quot;,<br>  &quot;tasks&quot;: [<br>    {<br>      &quot;label&quot;: &quot;Check or Create and Run Spec&quot;,<br>      &quot;type&quot;: &quot;shell&quot;,<br>      &quot;command&quot;: &quot;/bin/zsh&quot;,<br>      &quot;args&quot;: [<br>        &quot;-c&quot;,<br>        &quot;source ~/.zshrc &amp;&amp; run_or_create_spec &#39;${file}&#39;&quot;<br>      ],<br>      &quot;problemMatcher&quot;: [],<br>      &quot;presentation&quot;: {<br>        &quot;echo&quot;: true,<br>        &quot;reveal&quot;: &quot;always&quot;,<br>        &quot;focus&quot;: false,<br>        &quot;panel&quot;: &quot;shared&quot;,<br>        &quot;clear&quot;: true<br>      },<br>      &quot;group&quot;: {<br>        &quot;kind&quot;: &quot;test&quot;,<br>        &quot;isDefault&quot;: true<br>      }<br>    }<br>  ]<br>}</pre><h3>Step 3: Add a Keyboard Shortcut</h3><p>Finally, let’s bind this task to a convenient keyboard shortcut.</p><ol><li>Open your keybindings file:</li></ol><pre>code ~/.config/Code/User/keybindings.json</pre><p>You can also get there with: File &gt; Preferences &gt; Keyboard Shortcuts and clicking the link at the top right Open Keyboard Shortcuts (JSON) )</p><p>2. Add the custom keybinding: (I used Cmd+Shift+T but you can change it)</p><pre>[<br>  {<br>    &quot;key&quot;: &quot;cmd+shift+t&quot;,<br>    &quot;command&quot;: &quot;workbench.action.tasks.runTask&quot;,<br>    &quot;args&quot;: &quot;Check or Create and Run Spec&quot;<br>  }<br>]</pre><p>3. Restart Visual Studio Code or reload the window (Cmd+Shift+P and type Reload Window).</p><h3>Step 3: Test it!</h3><p>Step on a service object and type your new shortcut!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfcf3a4019da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails: Automate anti N+1 tests with a custom RSpec Matcher]]></title>
            <link>https://medium.com/@esperonleticia/rspec-matcher-to-identify-n-1-queries-62986d019a45?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/62986d019a45</guid>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 20:23:39 GMT</pubDate>
            <atom:updated>2024-02-28T16:52:40.764Z</atom:updated>
            <content:encoded><![CDATA[<p>As Rails devs, we are well-versed in crafting unit tests for functional requirements.</p><p>Non-functional requirements, that might revolve around important quality attributes such as performance and scalability, can be as important as functional ones. However, for some reason, we don’t have the habit of automating the tests for these. And we should. It’s not only application error bugs that bring the app down in production and make clients mad, after all.</p><p>I always get a tiny bit mad when I spend hours identifying and fixing N+1s in the codebase to discover months later that a Junior developer accidentally introduced them again. But the blame is only mine. If this is an important aspect, it should be enforced with automated tests.</p><p>In this blog post, I’ll introduce a straightforward script that can enhance your RSpec suite, enabling you to assert the number of database queries performed within a block of code. This can be particularly useful for catching N+1s in request specs or during the creation of GraphQL Loaders, among others.</p><p>While there are many <a href="https://github.com/civiccc/db-query-matchers">gems</a> serving this purpose, which come with a many more of features, we are often doubtful about adding a new dependency. This is especially true if the gem isn’t widely adopted or if its full feature set might not be exploited. Therefore, starting simple with some basic custom code is a good strategy, allowing us to gauge the need for a more robust solution as the codebase evolves.</p><p>So here it is:</p><p><em>(UPDATE: The following works on Rails &lt;7.1. Scroll to the bottom for Rails 7.1+ info.)</em></p><pre># spec/support/custom_matchers/perform_queries_count.rb<br><br><br># Counts the number of SQL performed by a block. Useful for testing N+1s.<br>#<br># Usage:<br># expect { ... }.to perform_queries_count(1)<br><br>RSpec::Matchers.define :perform_queries_count do |expected_count|<br>  supports_block_expectations<br><br>  match do |block|<br>    query_counter = ActiveSupport::Notifications.subscribe(&#39;sql.active_record&#39;) do<br>      @query_count += 1<br>    end<br><br>    @query_count = 0<br>    block.call<br>    ActiveSupport::Notifications.unsubscribe(query_counter)<br><br>    @query_count == expected_count<br>  end<br><br>  failure_message do |_block|<br>    &quot;expected to perform #{expected_count} SQL queries, but did #{@query_count}&quot;<br>  end<br>end</pre><p>This custom RSpec matcher leverages the ActiveSupport::Notifications API to subscribe to SQL ActiveRecord events, effectively counting every query executed within the provided block of code. It starts by setting up a subscription to ‘sql.active_record’ events, incrementing a counter each time one occurs. Then, the block of code we’re testing is executed, and the number of SQL queries it generates is recorded. After the block is run, we unsubscribe from the notifications to avoid memory leaks. Finally, we compare the number of executed queries against our expected count. If they match, the test passes; otherwise, we provide a failure message detailing the discrepancy.</p><p>As mentioned in the comment, you can use it like this:</p><pre>it &#39;only performs one SQL query&#39; do<br>  expect {<br>    get :index, as: :json<br>  }.to perform_queries_count(1)<br>end</pre><p>Or, an example for a more complex test for a graphql batch loader:</p><pre>it &#39;only performs one SQL query&#39; do<br>  expect {<br>    result = GraphQL::Batch.batch do<br>      Loaders::AssociationExists.new(Provider, :programs)<br>                                .load(provider_with_two_programs).then do |result|<br>        expect(result).to be true<br>      end<br><br>      Loaders::AssociationExists.new(Provider, :programs)<br>                                .load(provider_with_no_program).then do |result|<br>        expect(result).to be false<br>      end<br>    end<br>  }.to perform_queries_count(1)<br>end</pre><p>This simple yet effective script offers a stepping stone towards more conscious and performant code. So, go ahead, give it a try!</p><p>UPDATE: <strong>After Rails 7.1 update</strong> more events are going to get sent than the ones you’re probably interested in tracking (changelog (<a href="https://github.com/rails/rails/blob/7-1-stable/activerecord/CHANGELOG.md#rails-710beta1-september-13-2023">https://github.com/rails/rails/blob/7-1-stable/activerecord/CHANGELOG.md#rails-710beta1-september-13-2023</a>).<br>I’m not sure if this is the best solution for this or not, but it’s the only one I found:</p><pre>match do |block|<br>  query_counter = ActiveSupport::Notifications.subscribe(&#39;sql.active_record&#39;) do |event|<br>    @query_count += 1 unless event.payload[:name] == &#39;SCHEMA&#39;<br>  end<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62986d019a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transactional Push: The Sidekiq feature you need to enable right now]]></title>
            <link>https://medium.com/@esperonleticia/transactional-push-the-sidekiq-feature-you-need-to-enable-right-now-d3fc1787f6ce?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3fc1787f6ce</guid>
            <category><![CDATA[database-transaction]]></category>
            <category><![CDATA[background-jobs]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[sidekiq]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 13:56:18 GMT</pubDate>
            <atom:updated>2023-06-13T20:33:51.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6y49RFSj7o3Ag8lnhNAoA.png" /><figcaption>Sidekiq</figcaption></figure><p>Today, I’m thrilled to dive into a game-changing feature that has been introduced in Sidekiq 2022: the <strong>transactional_push!</strong>.</p><p>For those of you relying on background jobs in Ruby, this could be the answer to some long-standing challenges. <strong>With just a single line of code</strong>, you could save yourself from numerous potential headaches, so it’s in your best interest to read through. Let&#39;s unwrap it together.</p><h3>The Problem</h3><p>The issues that transactional_push! addresses arise from <strong>situations where a job is enqueued within a database transaction</strong>.</p><h4>Problem 1: ActiveRecord not found error</h4><p>Consider a scenario where you are creating a new record and enqueuing a job for that record, all within a transaction. Here’s a code snippet illustrating this:</p><pre>ActiveRecord::Base.transaction do<br>  user = User.create!(name: &#39;John Doe&#39;)<br>  Sidekiq::Worker.perform_async(user.id)<br>end</pre><p>In this case, <strong>Sidekiq might pick up the job before the database has committed </strong>the new User record. When the worker tries to find the User with User.find(user_id), an<strong> ActiveRecord error is raised as the User record isn&#39;t in the database yet</strong>.</p><p>This scenario is not the most worrisome, since you likely have a retrials mechanism in place. So, even if the job fails on the first try, it’ll keep retrying and will eventually succeed once the user is saved in the database. You’d likely have received annoying alerts in your error monitoring tool for this error, though.</p><h4>Problem 2: Sidekiq worker not picking up on changes</h4><p>Suppose you have a scenario where a User updates their phone number, and you want to send them an email notification about this update. You might implement this as follows:</p><pre>ActiveRecord::Base.transaction do<br>  user.update!(phone: &#39;1234567890&#39;)<br>  EmailUpdateWorker.perform_async(user.id)<br>end</pre><p>In the EmailUpdateWorker, you retrieve the User and send an email showing the user’s phone number.</p><pre>class EmailUpdateWorker<br>  include Sidekiq::Worker<br>  <br>  def perform(user_id)<br>    user = User.find(user_id)<br>    UserUpdatesMailer.with(to: user.email, new_phone: user.phone).phone_update_email.deliver_now<br>  end<br>end</pre><p>The problem arises when Sidekiq picks up this job before the transaction has committed the updated phone number to the database. As a result, the email sent to the user contains the old phone number instead of the updated one, leaving the customer confused.</p><h4>Problem 3: Job Execution Despite Transaction Rollback</h4><p>Finally, to illustrate the last problem, let’s consider a scenario involving an e-commerce application where a purchase order is submitted. The entire purchase process is wrapped within a transaction, and a job is enqueued to charge the customer via Stripe. The code might look something like this:</p><pre>ActiveRecord::Base.transaction do<br>  purchase_order = PurchaseOrder.create!(customer: customer, product: product)<br>  StripeChargeWorker.perform_async(charge_amount: product.amount)<br>  # more stuff...<br>  raise ActiveRecord::Rollback if some_condition<br>end</pre><p>In this instance, StripeChargeWorker is responsible for initiating the charge to the customer&#39;s credit card.</p><p>The problem arises if, for any reason, the transaction fails and is rolled back after the job has been enqueued. <strong>Despite the transaction rollback, Sidekiq will still execute the job</strong>, and Stripe will charge the customer. 😨 This leads to a scenario where the customer is charged for a purchase order that doesn’t exist in our database, leading to inconsistencies and customer complaints.</p><h3>The Solution: transactional_push!</h3><p>Here comes Sidekiq 2022 with its star feature: transactional_push!.<strong> This feature ensures that Sidekiq jobs are only enqueued after the associated database transaction has been successfully committed.</strong></p><p>To enable it, simply add the following line to your config/initializers/sidekiq.rb:</p><pre>Sidekiq.transactional_push!</pre><p><strong>By using </strong><strong>transactional_push!, Sidekiq now pushes jobs to Redis only after the database transaction is successfully committed. </strong>This approach eliminates the three problems we discussed earlier. The jobs are no longer executed prematurely, and jobs related to rolled-back transactions are never enqueued.</p><p>This feature introduces a dependency on the after_commit_everywhere gem, a clever gem that extends ActiveRecord transactions, enabling them to trigger actions after transactions are committed.</p><h3>Conclusion</h3><p>The transactional_push! feature in Sidekiq 2022 is a game-changer for those of us managing background tasks in our Ruby applications. By ensuring that jobs are only enqueued after database transactions are committed, it allows us to write more robust, error-resistant code. A huge shoutout to the Sidekiq team for this fantastic addition!</p><p>If you haven’t switched it on yet, now’s the time. Go for it!</p><h3>Related links</h3><p><a href="https://github.com/sidekiq/sidekiq/issues/5239">https://github.com/sidekiq/sidekiq/issues/5239</a><br><a href="https://github.com/sidekiq/sidekiq/pull/5291/files">https://github.com/sidekiq/sidekiq/pull/5291/files</a><br><a href="https://www.mikeperham.com/2022/06/17/coming-soon-in-sidekiq-2022-edition/">https://www.mikeperham.com/2022/06/17/coming-soon-in-sidekiq-2022-edition/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3fc1787f6ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Surviving the Email Template Jungle: Essential Housekeeping Tips for Third-Party Services]]></title>
            <link>https://medium.com/@esperonleticia/surviving-the-email-template-jungle-essential-housekeeping-tips-for-third-party-services-2f71960e77ad?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f71960e77ad</guid>
            <category><![CDATA[email-development]]></category>
            <category><![CDATA[sendgrid]]></category>
            <category><![CDATA[sendwithus]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 20:59:38 GMT</pubDate>
            <atom:updated>2023-06-09T21:07:09.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Email communication is the lifeblood of most development teams, with many leveraging third-party services for a streamlined process. Yet, when it comes to storing and managing email templates within these services, teams often find themselves in a chaotic wilderness. The absence of version control, a formal updating process, and the intricacies of complex HTML coding make the experience tough. Toss in the challenge of identifying deprecated components, discerning the contract for dynamic data, and the task seems daunting.</p><p>But fear not! This article offers fundamental tips that every team needs to effectively manage their email templates. This isn’t a full guide, but it provides the very bare essentials to keep you from pulling your hair out as the project and team evolves.</p><h3>Keep the templates categorized and properly named</h3><p>First off, create a clear distinction between the templates for each environment. This will help you avoid accidental modifications to production templates.</p><p>If possible, use separate provider accounts for production and staging. This gives you tighter control over who can access production, minimizing the chance of errors and potential security issues.</p><p>If you can’t use separate accounts, see if the third party allows categorizing templates. That way, you can separate them by environment. If that’s also not an option, like in SendGrid’s case, then it’s critical you adopt a clear naming convention to easily identify which templates are designated for production (such as prefixing them with LIVE.</p><p>Lastly, if multiple teams are sharing the same account, make sure your naming convention includes team or domain identifiers. This simple yet effective approach helps pinpoint template ownership which will become essential.</p><h3>Always keep the staging and production templates in sync</h3><p><strong>Never update the production template without also update staging’s one.</strong></p><p>Ideally, the promotion process would be automated but the reality is that this is often challenging to achieve so most teams update and promote templates manually, sometimes without any type of versioning control.</p><p>If your process to promote templates is not automated, ensure you always start with changing the staging template and then promoting it to production by manually copying its content and test data into the production one. The reason is,<strong> if you make changes to the production one only, we risk overriding those the next time someone starts from the staging one.</strong></p><p>Don’t forget to also sync:</p><ul><li>Subject</li><li>Plain text version</li><li>Content</li><li>Test data</li></ul><h3>Mind the indentation and overall quality</h3><p>The fact that we are not code versioning the templates nor have automated tests, or a formal code review process is not an excuse to go wild west. Whats more, it’s an argument to care for doing things cleanly more than ever.</p><p>Emails are a pain to deal with for any developer because the inline styling and excessive tables makes the HTML very hard to read. So:</p><ul><li>Respect indentation</li><li>Use comments and line breaks to separate logical sections (eg, footer start and end , table for X start and end, etc)</li><li>Don’t save the template with syntax errors. Address any red X that appear in the editor.</li><li>Don’t leave unused sections. If something is deprecated, clean after yourself. The code is hard to maintain as-is.</li></ul><h3>Don’t hardcode environment-specific URLs</h3><p>In the backend, have the classes that serialize the email template data organized. Design them in a way that they all share some generic dynamic data that is usually relevant in all templates, such as the environment’s frontend URL. Use this in the email template instead of hardcoding URLs that would need to change per environment.</p><p>The same applies to any data field that can vary per environment.</p><p>In a similar fashion, if you have some piece that is used in more than a couple templates and you foresee needing to update it at some point, spare yourself the future headache and make it be a dynamic field.</p><h3>Always set complete test data</h3><p>Always set the necessary test data. Try to not add more test data than the template is really using because it makes it harder to see the dynamic data contract that it depends on.</p><h3>Keep business logic out of the template</h3><p>Try to avoid complex if-statements in the template that represent business logic. Make the backend send all the needed information so that the template doesn’t have to make decisions either than omitting components for non-present fields.</p><h3>Try it out on different email clients</h3><p>Try it out in different devices, screen sizes, email clients. If you think building responsive apps is hard, building responsive emails is a pain. Every client interprets things differently.</p><p>Also try how it looks when dark mode is activated.</p><h3>Drop unused templates</h3><p>Don’t leave unused email templates in Sendgrid or whichever provider you’re using.</p><p>Likewise, don’t leave unused or deprecated template ids in the code, ENV VARs, table, or wherever you store them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f71960e77ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the “::” operator in Ruby (Scope Resolution)]]></title>
            <link>https://medium.com/@esperonleticia/understanding-the-operator-in-ruby-scope-resolution-1708ac454532?source=rss-d7d993b6e198------2</link>
            <guid isPermaLink="false">https://medium.com/p/1708ac454532</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Leticia Esperon]]></dc:creator>
            <pubDate>Tue, 30 May 2023 11:24:26 GMT</pubDate>
            <atom:updated>2023-06-09T14:43:21.369Z</atom:updated>
            <content:encoded><![CDATA[<p>(What is :: in Ruby? What does :: mean in Ruby?)</p><p><strong>The scope resolution operator “::” in Ruby is a double colon used for specifying the scope under which a particular constant is defined. </strong>This scope could be a class, a module, or even the main Object class that is the parent of all classes in Ruby.</p><p>In simpler terms, <strong>“::” is a way to look up constants</strong>, where <strong>constants can be either classes or modules</strong>.</p><p>For instance, if you had a class Vehicle and a subclass Car, you could reference the Car class with Vehicle::Car. Here, :: is telling Ruby to find Car within the context or &quot;scope&quot; of Vehicle.</p><pre>module Vehicle<br>  class Car<br>  end<br>end<br><br>my_car = Vehicle::Car.new</pre><p>Now, let’s say you’re already working within the context of the Vehicle module and want to reference the Car module. In this case, you do not need to use the scope resolution operator, as Car is already in your current scope:</p><pre>module Vehicle<br>  class Car<br>  end<br><br>  my_car = Car.new # This works because we&#39;re already inside the Vehicle module<br>end</pre><p>(Note: All this would still apply if Car was a module instead of a class.)</p><p>Finally, let’s look at this:</p><pre>module Vehicle<br>  class Car<br>  end<br><br>  my_car = Car.new <br>end<br><br>module Animal <br>  my_car = Car.new <br>  # This also works, referencing Car class inside Vehicle module. <br>  # Prefer using ::Vehicle::Car over this, though.<br>end</pre><p>In the above example, Car class is still being correctly referenced both within its parent module Vehicle and in an entirely different module, Animal. How is this possible?</p><h4>Constant Lookup Path</h4><p>When Ruby encounters a bare reference to a constant (like Car), it doesn&#39;t just look for the constant in the current scope. Instead, it follows a specific path to find the constant:</p><ol><li>It first looks in the current scope’s nested constants.</li><li>If it doesn’t find it, it moves to the outer scope and repeats the process.</li><li>It continues to move outward until it reaches the top level (the global scope).</li></ol><p>In the above example, when Ruby encounters Car.new inside the Animal module, it doesn&#39;t find a constant Car defined within Animal. So, it moves to the outer scope, which is the top-level (global) scope in this case. Here, it finds the Vehicle::Car constant, which is available because Vehicle is a top-level module and Vehicle::Car is its nested constant. So, it uses Vehicle::Car to instantiate a new Car object.</p><p>Here’s a visual representation of the process:</p><pre>module Vehicle   # &lt;---- Ruby looks here last<br>  class Car      # &lt;---- Ruby finds `Car` here<br>  end<br><br>  my_car = Car.new <br>end<br><br>module Animal    # &lt;---- Ruby looks here first<br>  my_car = Car.new <br>end</pre><h4>A Word of Caution</h4><p>This example demonstrates a key aspect of Ruby’s scope resolution and constant lookup. However, it’s generally considered good practice to avoid relying on this behavior, as it can lead to confusing and error-prone code.</p><p>If you reference a constant like Car that isn&#39;t clearly defined in your current scope, it might not be immediately clear where Car is coming from, especially in a larger codebase. This can make debugging more difficult and can also lead to unexpected results if a constant with the same name is defined in your current scope.</p><p>So, how do we correctly reference a constant that it’s outside of our current module?</p><h4>The Global Scope and “::”</h4><p>Where “::” really comes into play is when dealing with global and local scopes, especially when modules share the same name. By prefixing a constant with “::”, you tell Ruby to look for the constant in the global scope, instead of the current scope.</p><p>Imagine you have a class named Car in the global scope, and another named also named Car nested inside the Vehicle module.</p><pre>class Car<br>end<br><br>module Vehicle<br>  class Car<br>  end<br>end</pre><p>If you’re inside the Vehicle module and you refer to Car, Ruby will assume you&#39;re referring to Vehicle::Car. But what if you want to refer to the Car in the global scope? That&#39;s where &quot;::&quot; comes in. By prefixing Car with &quot;::&quot;, like this: ::Car, you&#39;re telling Ruby to ignore the current scope (in this case, Vehicle) and look in the global scope instead.</p><pre>module Vehicle<br>  module Car<br>  end<br><br>  my_global_car = ::Car.new # This refers to the Car in the global scope, not Vehicle::Car<br>end</pre><h3>Conclusion</h3><p>The “::” operator in Ruby is necessary to properly reference other classes or modules.</p><ul><li>You do not need to use “::” to reference other constants within the same module.</li><li>If you need to reference a constant outside of your current scope, use the global scope “::” to explicitly reference the scope where the constant is defined, even if Ruby constant lookup will end up finding it outside of the current module. This will make your code more readable, predictable and will help you avoid future bugs if you ever end up defining a different constant with same name in your current module.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1708ac454532" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>