<?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 Nicholus Muwonge on Medium]]></title>
        <description><![CDATA[Stories by Nicholus Muwonge on Medium]]></description>
        <link>https://medium.com/@nicholusmuwonge?source=rss-44e0e2467519------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qBmVn5J8ALWLfpLAFrQT7Q.jpeg</url>
            <title>Stories by Nicholus Muwonge on Medium</title>
            <link>https://medium.com/@nicholusmuwonge?source=rss-44e0e2467519------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:48:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicholusmuwonge/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[Database Pessimistic Locking: Underused, Misunderstood, and Critical.]]></title>
            <link>https://nicholusmuwonge.medium.com/database-pessimistic-locking-underused-misunderstood-and-critical-c9b241572d7e?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b241572d7e</guid>
            <category><![CDATA[table-lock]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[deadlock-prevention]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 12:01:17 GMT</pubDate>
            <atom:updated>2025-04-18T14:02:12.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hN4gHYSNB2WGoY-a" /><figcaption>Photo by <a href="https://unsplash.com/@tomthompsonphotography?utm_source=medium&amp;utm_medium=referral">Thomas Thompson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Concurrency</strong> is a typical modern programming concept that means multiple computations/operations happening simultaneously.</p><p>This concept is one of the key characteristics of database systems. It allows more than one transaction to run simultaneously, which reduces latency since operations are not sequential.</p><p>Well, it does come with a couple of challenges, such as deadlocks, race conditions, risks of data inaccuracy, and inconsistencies. This post will focus on how to mitigate these challenges by employing <strong>pessimistic</strong> <strong>locks</strong>.</p><p>It will cover what pessimistic locks are, when to use them, and any gotchas that come with them. This will also have Ruby(Rails with Active Record ORM) and SQL-specific examples.</p><h3>What is Pessimistic Locking and Why it Matters</h3><p>Locking is a mechanism that restricts access to tables, objects, and rows to only one transaction for a given time and releases the restriction once the operation is done. The only exception is shared locks, which allow multiple reads at the same time.</p><p>Locking mitigates the challenges that come with concurrency while also maintaining data integrity.</p><h4>Picture this:</h4><p>Apex Inc. account has €50 with no overdraft services. Niel heads out to buy office supplies for €40, and at the same time, Nick grabs coffee for the boardroom that’s €30.</p><p>Both transactions check the balance, see €50, and go for it. Without any locking in place, both go through, and then you end up with -<strong>€20 </strong>if no DB constraints are in place to prevent it. Not a very ideal balance.</p><p>But with locking? Niel’s transaction grabs the balance first, locks it, and when Nick’s transaction comes in, it finds the account record locked. His transaction will not proceed till Niel’s is done, and thereafter Nick will see that there’s not enough left. No more negative balances. A lock saves the day.</p><h3>Types of Locking</h3><h4>Row Locking</h4><p>There are different modes involved in locking a row in a table, each with its own use case. Following the example above;</p><p><strong>Update No Wait:</strong></p><p>Like in the scenario above, when two users are at a Point Of Sale trying to make a purchase, there’s no room for the other to hold the line while waiting for the lock to be released by the other user so it can get to its turn.</p><p>In this case, it’s better to give the user quick feedback so that they can reswipe the card if need be, rather than just wait for a while to grab the lock. Which is where this mode excels.</p><p>“No Wait” Means that if a row has a lock on it, any other transaction will not wait for the lock but exit with an error message, alerting the user that the lock isn’t available. This also means no updates or delete operations can be performed on the record.</p><p>Raw SQL Version</p><pre>BEGIN;<br><br>SELECT * FROM accounts <br>WHERE id = $1<br>FOR UPDATE NOWAIT;<br><br>UPDATE accounts<br>SET balance = balance - 20<br>WHERE id = $1;<br><br>COMMIT;</pre><p>In Active Record, this could be translated to</p><pre>begin<br>  account = Account.lock(&#39;FOR UPDATE NOWAIT&#39;).find(account_id)<br>  account.update!(balance: account.balance - 20)<br>rescue ActiveRecord::LockNotAvailable =&gt; e<br>  # Do something or retry<br>  Logger.info(e)<br>  retries += 1 # you could decide to do this<br>  # you could retry if logic allows it<br>end</pre><p><strong>Update Mode:</strong></p><p>When Niel needs to make an online purchase, an update lock will be obtained, and the expectation is that by the time the lock is released, there will have been a modification on the row. In this case, the balance will be reduced.</p><p>With this lock, no other transaction can update or delete this record until there’s a commit or a rollback. Then, the row will become updatable again.</p><p>This mode is suitable in scenarios where it doesn&#39;t hurt UX for the other user(Nick) to wait while Niel finalizes his transaction, such as purchasing stuff off of Amazon simultaneously.</p><p>The Raw SQL Version</p><pre>BEGIN;<br><br>SELECT * FROM accounts <br>WHERE id = $1<br>FOR UPDATE;<br><br>UPDATE accounts<br>SET balance = balance - 20<br>WHERE id = $1;<br><br>COMMIT;</pre><p>In Active Record, this could be translated to</p><pre>account = Account.lock(&#39;FOR UPDATE&#39;).find(account_id)<br>account.update!(balance: account.balance - amount)</pre><p><strong>Share Mode:</strong></p><p>Just like the first two modes, this mode prevents updates and deletes on a locked row. It also prevents exclusive reads from other transactions in case the lock has already been obtained by another transaction.</p><p>This mode ensures more than one transaction can hold the lock for read-only purposes, and none of them can modify the record, and it ensures they read the latest version of the row. The lock is released after the acquiring transaction is done.</p><p>This mode could be useful when checking if Nick’s purchase is within his spending limits, and the lock ensures that no updates occur to the limit during this check.</p><p>The Raw SQL Version</p><pre>BEGIN;<br><br>SELECT * FROM accounts<br>WHERE id = $1<br>FOR SHARE<br><br>-- Do the checks of the limit and create<br>COMMIT;</pre><p>In Active Record, this could be translated to</p><pre>Account.transaction do<br>  account = Account.lock(&#39;FOR SHARE&#39;).find(account_id)<br><br>  raise &quot;Limit Exceeded&quot; if account.limit =&lt; amount<br>  Transaction.create!(account_id: account.id, amount:)<br>end</pre><h4>Table Locking</h4><p>Unlike row locking, this type of locking affects the entire table, and some of these locks are obtained automatically by a DB server when;</p><ul><li>Renaming column, table.</li><li>Indexing a table, dropping an index, and altering an index.</li><li>altering fragments, table.</li></ul><p>Moving on to ones that are voluntarily acquired, we have two modes,</p><p><strong>For Share:</strong></p><p>This ensures that no writes or deletions can happen when this lock is obtained, but rather a shared read lock that supports reads from different transactions.</p><p>This would be a very applicable scenario where we want to ensure data consistency, like daily reconciliations. Having other transactions adjust the table during a reconciliation will produce inaccurate results, hence the shared lock. Other scenarios could be audits for duplicate transactions or abnormalities in a table.</p><pre>BEGIN;<br><br>LOCK TABLE transactions IN SHARE MODE;<br>LOCK TABLE bank_transactions IN SHARE MODE;<br><br>SELECT <br>  t.transaction_id,<br>  t.amount AS system_amount,<br>  b.amount AS bank_amount<br>FROM transactions t<br>JOIN bank_transactions b<br>  ON t.transaction_id = b.transaction_id<br>WHERE t.amount &lt;&gt; b.amount;<br><br>COMMIT;</pre><p>In Active Record, this could be translated to</p><pre>def find_amount_mismatches<br>  ActiveRecord::Base.transaction do<br>    # Lock both tables in SHARE MODE for consistency during reconciliation<br>    ActiveRecord::Base.connection.execute(&quot;LOCK TABLE transactions IN SHARE MODE&quot;)<br>    ActiveRecord::Base.connection.execute(&quot;LOCK TABLE bank_transactions IN SHARE MODE&quot;)<br><br>    # Fetch mismatched transaction IDs<br>    mismatches = Transaction<br>      .joins(&quot;INNER JOIN bank_transactions ON transactions.transaction_id = bank_transactions.transaction_id&quot;)<br>      .where.not(&quot;transactions.amount = bank_transactions.amount&quot;)<br>      .select(&quot;transactions.transaction_id, transactions.amount AS system_amount, bank_transactions.amount AS bank_amount&quot;)<br><br>    mismatches.each do |m|<br>      puts &quot;Mismatch found for transaction ID #{m.transaction_id}: System = #{m.system_amount}, Bank = #{m.bank_amount}&quot;<br>      # write to CSV<br>    end<br><br>    mismatches<br>  end<br>end<br><br>find_amount_mismatches()</pre><p>This way, no updates can be made to the transactions during the reconciliation.</p><p><strong>Exclusive Mode:</strong></p><p>This mode locks the table so that no writes or reads can occur before a commit or a rollback. This mode would be the best option when there’s a batch update to most of the rows in the table. To avoid inconsistencies, it makes sense not to allow reads or writes during the execution.</p><p>An example would be realising that there was a recent update in the business logic that led to the miscalculation of Value Added Tax. This could have affected all transactions to date, and a script needs to be run to update all transaction amounts to reflect the right VAT amounts; otherwise, customers will get the wrong information on their invoices.</p><p>Raw SQL Version;</p><pre>BEGIN;<br><br>-- Block all reads and writes on the transactions table<br>LOCK TABLE transactions IN EXCLUSIVE MODE;<br><br>-- Recalculate VAT for all transactions (assuming 20% VAT on amount)<br>UPDATE transactions<br>SET vat_amount = amount * 0.2;<br><br>COMMIT;</pre><p>In Active Record, it would look like this;</p><pre>def recalculate_all_vat!<br>  ActiveRecord::Base.transaction do<br>    # Prevent any reads or writes to ensure consistency during VAT fix<br>    ActiveRecord::Base.connection.execute(&quot;LOCK TABLE transactions IN EXCLUSIVE MODE&quot;)<br><br>    # Recalculate VAT for all existing transactions (assume 20%)<br>    Transaction.find_each do |tx|<br>      tx.update!(vat_amount: tx.amount * 0.2)<br>    end<br>  end<br>end<br><br>recalculate_all_vat!()</pre><p>Of course, it would help to run it in a rake task and off the main thread during peak hours, but it would allow for a smooth update rather than inconsistencies from transactions reading and writing to it as the script runs, hence the exclusive lock.</p><h3>Challenges that Come With Pessimistic Locks, aka Gotchas</h3><p><strong>Deadlocks</strong>. This can happen in cases where two transactions hold locks that the other needs to finish execution. The DB server will have to choose one to kill off one of them, which may result in data loss or hard-to-debug issues.</p><p>To resolve this, it&#39;s best to;</p><ul><li>Keep the transactions slim to handle a certain task instead of many unrelated DB tasks</li><li>Only run DB-related tasks in the transactions.</li><li>Handling deadlock exceptions. Since it&#39;s a possibility, always try and handle exceptions around deadlocks, ie <strong>ActiveRecord::DeadLocked</strong>(Rails) and if you’re using PostgreSQL, catch the exception <strong>PG::TRDeadlockDetected</strong> . This way, you can run any retry logic you may have.</li></ul><p><strong>Contention on busy rows</strong>. When one row keeps on being locked by many transactions, it keeps the other transactions waiting in line, which ends up killing the user experience.</p><p>To resolve this, it&#39;s best to;</p><ul><li>Use shared locks to allow multiple transactions to read and finish.</li><li>Opt for <a href="https://www.ibm.com/docs/en/db2/12.1.0?topic=overview-optimistic-locking">optimistic lock</a>s instead.</li></ul><p>Table locks, especially the exclusive mode, halt activity for the time the lock is acquired, and this may result in application-level failures. So any operations that require an exclusive lock would best be executed in low app usage hours, ie, Midnight or whatever makes sense for the business.</p><p>To debug lock-related issues in Postgres, try using the pgrowlocks extension.</p><p>I hope this was informative. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b241572d7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Care About Ruby Method Lookup Chain?]]></title>
            <link>https://nicholusmuwonge.medium.com/should-you-care-about-ruby-method-lookup-chain-d24ca41ed662?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24ca41ed662</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 18:23:01 GMT</pubDate>
            <atom:updated>2025-03-13T18:25:11.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lj4hqkokFXQEbtM1" /><figcaption>Photo by <a href="https://unsplash.com/@mostafa_meraji?utm_source=medium&amp;utm_medium=referral">mostafa meraji</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ruby is an object-oriented language that relies on classes, modules, and mixins to structure and reuse logic. In production applications, especially in Ruby on Rails, <a href="https://ruby-doc.com/docs/ProgrammingRuby/html/tut_modules.html"><strong>mixins</strong></a> are commonly used to share functionality across different classes and objects. However, method resolution in Ruby follows a specific <strong>lookup chain</strong>, which determines which method is called when multiple definitions exist across a class hierarchy or included modules. Misunderstanding this lookup order can lead to <strong>unexpected behavior, hard-to-debug issues, and even business-critical bugs</strong>, such as incorrect calculations or overridden ActiveRecord methods. Knowing how Ruby resolves methods can help you <strong>avoid conflicts, debug faster, and write more maintainable code</strong>.</p><p>With that brief background, this blog will provide;</p><ul><li>An insight into the level of hierarchy Ruby takes when executing methods with the same name in associated objects.</li><li>How this may affect you in your day-to-day work.</li><li>A surface understanding of keywords include, prepend and extend.</li></ul><h3><strong>Method Overriding</strong></h3><h4>Include</h4><p>Let’s look at an example where we have a payment module with different discount rates being included in classes that also implement their discount rate.</p><pre>module ExtraDiscountable<br>  def discount(amount)<br>    # some discount logic<br>    p &quot;Module based discount&quot;<br>    amount * 0.1<br>  end<br>end<br><br>module HolidayDiscountable<br>  def discount(amount)<br>    # some discount logic<br>    p &quot;Holiday Module based discount&quot;<br>    amount * 0.01<br>  end<br>end<br><br>class Payment<br>  def discount(amount)<br>    p &quot;base class discount&quot;<br>    0.3 * amount<br>  end<br>end<br><br>class PosPayment &lt; Payment<br>include ExtraDiscountable<br>end<br><br>payment = PosPayment.new<br>p payment.discount(100)<br>p PosPayment.ancestors, payment.method(:discount).source_location</pre><p>The output for this would be</p><pre>&quot;Module based discount&quot;<br>10.0<br>[PosPayment, ExtraDiscountable, Payment, Object, Kernel, BasicObject]<br>[&quot;lib/main.rb&quot;, 67]</pre><p>This means the ExtraDiscountable module’s discount method ran, and it is well laid out in the ancestors array, showing the order in which Ruby scans for the right method to call. In this case, it starts from PosPayment and finds no implementation of the discountmethod, moves up to ExtraDiscountable which happens to have the method defined there. Now, why is that so when the parent class Payment has a discount method, too?</p><p>The answer lies in the fact that in the PosPaymentclass, the include method is loaded after the Payment class method in the order of hierarchy, and if we added a new module below that; For instance HolidayDiscountableit would take precedence over the ExtraDiscountable module because it will be loaded later.</p><pre>payment.method(:discount).source_location</pre><p>at the end of the file should also assist in debugging by pinpointing where the invoked method is located.</p><h4>Prepend</h4><p>The order is always the current object is scanned first unless prepend is used instead of include . To better demonstrate this, I will modify the code above to show you the ancestors&#39; order changes with prepend coming before the base object.</p><pre>module ExtraDiscountable<br>  def discount(amount)<br>    # some discount logic<br>    p &quot;Module based discount&quot;<br>    amount * 0.1<br>  end<br>end<br><br>module HolidayDiscountable<br>  def discount(amount)<br>    # some discount logic<br>    p &quot;Holiday Module based discount&quot;<br>    amount * 0.01<br>  end<br>end<br><br>class Payment<br>  def discount(amount)<br>    p &quot;base class discount&quot;<br>    0.3 * amount<br>  end<br>end<br><br>class PosPayment &lt; Payment<br>  prepend ExtraDiscountable<br><br>  def discount<br>    p &quot;pos class discount&quot;<br>      0.4 * amount<br>  end<br>end<br><br>payment = PosPayment.new<br>p payment.discount(100)<br>p PosPayment.ancestors</pre><p>Had I stuck with include, this would have resulted in PosPayment#discount taking precedence because it would be the first one in the ancestors array. But with the introduction of prepend , that means the ExtraDiscountable would now come before PosPayment , its discount method will be run returning;</p><pre>&quot;Module based discount&quot;<br>10.0<br>[ExtraDiscountable, PosPayment, Payment, Object, Kernel, BasicObject]</pre><h4>Extend</h4><p>There’s another method called extend which is a singleton_method that is applied only on a specific instance of the class and will not exist for the other instances.</p><p>This method will always take precedence in the ancestors tree as it is scanned first.</p><pre>module ExtraDiscountable<br>  def discount(amount)<br>    # some discount logic<br>    p &quot;Module based discount&quot;<br>    amount * 0.1<br>  end<br>end<br><br>module HolidayDiscountable<br>  def discount(amount)<br>    # some discount logic<br>    p &quot;Holiday Module based discount&quot;<br>    amount * 0.01<br>  end<br>end<br><br>class Payment<br>  def discount(amount)<br>    p &quot;base class discount&quot;<br>    0.3 * amount<br>  end<br>end<br><br>class PosPayment &lt; Payment<br>  include ExtraDiscountable<br>end<br><br>payment = PosPayment.new<br>payment.extend(HolidayDiscountable)<br><br>payment1 = PosPayment.new<br>p payment.discount(100)<br>p payment.singleton_class.ancestors<br>p payment1.singleton_class.ancestors<br>p PosPayment.ancestors</pre><p>The output</p><pre>&quot;Holiday Module based discount&quot;<br>1.0<br>[#&lt;Class:#&lt;PosPayment:0x00007ff6851331d8&gt;&gt;, HolidayDiscountable, PosPayment, ExtraDiscountable, Payment, Object, Kernel, BasicObject]<br>[#&lt;Class:#&lt;PosPayment:0x00007ff685132df0&gt;&gt;, PosPayment, ExtraDiscountable, Payment, Object, Kernel, BasicObject]<br>[PosPayment, ExtraDiscountable, Payment, Object, Kernel, BasicObject]</pre><p>The results demonstrate this well, regardless of how I load the mixin in PosPayment the HolidayDiscountable module will always be scanned first.</p><h3>Applicability</h3><p>In general practice, it could be that you need to include a mixin’s functionality into a class, but you find the module defines methods that clash with the class methods. This can be hard to debug and could lead to major business losses; for instance, if the wrong discounts were applied, the business could be selling at a loss for a while before this is discovered.</p><h3><strong>Conclusion</strong></h3><p>These methods come in handy when working on a production app with lots of <a href="https://api.rubyonrails.org/classes/ActiveSupport/Concern.html"><strong>Concerns</strong></a> and class based <a href="https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/inheritance.html"><strong>inheritence</strong></a>. I have encountered some issues before by including <strong>mixins</strong> that implemented methods with the same name as some of my local class methods. In case there’s no other way around it, knowing the method lookup chain speeds up debugging.</p><p>As this blog focuses on a narrower scope, you may also want to read more about;</p><ul><li><a href="https://ruby-doc.org/stdlib-2.5.1/libdoc/singleton/rdoc/Singleton.html">singleton_classes</a> and methods</li><li><a href="https://apidock.com/ruby/BasicObject/method_missing">method_missing</a> as they’re closely related to this topic.</li></ul><p>So do you think you need to understand the lookup chain after reading through this blogpost? Let me know in the comments. Till then, cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24ca41ed662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating PDF Reports within Rails using Prawn PDF and Prawn Table Gems.]]></title>
            <link>https://nicholusmuwonge.medium.com/generating-pdf-reports-within-rails-using-prawn-pdf-and-prawn-table-gem-c5fea5b73e7f?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5fea5b73e7f</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[prawn-table]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[prawn-pdf]]></category>
            <category><![CDATA[rails-pdf]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 15:21:32 GMT</pubDate>
            <atom:updated>2023-09-14T18:49:13.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6FIyUR1JWp1xdhh" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I’m working on different projects, I often have to create PDFs for important documents like transaction summaries and invoices. But don’t worry, it’s not as complicated as it sounds! In this blog post, I’ll show you a simple way to make PDFs. If you’re looking for PDF gems for Ruby, just search for “PDF” on RubyGems.org or LibHunt and you’ll find plenty of options.</p><p>Let&#39;s dive right in then. We will start by creating an empty new project</p><pre>rails new prawn_pdf</pre><p>After the project files have been generated, we will need to add the gems required to the Gemfile and run bundle install .</p><pre>gem &quot;prawn&quot;, &quot;~&gt; 2.4&quot; # for generating pdfs<br>gem &quot;prawn-table&quot;, &quot;~&gt; 0.2.2&quot; # for adding tables to prawn pdfs, - <br># because most reports have tables in them.<br>gem &quot;prawn-icon&quot;, &quot;~&gt; 3.1&quot; # You may need this if you want to use icons at all<br>gem &quot;letter_opener&quot;, group: :development # add this under the development section.</pre><p>You can find the links to the Gem GitHub pages at the end of this blog. Prawn Gem has a PDF doc and does Prawn Table Gem.</p><p>There are multiple ways to approach building a PDF, but I usually approach it like I am designing an email. I use tables a lot to align stuff really well across the page.</p><p>For this blog post, I found this random PDF online, and I will try to redesign it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f0Pp88cddaH7eH0d.png" /><figcaption>Report We’re trying to generate</figcaption></figure><p>Since I will be using the PDF throughout my entire Rails application, I will place it in a service. Let’s create one under `<strong>app/services/pdf_generator_service.rb</strong>`</p><h4>The Initialization:</h4><p>In this section, I set up everything that would need to be used throughout the pdf sections like the: fonts , page orientation and other components</p><pre>class PdfGeneratorService<br>  MONTSERRAT_FONT_PATH = &#39;app/assets/stylesheets/Montserrat-Medium.ttf&#39;<br>  MONTSERRAT_BOLD_FONT_PATH = &#39;app/assets/stylesheets/Montserrat-Black.ttf&#39;<br>  LOGO_IMG_PATH = &#39;app/assets/images/logo.png&#39;<br>  def initialize<br>    @pdf = Prawn::Document.new<br>    @document_width = @pdf.bounds.width # width fo the document<br>    @pdf.font_families.update(<br>      &#39;montserrat&#39; =&gt; {<br>        normal: MONTSERRAT_FONT_PATH, # Path to the normal (regular) font style<br>        bold: MONTSERRAT_BOLD_FONT_PATH # Path to the bold font style (if applicable)<br>      }<br>    )<br>  end<br>end</pre><p>In this case, I wanted to use a custom font called montserrat for which I downloaded .ttf a file from Google Fonts to use in this pdf. Prawn supports custom fonts as well.</p><h4>The Header Section:</h4><pre>class PdfGeneratorService<br>  ...<br>  def header<br>    status_results = [%w[15 3 5 4 3], %w[TESTS FAILED PASSED BLOCKED UNKNOWN]]<br>    text_colors = { 1 =&gt; &#39;C8102F&#39;, 2 =&gt; &#39;83BC41&#39;, 3 =&gt; &#39;FDB357&#39;, 4 =&gt; &#39;BBBBBB&#39; }<br><br>    header_table = @pdf.make_table(status_results) do |table|<br>      table.row(0).font_style = :bold<br>      table.row(0).font = &#39;montserrat&#39;<br><br>      header_status_rows = [0, 1]<br>      header_status_rows.each do |row_index|<br>        text_colors.each do |column_index, color|<br>          table.row(row_index).column(column_index).style(text_color: color)<br>        end<br>      end<br><br>      table.row(0..1).border_width = 0<br>      table.row(0..1).column(0).border_width = 1<br>      table.row(0..1).column(0).border_color = &#39;c0c5ce&#39;<br>      table.row(0..1).column(0).borders = [:right]<br>      table.row(0).size = 17<br>      table.row(1).size = 11<br>    end<br><br>    header_column_widths = [@document_width * 2 / 3, @document_width * 1 / 3]<br>    header_title_data = [[&#39;Execution Summary&#39;]]<br>    header_title_options = {<br>      column_widths: [@document_width],<br>      row_colors: [&#39;EDEFF5&#39;],<br>      cell_style: {<br>        border_width: 0,<br>        padding: [15, 12, 1, 20],<br>        size: 20,<br>        font: &#39;montserrat&#39;,<br>        font_style: :normal<br>      }<br>    }<br><br>    header_logo_data = [[header_table, { image: LOGO_IMG_PATH, position: :center, scale: 0.5, colspan: 6 }]]<br>    header_logo_options = {<br>      column_widths: header_column_widths,<br>      row_colors: [&#39;EDEFF5&#39;],<br>      cell_style: {<br>        border_width: 2,<br>        padding: [15, 15],<br>        borders: [:bottom],<br>        border_color: &#39;c9ced5&#39;<br>      }<br>    }<br><br>    @pdf.table(header_title_data, header_title_options)<br>    @pdf.table(header_logo_data, header_logo_options)<br>  end<br>  ...<br>end</pre><p>So this gives us this and I know it is not the exact replica but due to limited time, this is how close I got;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wUyHuOHzlsD9_KJ2ZrQLA.png" /><figcaption>The Header Section</figcaption></figure><p>Key takeaways;</p><ul><li>Prawn allows tables can be nested into other tables</li></ul><h4>The Middle Section:</h4><pre>class PdfGeneratorService<br>  ...<br>  def mid_section<br>    mid_section_data = [[&#39;General&#39;, &#39;&#39;, &#39;&#39;], [&#39;Start time:&#39;, &#39;Duration:&#39;, &#39;Executed by:&#39;],<br>              [&quot;Apr 7, 2020 \n 10:33:57&quot;, &#39;15m 9s&#39;, &#39;z-automation-sayvr@perfectmobile.com&#39;]]<br>   <br>    mid_section_options = {<br>     width: @document_width,<br>     row_colors: [&#39;ffffff&#39;],<br>     cell_style: {<br>      border_width: 0,<br>      borders: [:bottom],<br>      border_color: &#39;c9ced5&#39;,<br>      padding: [10, 15]<br>     }<br>    }<br>   <br>    @pdf.table(mid_section_data, mid_section_options) do |table|<br>     table.row(0).border_width = 0.5<br>     table.row(1).text_color = &#39;888892&#39;<br>     table.row(0).padding = [10, 15]<br>     table.row(2).size = 11<br>    end<br>   end<br>  ...<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuQx9tedtEyWOpiSuM8VGQ.png" /><figcaption>This is what we would achieve with the code above.</figcaption></figure><h4>The Results Section:</h4><pre>class PdfGeneratorService<br>  ...<br>  def result_section<br>    report_data = [[&#39;Report&#39;, &#39;&#39;, &#39;View detailed list in new Reporting&#39;],<br>           [&#39;Name&#39;, &#39;Platform&#39;, &#39;Status&#39;],<br>           [&#39;gehpbatosid4pp_oak6f&#39;, &quot;Apple Chibn \n f7euq&quot;, &#39;BLOCKED&#39;],<br>           [&#39;gehpbatosid4pp_oak6f&#39;, &quot;Apple Chibn \n f7euq&quot;, &#39;PASSED&#39;]]<br>   <br>    report_data_options = {<br>     width: @document_width,<br>     row_colors: [&#39;ffffff&#39;],<br>     cell_style: {<br>      border_width: 1,<br>      borders: [:bottom],<br>      border_color: &#39;c9ced5&#39;<br>     }<br>    }<br>   <br>    @pdf.table(report_data, report_data_options) do |table|<br>     test_status = table.rows(1..-1).column(-1)<br>     <br>     test_status.filter do |cell|<br>      case cell.content<br>      when &#39;BLOCKED&#39;<br>       cell.text_color = &#39;FDB357&#39;<br>      when &#39;PASSED&#39;<br>       cell.text_color = &#39;83BC41&#39;<br>       # add more cases<br>      end<br>     end<br>   <br>     table.row(0..1).border_width = 0.5<br>     table.row(0).column(2).text_color = &#39;2787c4&#39;<br>     table.row(0).column(2).size = 11<br>     table.row(1).background_color = &#39;EDEFF5&#39;<br>     table.row(1..-1).column(1..2).align = :center<br>     table.row(1).text_color = &#39;465579&#39;<br>     table.row(1).size = 10<br>     table.row(1..-1).padding = [10, 15]<br>     table.row(0).padding = [7, 15]<br>    end<br>   end<br>   ...<br>end</pre><p>We achieve this part with the code above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCRNWxwwVBFOwAYc0LwE6Q.png" /><figcaption>The bottom section</figcaption></figure><p>And finally combining all the sections in the PDF.</p><pre>class PdfGeneratorService<br>  ...<br>  def generate_pdf<br>    header<br>    mid_section<br>    lower_section<br>    @pdf.render<br>  end<br>  ...<br>end</pre><p>The overall service.</p><pre># frozen_string_literal: true<br><br>class PdfGeneratorService<br>  MONTSERRAT_FONT_PATH = &#39;app/assets/stylesheets/Montserrat-Medium.ttf&#39;<br> MONTSERRAT_BOLD_FONT_PATH = &#39;app/assets/stylesheets/Montserrat-Black.ttf&#39;<br>  LOGO_IMG_PATH = &#39;app/assets/images/logo.png&#39;<br>  def initialize<br>    @pdf = Prawn::Document.new<br>    @document_width = @pdf.bounds.width<br>    @pdf.font_families.update(<br>      &#39;montserrat&#39; =&gt; {<br>        normal: MONTSERRAT_FONT_PATH, # Path to the normal (regular) font style<br>        bold: MONTSERRAT_BOLD_FONT_PATH # Path to the bold font style (if applicable)<br>      }<br>    )<br>  end<br><br>  def header<br>    status_results = [%w[15 3 5 4 3], %w[TESTS FAILED PASSED BLOCKED UNKNOWN]]<br>    text_colors = { 1 =&gt; &#39;C8102F&#39;, 2 =&gt; &#39;83BC41&#39;, 3 =&gt; &#39;FDB357&#39;, 4 =&gt; &#39;BBBBBB&#39; }<br><br>    header_table = @pdf.make_table(status_results) do |table|<br>      table.row(0).font_style = :bold<br>      table.row(0).font = &#39;montserrat&#39;<br><br>      header_status_rows = [0, 1]<br>      header_status_rows.each do |row_index|<br>        text_colors.each do |column_index, color|<br>          table.row(row_index).column(column_index).style(text_color: color)<br>        end<br>      end<br><br>      table.row(0..1).border_width = 0<br>      table.row(0..1).column(0).border_width = 1<br>      table.row(0..1).column(0).border_color = &#39;c0c5ce&#39;<br>      table.row(0..1).column(0).borders = [:right]<br>      table.row(0).size = 17<br>      table.row(1).size = 11<br>    end<br><br>    header_column_widths = [@document_width * 2 / 3, @document_width * 1 / 3]<br>    header_title_data = [[&#39;Execution Summary&#39;]]<br>    header_title_options = {<br>      column_widths: [@document_width],<br>      row_colors: [&#39;EDEFF5&#39;],<br>      cell_style: {<br>        border_width: 0,<br>        padding: [15, 12, 1, 20],<br>        size: 20,<br>        font: &#39;montserrat&#39;,<br>        font_style: :normal<br>      }<br>    }<br><br>    header_logo_data = [[header_table, { image: LOGO_IMG_PATH, position: :center, scale: 0.5, colspan: 6 }]]<br>    header_logo_options = {<br>      column_widths: header_column_widths,<br>      row_colors: [&#39;EDEFF5&#39;],<br>      cell_style: {<br>        border_width: 2,<br>        padding: [15, 15],<br>        borders: [:bottom],<br>        border_color: &#39;c9ced5&#39;<br>      }<br>    }<br><br>    @pdf.table(header_title_data, header_title_options)<br>    @pdf.table(header_logo_data, header_logo_options)<br>  end<br><br> def mid_section<br>  mid_section_data = [[&#39;General&#39;, &#39;&#39;, &#39;&#39;], [&#39;Start time:&#39;, &#39;Duration:&#39;, &#39;Executed by:&#39;],<br>            [&quot;Apr 7, 2020 \n 10:33:57&quot;, &#39;15m 9s&#39;, &#39;z-automation-sayvr@perfectmobile.com&#39;]]<br> <br>  mid_section_options = {<br>   width: @document_width,<br>   row_colors: [&#39;ffffff&#39;],<br>   cell_style: {<br>    border_width: 0,<br>    borders: [:bottom],<br>    border_color: &#39;c9ced5&#39;,<br>    padding: [10, 15]<br>   }<br>  }<br> <br>  @pdf.table(mid_section_data, mid_section_options) do |table|<br>   table.row(0).border_width = 0.5<br>   table.row(1).text_color = &#39;888892&#39;<br>   table.row(0).padding = [10, 15]<br>   table.row(2).size = 11<br>  end<br> end<br><br><br> def lower_section<br>  report_data = [[&#39;Report&#39;, &#39;&#39;, &#39;View detailed list in new Reporting&#39;],<br>         [&#39;Name&#39;, &#39;Platform&#39;, &#39;Status&#39;],<br>         [&#39;gehpbatosid4pp_oak6f&#39;, &quot;Apple Chibn \n f7euq&quot;, &#39;BLOCKED&#39;],<br>         [&#39;gehpbatosid4pp_oak6f&#39;, &quot;Apple Chibn \n f7euq&quot;, &#39;PASSED&#39;]]<br> <br>  report_data_options = {<br>   width: @document_width,<br>   row_colors: [&#39;ffffff&#39;],<br>   cell_style: {<br>    border_width: 1,<br>    borders: [:bottom],<br>    border_color: &#39;c9ced5&#39;<br>   }<br>  }<br> <br>  @pdf.table(report_data, report_data_options) do |table|<br>   test_status = table.rows(1..-1).column(-1)<br>   test_status.filter do |cell|<br>    case cell.content<br>    when &#39;BLOCKED&#39;<br>     cell.text_color = &#39;FDB357&#39;<br>    when &#39;PASSED&#39;<br>     cell.text_color = &#39;83BC41&#39;<br>    end<br>   end<br> <br>   table.row(0..1).border_width = 0.5<br>   table.row(0).column(2).text_color = &#39;2787c4&#39;<br>   table.row(0).column(2).size = 11<br>   table.row(1).background_color = &#39;EDEFF5&#39;<br>   table.row(1..-1).column(1..2).align = :center<br>   table.row(1).text_color = &#39;465579&#39;<br>   table.row(1).size = 10<br>   table.row(1..-1).padding = [10, 15]<br>   table.row(0).padding = [7, 15]<br>  end<br> end<br><br>  def generate_pdf<br>    header<br>    mid_section<br>    lower_section<br>    @pdf.render<br>  end<br>end</pre><p>A lot of things could have been done better, in this class:</p><ul><li>Create classes for each section and also put together similar styles and reuse them</li></ul><p>Let’s create a controller to get this functionality working</p><h4>Controllers:</h4><pre>class PdfGeneratorController &lt; ApplicationController<br> def index;end<br><br> def generate_pdf<br>    pdf_service = PdfGeneratorService.new<br>    pdf_content = pdf_service.generate_pdf<br>    pdf_filename = &quot;test.pdf&quot;<br><br>    PdfMailer.send_report.deliver_now<br>    File.open(&#39;test.pdf&#39;, &#39;wb&#39;) { |file| file.write(pdf_content) }<br><br>    respond_to do |format|<br>      format.pdf do<br>        send_data pdf_content, filename: pdf_filename, type: &#39;application/pdf&#39;, disposition: &#39;attachment&#39;<br>      end<br>    end<br>  end<br>end</pre><p>For sending the PDF attached to a mail. app/mailers/pdf_mailer.rb</p><h4>Mailers:</h4><pre>class PdfMailer &lt; ApplicationMailer<br> def send_report<br>  @message = &quot;Hey this is a result from your test suite.&quot;<br>  pdf_content_path = generate_pdf_content<br><br>    attachments[&#39;test_result_report.pdf&#39;] = File.read(pdf_content_path)<br><br>    mail(to: &#39;email@gmail.com&#39;, subject: &#39;Test Report Results.&#39;)<br> end<br><br> private<br><br> def generate_pdf_content<br>  pdf_service = PdfGeneratorService.new<br>    pdf = pdf_service.generate_pdf<br>    pdf_file = Tempfile.new([&#39;test_result_report&#39;, &#39;.pdf&#39;], Rails.root.join(&#39;tmp&#39;)) # store the generated pdf in tmp folder to be attached when sending mail.<br>    pdf_file.binmode # converts the document content to binary mode. When you set a file to binary mode using binmode, it ensures that no newline character translations or character encoding conversions occur when reading or writing data<br>    pdf_file.write(pdf)<br>    pdf_file.rewind # move cursor to the top start of the page<br>    pdf_file.close<br>    pdf_file.path # generated pdf path<br> end<br>end</pre><p><strong>Binmode</strong> : When you set a file to binary mode using binmode, it ensures that no newline character translations or character encoding conversions occur when reading or writing data.</p><h4>Views:</h4><p>`<strong>app/views/pdf_generator/index.html.erb</strong>`</p><pre>&lt;div&gt;<br>    &lt;h1&gt;The PDF generator&lt;/h1&gt;<br>    &lt;%= link_to &#39;Generate PDF&#39;, generate_pdf_path(format: :pdf), class: &#39;btn btn-primary&#39; %&gt;<br>&lt;/div&gt;</pre><p>`<strong>app/views/pdf_mailer/send_report.html.erb</strong>`</p><pre>&lt;div&gt;<br>   &lt;h1&gt;The PDF generator Tutorial&lt;/h1&gt;<br>   &lt;p&gt;<br>    &lt;%= @message %&gt;<br>   &lt;/p&gt;<br>&lt;/div&gt;</pre><p>The final result would look like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awx7HxonGgqnxZETVuHBWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iT5qfyU3qSHgwjUGHyJw_w.png" /><figcaption>This is what the final result would look like for the mailer and the pdf overall.</figcaption></figure><p>Extra tasks you could try out;</p><ul><li>Add icons, using prawn-icon</li><li>Add footers at the bottom</li><li>Use dynamic data from an actual source like a Model.</li></ul><p><strong>Important Links:</strong></p><ul><li><a href="https://github.com/prawnpdf/prawn-table">https://github.com/prawnpdf/prawn-table</a></li><li><a href="https://github.com/jessedoyle/prawn-icon">https://github.com/jessedoyle/prawn-icon</a></li><li><a href="https://github.com/ryanb/letter_opener">https://github.com/ryanb/letter_opener</a></li><li><a href="https://github.com/prawnpdf/prawn">https://github.com/prawnpdf/prawn</a></li></ul><p>You can find the working example via <a href="https://github.com/NicholusMuwonge/prawn_pdf">https://github.com/NicholusMuwonge/prawn_pdf</a>. Feel free to comment with any questions and enhancements, I’m happy to learn from you all as well.</p><p>LinkedIn: linkedin.com/in/muwonge-nicholus-868468144/</p><p><em>Cheers 🥂.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5fea5b73e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Roles in a Rails app using Rolify, Devise Invitable, and Pundit.]]></title>
            <link>https://nicholusmuwonge.medium.com/dynamic-roles-in-a-rails-app-using-rolify-devise-invitable-and-pundit-b72011451239?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/b72011451239</guid>
            <category><![CDATA[devise-invitable]]></category>
            <category><![CDATA[pundits]]></category>
            <category><![CDATA[dynamic-role]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rolify]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 10:02:38 GMT</pubDate>
            <atom:updated>2023-09-04T07:21:48.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BsYpXmFTsOnqsLV7" /><figcaption>Photo by <a href="https://unsplash.com/@pete_a?utm_source=medium&amp;utm_medium=referral">Pete Alexopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In many applications, where one account can have more than one user, there’s always a need for the account owner(s) to assign roles/permissions to the members who exist on the same account. This can get tricky if the developer had to set roles for each account because they can change depending on the account’s needs this wouldn’t also be scalable.</p><blockquote>For a scalable system, an account administrator needs to be able to add, remove, and assign roles to the members. This can be viewed in web applications like the <strong>AWS IAM</strong> roles setting for example a feature where one can create a role with a couple of policies or permissions. The admin can then assign this role or someone with admin rights to assign roles to the members of that AWS account. This way, someone with a role ie dev_manager automatically gets the permissions that come with the role for instace ability to invite users, remove them but may not be able to create new roles for instance. This can be very convenient if you have a group of people that need to be assigned similar permissions.</blockquote><p>This write-up shows a step-by-step breakdown of how I would approach building a dummy application like this. Let’s use an example of a blog post platform like <em>Medium.com</em> where a publishing company can create an account. The publishing company can have all its other employees invited under the same account with different roles, for instance, a reviewer who would flag a post as ready for release.</p><p>To kick things off, we need to visualize how this feature would flow;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yH3OuEhaJk0EoTK5Jfp3tg.png" /><figcaption>Data flow in the application</figcaption></figure><p>To get things started let’s create an empty project.</p><pre>rails new publishing_app<br>cd publishing_app</pre><p>Let&#39;s install the dependencies we’ll need by adding these to the generated <strong>Gemfile</strong> like below and run bundle install;</p><pre>gem &#39;devise&#39; # For user authentication<br>gem &#39;rolify&#39; # For role management<br>gem &#39;devise_invitable&#39;, &#39;~&gt; 2.0.0&#39; # For iniviting members to a publisher account<br>gem &#39;pundit&#39; # For authorizations in the application<br>gem &#39;letter_opener&#39;, group: :development # For opening emails in browser during development</pre><p>Each User needs to belong to an Account in our case that being the Publisher. So we need to create migrations for that since other migrations rely on it.</p><pre>bundle exec rails generate migration CreatePublishers name:string description:text</pre><p>The generated migration file for Publisher.</p><pre>class CreatePublishers &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :publishers do |t|<br>      t.string :name<br>      t.text :description<br><br>      t.timestamps<br>    end<br>  end<br>end</pre><p>Let’s generate User migrations and Devise configurations</p><pre>bundle exec rails generate devise:install # to generate all the necessary initializations and configurations<br>bundle rails generate devise User # to generate the model scaffolds. <br># There are devise controller scaffolds as well incase someone wants to make changes to any of those files or just check them out by just running<br># rails generate devise:controllers [scope]</pre><p>The User migration will look like this</p><p>user.rb</p><pre># frozen_string_literal: true<br><br>class DeviseCreateUsers &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :users do |t|<br>      ## Database authenticatable<br>      t.string :email,              null: false, default: &quot;&quot;<br>      t.string :encrypted_password, null: false, default: &quot;&quot;<br><br>      ## Recoverable<br>      t.string   :reset_password_token<br>      t.datetime :reset_password_sent_at<br><br>      ## Rememberable<br>      t.datetime :remember_created_at<br><br>      ## Trackable<br>      # t.integer  :sign_in_count, default: 0, null: false<br>      # t.datetime :current_sign_in_at<br>      # t.datetime :last_sign_in_at<br>      # t.string   :current_sign_in_ip<br>      # t.string   :last_sign_in_ip<br><br>      ## Confirmable<br>      # t.string   :confirmation_token<br>      # t.datetime :confirmed_at<br>      # t.datetime :confirmation_sent_at<br>      # t.string   :unconfirmed_email # Only if using reconfirmable<br><br>      ## Lockable<br>      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts<br>      # t.string   :unlock_token # Only if unlock strategy is :email or :both<br>      # t.datetime :locked_at<br>      t.references :publisher # because user belongs to a publisher.<br><br>      t.timestamps null: false<br>    end<br><br>    add_index :users, :email,                unique: true<br>    add_index :users, :reset_password_token, unique: true<br>    # add_index :users, :confirmation_token,   unique: true<br>    # add_index :users, :unlock_token,         unique: true<br>  end<br>end</pre><p>Then let&#39;s set up devise_invitable</p><pre>bundle exec rails generate devise_invitable:install<br>bundle exec rails generate devise_invitable User</pre><p>The User Invitable migration at this point would look like this</p><pre>class DeviseInvitableAddToUsers &lt; ActiveRecord::Migration[7.0]<br>  def up<br>    change_table :users do |t|<br>      t.string     :invitation_token<br>      t.datetime   :invitation_created_at<br>      t.datetime   :invitation_sent_at<br>      t.datetime   :invitation_accepted_at<br>      t.integer    :invitation_limit<br>      t.references :invited_by, polymorphic: true<br>      t.integer    :invitations_count, default: 0<br>      t.index      :invitation_token, unique: true # for invitable<br>      t.index      :invited_by_id<br>    end<br>  end<br><br>  def down<br>    change_table :users do |t|<br>      t.remove_references :invited_by, polymorphic: true<br>      t.remove :invitations_count, :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token, :invitation_created_at<br>    end<br>  end<br>end</pre><p>Then let&#39;s set up Rolify as well. In this app, the scope is User, but in another app, it could be Admin or something else.</p><pre>bundle exec rails generate rolify Role User</pre><p>The Rolify migration would look like</p><pre>class RolifyCreateRoles &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table(:roles) do |t|<br>      t.string :name<br>      t.references :resource, :polymorphic =&gt; true<br><br>      t.timestamps<br>    end<br><br>    create_table(:users_roles, :id =&gt; false) do |t|<br>      t.references :user<br>      t.references :role<br>    end<br>    <br>    add_index(:roles, :name)<br>    add_index(:roles, [ :name, :resource_type, :resource_id ]) # ensure role is unique per resource and its matching name.<br>    add_index(:users_roles, [ :user_id, :role_id ])<br>  end<br>end</pre><p>Let’s run the migrations.</p><pre>bundle exec rails db:migrate</pre><p>In this project, we will be using the default db option, the <strong>sqlite</strong> option but you can configure yours with your DB of choice.</p><h4>The Models</h4><p>Let&#39;s move on to the models, first the Users.</p><p>user. rb</p><pre>class User &lt; ApplicationRecord<br>  rolify<br>  # Include default devise modules. Others available are:<br>  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable<br>  belongs_to :publisher<br>  has_many :permissions, through: :roles<br><br><br>  devise :invitable, :database_authenticatable, :registerable,<br>         :recoverable, :rememberable, :validatable, :invitable # this is for devise invitable<br><br>  validates_presence_of :publisher<br>  before_validation :assign_role_to_account_owner<br>  <br>  private<br><br>  def assign_role_to_account_owner<br>    admin_role = Role.find_or_create_by(name: &quot;admin&quot;, resource: publisher) do |role|<br>      role.permissions = Permission.all<br>    end<br>  <br>    add_role(:admin, publisher) if admin_role.persisted? &amp;&amp; !invited_by.present?<br>  end<br>end</pre><p>Then the Publisher</p><p>publisher. rb</p><pre>class Publisher &lt; ApplicationRecord<br>  has_many :users<br>  accepts_nested_attributes_for :users <br>  # the above method allows us to access the attributes of User through<br>  # publisher and also access the validations and get created through the Publisher<br><br><br>  validates :name, presence: true, uniqueness: true, length: {minimum:2}<br>  validates :description, presence: true, if: -&gt; { description.present? }<br><br>  resourcify<br>end</pre><p>The Role would look like<br>role.rb</p><pre>class Role &lt; ApplicationRecord<br>  attr_accessor :permission_ids_input # help pick permissions_ids attributes from the Roles form<br>  <br>  has_and_belongs_to_many :users, :join_table =&gt; :users_roles<br>  belongs_to :resource,<br>             :polymorphic =&gt; true,<br>             :optional =&gt; true<br>  has_and_belongs_to_many :permissions, join_table: &quot;roles_permissions&quot;<br>  <br>  before_validation :assign_permissions_from_input, on: :create<br>  before_validation :normalize_name<br><br>  validates :resource_type,<br>            :inclusion =&gt; { :in =&gt; Rolify.resource_types },<br>            :allow_nil =&gt; true<br>  <br>  validates :name, presence: true<br>  validates :name, uniqueness: { scope: [:resource_type, :resource_id], message: &quot;Role already exists for this resource&quot; } <br>  validate :at_least_one_permission<br>  <br>  scopify # A method added from Rolify<br><br>  private<br><br>  def assign_permissions_from_input<br>    self.permission_ids = permission_ids_input&amp;.reject(&amp;:blank?) if permission_ids_input.present?<br>  end<br><br>  def at_least_one_permission<br>    errors.add(:base, &#39;At least one permission is required&#39;) if permissions.empty?<br>  end<br><br>  def normalize_name<br>    self.name = normalize_string(name)<br>  end<br><br>  def normalize_string(str)<br>    str.downcase.gsub(/[^a-z0-9]/, &#39;_&#39;)<br>  end<br><br>end</pre><p>The permission model would look like<br>permission. rb</p><pre>class Permission &lt; ApplicationRecord<br>  has_and_belongs_to_many :roles<br>end</pre><p>Since we have a need for a join table for permissions and roles based on this line in the role.rb model</p><pre>has_and_belongs_to_many :permissions, join_table: &quot;roles_permissions&quot;</pre><p>We also need to create a migration for that and migrate it as well</p><pre>class RolesPermissionsJoinTable &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :roles_permissions, id: false do |t|<br>      t.references :role, null: false<br>      t.references :permission, null: false<br>    end<br>    add_index(:roles_permissions, [ :permission_id, :role_id ], unique: true)<br>  end<br>end</pre><p>For how these models relate to each other, please see the diagram at the start of this blog. :)</p><h4>Controllers:</h4><p>My controller structure looks like this</p><pre>├── application_controller.rb<br>├── concerns<br>└── users<br>    ├── invitations_controller.rb<br>    ├── publishers_controller.rb<br>    ├── roles_controller.rb<br>    ├── sessions_controller.rb<br>    └── users_controller.rb</pre><p>To be able to generate the invitations_controller.rb, I had to run</p><pre>rails generate devise_invitable:views users</pre><p>This generated views for both edit.html.erb and new.html.erb and controllers like invitations_controller.rb to allow us to edit the invitations scaffolds to add any code according to our preference. It so happens that we need to make the following modifications;<br>1. We need to make sure that any other users apart from the account owners need to be invited with a role attached to them. Like the snippet below;</p><pre>&lt;div&gt;<br>  &lt;label&gt;Roles:&lt;/label&gt;<br>  &lt;% Role.where(resource_id: current_user.publisher.id, resource_type: &quot;Publisher&quot;).where.not(name: &quot;admin&quot;).each do |role| %&gt;<br>    &lt;%= check_box_tag &quot;role[role_ids][]&quot;, role.id %&gt;<br>    &lt;%= role.name&amp;.humanize %&gt;&lt;br&gt;<br>  &lt;% end %&gt;<br>&lt;/div&gt;</pre><p>2. We need to swap out the error messaging for the shared alerts to use a simple alerting system in the form as demonstrated below;</p><pre>&lt;% resource.errors.each do |error| %&gt;<br>    &lt;li&gt;&lt;%= error.full_message %&gt;&lt;/li&gt;<br>&lt;% end %&gt;</pre><p>app/controllers/users/invitations_controller.rb</p><pre>class Users::InvitationsController &lt; Devise::InvitationsController<br> before_action :configure_permitted_parameters, if: :devise_controller?<br><br> protected<br> def after_invite_path_for(_resource)<br>  users_users_path<br> end<br><br> def invite_resource<br>  @resource_roles = Role.where(resource_id: current_user.publisher.id, resource_type: &quot;Publisher&quot;).where.not(name: &quot;admin&quot;) # roles that belong to that account.<br><br>  super do |user|<br>   user.publisher = current_user.publisher # the account user must belongs to<br>   user.roles = Role.where(id: params[:role][:role_ids])&amp;.compact_blank # the role to be assigned to this user.<br>   user.save<br>  end<br> end<br><br> def configure_permitted_parameters<br>  devise_parameter_sanitizer.permit(:invite, keys: [:email, :role_ids]) # role_ids is the modification to the permitted params for the invitations<br> end<br>end</pre><p>app/controllers/users/publishers_controller.rb</p><pre>class Users::PublishersController &lt; ApplicationController<br>  before_action :set_publisher, only: %i[ show ]<br>  before_action :authenticate_user!, only: %i[ show ]<br><br>  # GET /publishers or /publishers.json<br>  def index<br>    @publishers = Publisher.all<br>  end<br><br>  # GET /publishers/1 or /publishers/1.json<br>  def show<br>  end<br><br>  # GET /publishers/new<br>  def new<br>    @publisher = Publisher.new<br>    @publisher.users.build<br>  end<br><br>  # POST /publishers or /publishers.json<br>  def create<br>    @publisher = Publisher.new(publisher_params)<br><br>    respond_to do |format|<br>      if @publisher.save<br>        format.html { redirect_to users_publisher_url(https://medium.com/@publisher), notice: &quot;Publisher was successfully created.&quot; }<br>        format.json { render :show, status: :created, location: @publisher }<br>      else<br>        format.html { render :new, status: :unprocessable_entity }<br>        format.json { render json: @publisher.errors, status: :unprocessable_entity }<br>      end<br>    end<br>  end<br><br>  private<br>    # Use callbacks to share common setup or constraints between actions.<br>    def set_publisher<br>      @publisher = Publisher.find(params[:id])<br>    end<br><br>    # Only allow a list of trusted parameters through.<br>    def publisher_params<br>      params.require(:publisher).permit(:name, :description, users_attributes: [:email, :password, :password_confirmation])<br>    end<br>end</pre><p>app/controllers/users/roles_controller.rb</p><pre>class Users::RolesController &lt; ApplicationController<br>  before_action :authenticate_user!<br>  before_action :set_role, only: %i[ show ]<br><br>  # GET /roles or /roles.json<br>  def index<br>    @roles = Role.where(resource_id: current_user.publisher.id).all<br>  end<br><br>  # GET /roles/1 or /roles/1.json<br>  def show<br>  end<br><br>  # GET /roles/new<br>  def new<br>    @role = Role.new<br>    @user = current_user<br>  end<br><br>  # POST /roles or /roles.json<br>  def create<br>    @role = Role.new(role_params)<br>    @role.resource = current_user.publisher<br>    respond_to do |format|<br>      if @role.save<br>        format.html { redirect_to users_roles_path, notice: &quot;Role was successfully created.&quot; }<br>        format.json { render :show, status: :created, location: @role }<br>      else<br>        format.html { render :new, status: :unprocessable_entity }<br>        format.json { render json: @role.errors, status: :unprocessable_entity }<br>      end<br>    end<br>  end<br><br>  private<br>    # Use callbacks to share common setup or constraints between actions.<br>    def set_role<br>      @role = role.find(params[:id])<br>    end<br><br>    # Only allow a list of trusted parameters through.<br>    def role_params<br>      params.require(:role).permit(:name, permission_ids_input: [])<br>    end<br>end</pre><p>app/controllers/users/users_controller.rb</p><pre>class Users::UsersController &lt; ApplicationController<br> before_action :authenticate_user!<br> before_action :set_user, only: %i[show]<br> <br> def index<br>  @users = User.where(publisher: current_user.publisher).all<br> end<br><br> def show<br> end<br><br> private<br><br> def set_user<br>  @user = User.find(params[&quot;id&quot;])<br> end<br>end</pre><h4>The Routes</h4><p>config/routes.rb</p><pre>Rails.application.routes.draw do<br>  devise_for :users, controllers: { invitations: &#39;users/invitations&#39; }<br><br>  namespace :users do<br>    resources :users<br>    resources :publishers<br>    resources :roles<br>  end<br>  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html<br><br>  # Defines the root path route (&quot;/&quot;)<br>  root &quot;users/users#index&quot; # set this to what you prefer<br>end</pre><h4>The Views</h4><pre>.<br>├── layouts<br>│   ├── application.html.erb<br>│   ├── mailer.html.erb<br>│   └── mailer.text.erb<br>└── users<br>    ├── invitations<br>    │   ├── edit.html.erb<br>    │   └── new.html.erb<br>    ├── mailer<br>    │   ├── invitation_instructions.html.erb<br>    │   └── invitation_instructions.text.erb<br>    ├── publishers<br>    │   ├── _form.html.erb<br>    │   ├── _publisher.html.erb<br>    │   ├── _publisher.json.jbuilder<br>    │   ├── edit.html.erb<br>    │   ├── index.html.erb<br>    │   ├── index.json.jbuilder<br>    │   ├── new.html.erb<br>    │   ├── show.html.erb<br>    │   └── show.json.jbuilder<br>    ├── roles<br>    │   ├── _form.html.erb<br>    │   ├── _role.html.erb<br>    │   ├── _role.json.jbuilder<br>    │   ├── edit.html.erb<br>    │   ├── index.html.erb<br>    │   ├── index.json.jbuilder<br>    │   ├── new.html.erb<br>    │   ├── show.html.erb<br>    │   └── show.json.jbuilder<br>    └── users<br>        ├── _user.html.erb<br>        ├── index.html.erb<br>        ├── index.json.jbuilder<br>        ├── show.html.erb<br>        └── show.json.jbuilder</pre><p>The changes I made in the app/views/users/invitations/new.html.erb to be able to assign roles during the invitation process.</p><p>app/views/users/invitations/new.html.erb</p><pre>&lt;h2&gt;&lt;%= t &quot;devise.invitations.new.header&quot; %&gt;&lt;/h2&gt;<br><br>&lt;%= form_for(resource, as: resource_name, url: invitation_path(resource_name), html: { method: :post }) do |f| %&gt;<br>  &lt;% resource.errors.each do |error| %&gt;<br>    &lt;li&gt;&lt;%= error.full_message %&gt;&lt;/li&gt;<br>  &lt;% end %&gt;<br><br>  &lt;% resource.class.invite_key_fields.each do |field| -%&gt;<br>    &lt;div class=&quot;field&quot;&gt;<br>      &lt;%= f.label field %&gt;&lt;br /&gt;<br>      &lt;%= f.text_field field %&gt;<br>    &lt;/div&gt;<br>    &lt;br/&gt;<br>    &lt;div&gt;<br>      &lt;label&gt;Roles:&lt;/label&gt;<br>      &lt;% Role.where(resource_id: current_user.publisher.id, resource_type: &quot;Publisher&quot;).where.not(name: &quot;admin&quot;).each do |role| %&gt;<br>        &lt;%= check_box_tag &quot;role[role_ids][]&quot;, role.id %&gt;<br>        &lt;%= role.name&amp;.humanize %&gt;&lt;br&gt;<br>      &lt;% end %&gt;<br>    &lt;/div&gt; <br>    &lt;br/&gt;<br>    &lt;hr /&gt;<br>  &lt;% end -%&gt;<br><br>  &lt;div class=&quot;actions&quot;&gt;<br>    &lt;%= f.submit t(&quot;devise.invitations.new.submit_button&quot;) %&gt;<br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><p>app/views/users/publishers/_form.html.erb</p><p><em>This is the form used to create the Publisher account and the account owner.</em></p><pre>&lt;%= form_with(model: publisher, url: users_publishers_path) do |form| %&gt;<br>  &lt;% if publisher.errors.any? %&gt;<br>    &lt;div style=&quot;color: red&quot;&gt;<br>      &lt;h2&gt;&lt;%= pluralize(publisher.errors.count, &quot;error&quot;) %&gt; prohibited this publisher from being saved:&lt;/h2&gt;<br><br>      &lt;ul&gt;<br>        &lt;% publisher.errors.each do |error| %&gt;<br>          &lt;li&gt;&lt;%= error.full_message %&gt;&lt;/li&gt;<br>        &lt;% end %&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  &lt;% end %&gt;<br><br>  &lt;div&gt;<br>    &lt;%= form.label :name, style: &quot;display: block&quot; %&gt;<br>    &lt;%= form.text_field :name %&gt;<br>  &lt;/div&gt;<br>  &lt;%= form.fields_for :users do |user_form| %&gt;<br>    &lt;div class=&quot;field&quot;&gt;<br>      &lt;%= user_form.label :email %&gt;&lt;br /&gt;<br>      &lt;%= user_form.email_field :email, autofocus: true, autocomplete: &quot;email&quot; %&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;field&quot;&gt;<br>      &lt;%= user_form.label :password %&gt;<br>      &lt;% if @minimum_password_length %&gt;<br>      &lt;em&gt;(&lt;%= @minimum_password_length %&gt; characters minimum)&lt;/em&gt;<br>      &lt;% end %&gt;&lt;br /&gt;<br>      &lt;%= user_form.password_field :password, autocomplete: &quot;new-password&quot; %&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;field&quot;&gt;<br>      &lt;%= user_form.label :password_confirmation %&gt;&lt;br /&gt;<br>      &lt;%= user_form.password_field :password_confirmation, autocomplete: &quot;new-password&quot; %&gt;<br>    &lt;/div&gt;<br>  &lt;% end %&gt;<br><br>  &lt;div&gt;<br>    &lt;%= form.label :description, style: &quot;display: block&quot; %&gt;<br>    &lt;%= form.text_area :description %&gt;<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;%= form.submit %&gt;<br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><p>For further reference, the link to the repo files will be shared at the end of the blog.<br>At this point, we need to add <strong>Pundit</strong> to the application for authorization.</p><p>Add this to the application_controller.rb</p><pre>include Pundit::Authorization</pre><p>Run the initializer below to generate the policies folder and the app/policies/application_policy.rb file.</p><pre>bundle exec rails g pundit:install</pre><p>We’ll go ahead and create a new User Policy inheriting from the application_policy to help us authorize users and limit the scope of who can view users that belong to an account based on the permissions they possess.</p><p>app/policies/user_policy.rb</p><pre>class UserPolicy &lt; ApplicationPolicy<br> class Scope &lt; Scope<br>    def resolve<br>      if user.user?<br>        scope.all<br>      end<br>    end<br>  end<br><br>  def index?<br>    user.has_role?(:admin, user&amp;.publisher) or has_permission(&quot;view_users&quot;)<br>  end<br><br> private<br><br> def has_permission(permission)<br>  user.permissions.exists?(name: permission)<br> end<br>end</pre><p>We’ll go ahead and add the authorization logic to the users_controller.rb</p><pre>class Users::UsersController &lt; ApplicationController<br> ...<br> def index<br>  @users = User.where(publisher: current_user.publisher).all<br>  authorize current_user<br> end<br> ...<br>end</pre><p>This means that any user who isn’t the owner of the account or any user without ‘view_users’ rights will get an exception when they navigate to the index.</p><pre>Pundit::NotAuthorizedError</pre><p>Since we haven’t fully handled a fallback screen for the exception, in this example we can explore other ways the authorization may work like showing certain content to authorized users and different content for non-authorised users. So we’ll make the adjustment in our code below</p><p>app/views/users/users/index.html.erb</p><pre>&lt;div id=&quot;users&quot;&gt;<br>  &lt;% if policy(current_user).index? %&gt;<br>    &lt;% @users.each do |user| %&gt;<br>      &lt;%= render user %&gt;<br>      &lt;p&gt;<br>        &lt;%= link_to &quot;Show this user&quot;, users_user_path(user) %&gt;<br>      &lt;/p&gt;<br>      &lt;hr /&gt;<br>    &lt;% end %&gt;<br>  &lt;% else %&gt;<br>      &lt;div&gt;You&#39;re not authorised to view the users&lt;/div&gt;<br>  &lt;% end %&gt;<br>&lt;/div&gt;</pre><p>and omit the ‘authorize current_user’ line from the user controller.</p><p>A few final steps to take this for a test drive. We need permissions to be present to be able to create roles in the application. So we will seed a few roles for testing purposes but in a production environment, you’d be better off using the ‘permissions.yml’ file to keep all the new additional permissions and pick them from there to update the production db.</p><p>db/seeds.rb</p><pre>Permission.create!(name: &quot;view_users&quot;, controller: &quot;users&quot;, description: &quot;can view current publisher account users&quot;, controller_method: &quot;index&quot;)<br>Permission.create!(name: &quot;edit_users&quot;, controller: &quot;users&quot;, description: &quot;can update current publisher account users profiles&quot;, controller_method: &quot;update&quot;)</pre><p>Run seeders to Populate the Permissions table to aid in creating the Publisher account roles.</p><pre>bundle exec rails db:seed</pre><p>So to test and see the application in operation, we would need to go through the following steps:</p><ul><li>Create a Publisher account as an owner</li><li>login and create roles for that account ( Role requires at least one permission to be created.)</li><li>Invite other users and assign roles to them</li><li>Invited user accepts invitation and logs in to see if he/she is able to view users for that account based on the permissions they have.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F858823824%3Fh%3D14988d275a%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F858823824%2F14988d275a&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1716432712-43a73773ad53973f03fea69b470e7040f79603b598932e329383e5ac096dd744-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1512" height="982" frameborder="0" scrolling="no"><a href="https://medium.com/media/354a44c8bfc9d02f1615250806b75c00/href">https://medium.com/media/354a44c8bfc9d02f1615250806b75c00/href</a></iframe><p>There’s a lot that can still be done like writing some tests, improving the UI, challenging oneself to have scoped authorizations for system admins and other users, and adding more functionality like creating blog posts. However, this couldn&#39;t be covered in this blog post.</p><p>Any feedback is appreciated. Thank you.</p><p><em>You can find the demo project files </em><a href="https://github.com/NicholusMuwonge/rails_dynamic_roles"><em>here</em></a><em>.</em></p><p>Find me on LinkedIn <a href="https://www.linkedin.com/in/muwonge-nicholus-868468144/">https://www.linkedin.com/in/muwonge-nicholus-868468144/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b72011451239" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Background Cron Jobs in Rails Using Sidekiq, Redis, and Whenever gems.]]></title>
            <link>https://nicholusmuwonge.medium.com/background-cron-jobs-in-rails-using-sidekiq-redis-and-whenever-gems-25c965ba648c?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c965ba648c</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[sidekiq]]></category>
            <category><![CDATA[background-jobs]]></category>
            <category><![CDATA[whenever]]></category>
            <category><![CDATA[cronjob]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 11:34:30 GMT</pubDate>
            <atom:updated>2021-04-06T06:26:58.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCuUVmtx5vYZpDsyu3DdyQ.png" /></figure><p>Earlier this week, I was tasked to add a feature that sent out notifications when a certain task didn’t check in from a third-party API. I had to come up with a background job that did this heavy lifting in intervals to keep the users informed of certain failures in certain transactions. This is how I solved this challenge and I hope my approach helps you implement your own solution.</p><p><strong>NB</strong>: <em>This tutorial is based on a fictional scenario that you could easily learn from and implement in your own project. This tutorial could be useful for scenarios like sending out scheduled marketing emails, app administration, etc.</em></p><p>For this, I needed to work with the <strong>Whenever</strong> gem for running the scheduled checks/jobs in the background and <strong>Sidekiq</strong> for executing the jobs(also visualizing the queued jobs ) at the same time in form of threads and <strong>Redis</strong> memory database to store this data in the memory as the app ran.</p><p>So let’s dive into it already.</p><p>Add the whenever gem to your Gemfile.</p><pre>gem &#39;whenever&#39;, require: false</pre><p>then run bundle install to install the gem.</p><p>Next we Wheneverize the project by running bundle exec wheneverize . . Read more about <strong>whenever gem </strong>options from <a href="https://github.com/javan/whenever">https://github.com/javan/whenever</a></p><p>A <strong>schedule.rb</strong> the file will be generated in the project Config folder. In this file, you can add your scheduled task runners. In this example, we shall be working with rake tasks. Read more about rake tasks here <a href="https://github.com/ruby/rake">https://github.com/ruby/rake</a>.</p><p><strong>config/schedule.rb</strong></p><pre>// set where you want to see the logs for jobs at.<br>set :output, { error: &#39;/log/error.log&#39;, standard: &#39;/log/cron.log&#39;}</pre><pre>every 2.hours do<br>  rake &#39;shopping_cart_notifier:pending_checkout_clearance&#39;<br>end</pre><p>then at this point, let’s go ahead and create the rake tasks because what we have up there is just a placeholder. To be honest you could do this first and add it to the <strong>schedule.rb</strong> later.</p><p><strong>lib/tasks/shopping_cart_notifier.rake</strong></p><pre>require &#39;rake&#39;<br>namespace :shopping_cart_notifier do<br>  desc &#39;Sends notification about items in the cart that haven&#39;t been paid for and checked out.&#39;<br>    task pending_checkout_clearance: :environment do<br>      NotifyPendingCheckoutJob.perform_later<br>    end<br>end</pre><p>Let&#39;s go ahead and create the actual function that does the job NotifyPendingCheckoutJob . Now this will require Sidekiq and Redis installed.</p><p>Add these gems to your Gemfile and run bundle install.</p><pre>gem ‘<a href="https://rubygems.org/gems/sidekiq">sidekiq</a>’</pre><pre>gem ‘<a href="https://rubygems.org/gems/redis">redis</a>’, ‘~&gt; 4.0’</pre><pre>gem ‘<a href="https://rubygems.org/gems/letter_opener">letter_opener</a>’ // you may need this to preview emails locally in case its ehat you&#39;re using emails as the form of notification.</pre><p>then go ahead and place this line in the Config/application.rb to set up Sidekiq to work within the application. Add at the end right before the end keyword.</p><pre>config.active_job.queue_adapter = :sidekiq</pre><p>Go to the initializers and configure Sidekiq to use Redis. <strong>config/initializers/sidekiq.rb</strong></p><pre>if Rails.env.production?<br>    redis_host = &#39;127.0.0.1&#39;<br>    redis_port = 6379<br>    redis_db = 1<br>  else<br>    redis_host = &#39;localhost&#39;<br>    redis_port = 6379<br>    redis_db = 0<br>  end<br>  <br>  Sidekiq.configure_server do |config|<br>    config.redis = { url: &quot;redis://#{redis_host}:#{redis_port}/#{redis_db}&quot; }<br>  end<br>  <br>  Sidekiq.configure_client do |config|<br>    config.redis = { url: &quot;redis://#{redis_host}:#{redis_port}/#{redis_db}&quot; }<br>  end</pre><p>Then let’s go to the routes and set up a route to view the Sidekiq user interface by adding these two lines.</p><pre>require &#39;sidekiq/web&#39;<br>authenticate :[user(for example the ordinary user)] do<br>  mount Sidekiq::Web =&gt; &#39;/sidekiq&#39;<br>end</pre><p>Then lastly, let&#39;s configure our app to use the letter opener for testing to check if the letters were sent through. Add these two lines to the <strong>config/environments/development.rb </strong>file.</p><pre>config.action_mailer.delivery_method = :letter_opener<br>config.action_mailer.perform_deliveries = true</pre><p>Then lets create a job file in <strong>app/jobs/notify_pending_checkout_job.rb</strong></p><pre>class NotifyPendingCheckoutJob &lt; ApplicationJob<br>    sidekiq_options retry: 5<br>    queue_as :default<br>  <br>    def perform(*_args)<br>        $pending_checkouts = ShoppingCart.where(status: :not_checked_out).where([&#39;created_at &lt; ?&#39;, 2.hours.ago]).all</pre><pre>                          AdminMailer.notify_admin_pending_checkouts($pending_checkouts).deliver! if $pending_checkouts.any? // this is for sending out email notifications<br>    end<br>  end</pre><p>Let’s create the mailer functions now. This can be done in <strong>app/mailers/admin_mailer.rb</strong></p><pre>class AdminMailer&lt;ApplicationMailer<br>    default from: &#39;[some email]@[some_domain].com&#39;<br>    layout &#39;mailer&#39;<br><br>    def notify_admin_pending_checkouts(pending_checkout)<br>        @pending_checkout=pending_checkout<br>        mail(<br>        to: &#39;[some admin mail]@domain.com&#39;,<br>        subject: &quot;#{@pending_checkout.count} cart items have not been checked out for the past two hours.&quot;<br>        )<br>    end<br>end</pre><p>Let’s create an <strong>html.erb</strong> template to display this data to the admin in the tables. Better we do in a table. Create it in <strong>app/views/admin_mailer/notify_admin_pending_checkouts.html.erb.</strong></p><pre>&lt;h1&gt;These users need to be reminded to checkout their cart items. &lt;/h1&gt;<br><br>// add your display logic here<br>&lt;table style=&quot;width:100%&quot;&gt;<br>    &lt;tr style=&quot;text-align:center; &quot;&gt;<br>        &lt;th&gt;User&lt;/th&gt;<br>        &lt;th&gt;cart Id&lt;/th&gt;<br>    &lt;/tr&gt;<br>    &lt;%= $pending_checkouts.each do |item|%&gt;<br>        &lt;tr&gt;<br>            do something<br>        &lt;/tr&gt;<br>    &lt;% end %&gt;<br>&lt;/table&gt;</pre><p>To view Sidekiq in the browser, you have to ensure that Redis is installed and running by running redis_server in the terminal and then accessing yourapp.com/sidekiq.. To do this in your app template on a nav link or button, you can also use the Sidekiq path since it&#39;s already added to the routes.</p><pre>&lt;%= link_to sidekiq_web_path,  class: &quot;[your class]&quot;, target: &quot;_blank&quot; do%&gt;<br> Sidekiq<br>&lt;% end %&gt;</pre><p>Looks like we’re done with this. So, let’s test it out locally. Go ahead and create a seeder to create mock data. Alternatively, go ahead and open up the <strong>rails console</strong> and achieve the same result.</p><p>Go to the rake task and change the perform_later to perform_now to be able to see the task in action when you run the rake task in the terminal for instance.</p><pre>rake &#39;shopping_cart_notifier:pending_checkout_clearance&#39;</pre><p>Please remember to revert it after testing. Also, test out the scenario for delivering later by reducing the schedule times in the <strong>schedule.rb.</strong></p><p>I think that will be all for this post. I will look into writing about using Sidekiq in production managed by Systemd and Redis in my next post.</p><p>Read more about Sidekiq: <a href="https://github.com/mperham/sidekiq">https://github.com/mperham/sidekiq</a></p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c965ba648c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing Props from Child to Parent in React]]></title>
            <link>https://nicholusmuwonge.medium.com/passing-props-from-child-to-parent-in-react-a1fb4b7e5b70?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1fb4b7e5b70</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[child-component]]></category>
            <category><![CDATA[props]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 14:10:23 GMT</pubDate>
            <atom:updated>2021-01-01T14:10:23.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3IvQLRqVXoquj5oG" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Props</strong> are a very important aspect of React or React Native as they determine the characteristics of a Component. These need to be present for the Component to work as expected.For instance</p><blockquote>&lt;Input value={add_something} /&gt;</blockquote><ul><li>The prop value must be present for the Input field to work as expected.</li></ul><p>You can read more about the props over at the react docs <a href="https://reactjs.org/docs/components-and-props.html">https://reactjs.org/docs/components-and-props.html</a>.</p><p>Since components work in a network, they always share properties with each other for instance, a button inside a form may take on the backgroundColor similar to that of the parent or padding so it becomes crucial to know how to work past these properties between components.</p><p>There are a couple of methods in which components could access each other’s properties(props) like central state management libraries like <strong>Redux</strong>, then <strong>React’s Context API</strong> which I will get into in future posts and passing them on a component to component basis. Any other way, I will be happy to learn from you.</p><p>My focus will be on a component level where a child passes props to its parent component as it gave me hard time when I tried to implement it.</p><blockquote>The example I will use below demonstrates just picking the button text and displaying it in the parent component.</blockquote><pre>// This is the parent component somewhere in my file structure or same file.It just takes child prop button text and displays it.</pre><pre>export default function Parent() {</pre><pre>    const [data_from_child, setData]= useState(&#39;&#39;);</pre><pre>// this function should be taking in a value that will be passed in the child element</pre><pre>    const passedProps=(value)=&gt;{</pre><pre>      setData(value)</pre><pre>     }</pre><pre>    return (</pre><pre>       &lt;div className=&quot;App&quot;&gt;</pre><pre>         &lt;h1&gt;Below is the button&#39;s text&lt;/h1&gt;</pre><pre>         &lt;h3&gt;{data_from_child}&lt;/h3&gt;</pre><pre>         &lt;ChildComponent passProps={passedProps}/&gt;</pre><pre>       &lt;/div&gt;</pre><pre>      );</pre><pre>}</pre><p>The child component sets the value to be passed to the parent component</p><pre>const ChildComponent=(props)=&gt;{</pre><pre>   const showButtonText=()=&gt;{<br>      // not the most ideal Id to use but it should do the job for         this explanation.</pre><pre>     return document.getElementById(&#39;test-button&#39;).innerHTML;</pre><pre>   }</pre><pre>  return(</pre><pre>    &lt;button id=&#39;test-button&#39; <br>     // showButtonText returns a value that I pass in to the function in the parent component.</pre><pre>     onClick={()=&gt;props.passProps(showButtonText)}&gt;<br>     Button Name <br>    &lt;/button&gt;</pre><pre>   )</pre><pre>}</pre><p>This implementation is for hooks and I am happy to see how you would approach it in the comments.</p><p>Find my actual working code <a href="https://codesandbox.io/s/sharing-props-v5t9d?file=/src/App.js:111-427">here</a> for testing.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fv5t9d&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fv5t9d&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fv5t9d%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e13f108f794b9097f7b5a43f4c6638b/href">https://medium.com/media/7e13f108f794b9097f7b5a43f4c6638b/href</a></iframe><p>Thanks for reading. Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1fb4b7e5b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social Login with React, Rails API, Devise Auth Token]]></title>
            <link>https://nicholusmuwonge.medium.com/social-login-with-react-rails-api-devise-auth-token-b938d89f85ca?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/b938d89f85ca</guid>
            <category><![CDATA[devise-auth-token]]></category>
            <category><![CDATA[omniauth]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[social-login]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Sun, 25 Oct 2020 15:29:09 GMT</pubDate>
            <atom:updated>2020-10-30T15:31:19.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4_NWeBKUBhZargvz" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Just the other week, I was faced with a challenge to implement social auth using Omniauth. It seems to me, it wasn&#39;t well optimized for APIs and this could cause you some good headache. Here’s a little demonstration of how you could approach it.</p><p>The first challenge is always figuring the data flow to login someone here it goes;</p><ul><li>In React you invoke a request by clicking a button which fires off a request to the provider (Facebook or Google or whatever). This is usually where you have attached a client ID to the request.</li><li>The client returns you a response with the details, an access token and a user id.</li><li>This is what you send to the back end to pick out the user details and save the user or log them in and send a message and an access-token through the callback.</li></ul><p>Let’s start with the Front end in React.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64cd1e174bba4338e5190c8ad0ad0253/href">https://medium.com/media/64cd1e174bba4338e5190c8ad0ad0253/href</a></iframe><p>So when that&#39;s all done, we expect data from the backend in the form of a response from the API.</p><p>We need to add Omniauth to our application by adding these gems to the Gemfile and running bundle install</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cede0b9aed0c70ba3f84217401671cb1/href">https://medium.com/media/cede0b9aed0c70ba3f84217401671cb1/href</a></iframe><p>Set up the providers after getting the credentials from either Google developers console or Facebook console</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda5c6b54a8d808b59feb30a38934006/href">https://medium.com/media/bda5c6b54a8d808b59feb30a38934006/href</a></iframe><p>I&#39;m assuming you already have a user model in place so place this code in there</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cadaaad871dbbb45e26d0347b52553c1/href">https://medium.com/media/cadaaad871dbbb45e26d0347b52553c1/href</a></iframe><p>So we also set up the <strong>CORS </strong>and add this other code to allow Devise omniauth to work perfectly with APIs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dde0905f37b4f892c99136b065670aa6/href">https://medium.com/media/dde0905f37b4f892c99136b065670aa6/href</a></iframe><p>Let&#39;s go ahead and add a controller where all this logic that I stated up will be handled</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43cb1e22651b985b56b4fcaebac79ce1/href">https://medium.com/media/43cb1e22651b985b56b4fcaebac79ce1/href</a></iframe><p>To finish it all off, let&#39;s add a call back URL that will be called in React in which we shall be sending information about the user login.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1ed46a41f22b71c894845670ad3254c/href">https://medium.com/media/d1ed46a41f22b71c894845670ad3254c/href</a></iframe><p>Don&#39;t forget to add rack-cors a gem for the <strong>CORS </strong>to the Gemfile and run bundle i .</p><p>To test it all out, get the route we just created and paste in as the callback URL in react and make a request. Make sure both servers are started and running.</p><p>Hope this helps and if you have questions please leave me a comment. I will get back to you soonest as I can.</p><p>Cheers!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b938d89f85ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self Review And Future Projections.]]></title>
            <link>https://nicholusmuwonge.medium.com/self-review-and-future-projections-95bb70407e87?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/95bb70407e87</guid>
            <category><![CDATA[planning]]></category>
            <category><![CDATA[development-and-growth]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 23:36:28 GMT</pubDate>
            <atom:updated>2019-04-29T23:38:19.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nvGDHoCim1v8tlBk" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I on joining the Andela deferral program had expectations in mind of both what was expected of me and what I expected of myself. Well, diving right in, I always expected:</p><ul><li>To improve my skills in javascript since in the previous challenge I had struggled a great deal.</li><li>To be able to work more with image uploads and larger files since in Flask they made a mess of me hence a hard time in the front end.</li><li>To Improve my saving and retrieving of data in Postgres with more routes to carry out specified tasks for easy execution in the frontend.</li><li>To Learn how to work in a team and with a spoiler from the deferral program predecessors, I expected to take remote meetings and also become good at it.</li><li>To learn better ways of using git and Continous Integration tools.</li><li>To become a better communicator with the rest of the team.</li></ul><p>Well, I got to tick most of these wishes as accomplished but Javascript since we didn&#39;t get to that bit. I, however, enjoyed working on setting up user profiles feature in Django because for the first time I knew exactly what I was doing with the help of a well-detailed tutorial. The implementation was also a world-class kind of way and I would say I felt proud of myself for it.</p><p>With this feature, I was able to separate apps to handle different concerns, Implement signals with proper listeners, wrote clean code and tested all the edge cases for this feature.</p><p>Meanwhile, everything didn&#39;t go according to plan. For instance, Rating an article feature seemed way more complicated than expected. It took me a long time to get the application returning an average score for ratings on an article. Furthermore, on merging this feature, the code broke and I had to just fix it with another story. I realized I needed to read further ahead on the feature before writing any code.</p><p>My development plan on the other hand involves:</p><ul><li>Learning something new every day in python to help improve my understanding of the language as a whole.</li><li>Working on more test projects in Django to get me more familiar with the framework come simulations.</li><li>To organize level up sessions to discuss with others about areas in which I feel weak.</li></ul><p>On conclusion of the deferral program, I intend to:</p><ul><li>Improve my skills in writing unit test in the next three weeks to enable me to get through simulations and apprenticeships with less worry.</li><li>learn javascript from basics including the best practices so as to have a shortcut while learning React/Redux.</li><li>Train myself to work within the official hours and accomplish my daily tasks to prevent burnouts.</li><li>Take youtube lessons on professional writing for about a week to allow me to publish stories that are professional.</li></ul><p>I hope to rely on internet resources to level up like Thinkster.io, my teammates and coding on the go.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95bb70407e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Giving & Receiving Feedback In A Team.]]></title>
            <link>https://nicholusmuwonge.medium.com/giving-receiving-feedback-in-a-team-4c2d3390f26f?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2d3390f26f</guid>
            <category><![CDATA[feedback]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[code-reviewing]]></category>
            <category><![CDATA[ask]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 22:34:34 GMT</pubDate>
            <atom:updated>2019-04-29T22:34:34.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l2s7nhnu3993eMDD" /><figcaption>Photo by <a href="https://unsplash.com/@headwayio?utm_source=medium&amp;utm_medium=referral">Headway</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In software development, working in teams is inevitable for big and complex applications for various reasons. These range from the fact that it would take ages for one to handle on their own to the fact that it would have a lot of bugs. So working in teams helps regulate these shortfalls.</p><p>The biggest advantage for the developers is that their code improves through both seniors’ and peers’ review of the code. One can never get away with doing mediocre work this way.</p><p>At Andela, during the deferral program, I am a member of team Acqua where as we worked on a project called Authors’ Haven, the teammates and the Technical Team Lead review code to be able to merge foolproof code. I have got all the feedback that makes you cry while you fix changes, as you chew on a full bucket of popcorn at 2, am in the morning. It&#39;s not that bad though because the following time I become more careful on what I commit and push.</p><p>Below is an example of ASK kind of feedback ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6movhh1nAzQ5oicljwuCuw.jpeg" /><figcaption>Kind, Specific and Actionable feedback</figcaption></figure><p>As you can see, I didn&#39;t just take on the feedback, defending what I knew and enquiring more on why I should drop my practice for their recommendation. In simple terms the pros that superseded my practices’ pros.</p><p>On finding the proper reason for their recommendation, I went ahead and fixed my code and I can gladly say its better state. Nevertheless, since we were all new to giving professional feedback, there are some reviews that were given that weren&#39;t Actionable, Specific and Kind in nature for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHAtU6dbbyo0eL1cwl04oA.jpeg" /><figcaption>rude reviews</figcaption></figure><p>Well, sadly that&#39;s me giving that review before having any idea of what I should follow . This feedback was more attacking someone instead of helping them improve and ever since then I have come to give reviews that help others improve in a nice way also as illustrated down below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKlKaoiIsK_axGiQNs9osw.jpeg" /><figcaption>cool feedback</figcaption></figure><p>I think here, there’s a great deal of improvement I inspired through suggesting an alternative and also adding why I suggested it.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2d3390f26f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Timelines Expectations In Software Development]]></title>
            <link>https://nicholusmuwonge.medium.com/timelines-expectations-in-software-development-2e6c769a6364?source=rss-44e0e2467519------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6c769a6364</guid>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[meeting-expectations]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[timeline]]></category>
            <dc:creator><![CDATA[Nicholus Muwonge]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 21:42:28 GMT</pubDate>
            <atom:updated>2019-04-29T21:44:40.299Z</atom:updated>
            <content:encoded><![CDATA[<p>As a programmer what yields more stress than broken code is most definitely failure to deliver assigned tasks to the client. This doesn&#39;t mean one has failed to finish up the task, rather finish up in the designed time. This in the worst case scenario would be losing the client or being sued by the client for losing so much money in the time you failed to deliver a task.</p><p>Well, having given a brief insight into its causes, I have an experience of my own concerning the issue to share. While I was in the deferral program’s initial stages, I was surely excited and ready to deliver features at the earliest of convenience. The Pivotal Tracker always had feature broken down and with them came a timeline against which everyone would be executed.</p><p>During sprint planning, I happened to have done some choices beforehand of the feature I wished to handle first which was only a two-starred <a href="https://www.pivotaltracker.com/story/show/164691217">story </a>for the first week. It didn&#39;t feel convincing enough because I would be the cool developer I set out to be, so I request for another one point <a href="https://www.pivotaltracker.com/story/show/164691215">story</a> to top it all off atleast save the goal in mind.</p><p>Being green in Django and new to team software development, I realized halfway the one-star story wasn&#39;t getting any easier, and I was so afraid I wouldn&#39;t even be able to deliver this simple feature. I kept raising stand-ups that had statements like ‘fixing user validation bugs’ for two days.</p><p>Having learned my lesson, a day left to the demo, I came out to the whole team about how I realized I couldn&#39;t deliver the promised tasks but rather just the one-star story that week that I had taken on as an extra. Luckily enough, a group mate of mine was able to pick up my would have been major task.</p><p>At this point in time, I learned that I was supposed to anticipate my weakness of having little proficiency in Django and I should have accounted for it in setting a timeline for myself. I also realized that If I had pushed back earlier, I would have produced the best work I was expected of.</p><p>A fortnight later, I was back in the same scenario where I had two features on the backlog but had to get assigned new tasks for the week. Having learned from my past actions, I asked for a point feature that I would be able to deliver alongside the other pending two within that week and most realistically, I was able to deliver these tasks as promised.</p><p>So, I urge any developer to take on tasks they can best handle rather than promising and not delivering which instead damages their reputation.</p><p>Thanks for the read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6c769a6364" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>