<?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 Spoorthi on Medium]]></title>
        <description><![CDATA[Stories by Spoorthi on Medium]]></description>
        <link>https://medium.com/@spoorthi0811?source=rss-610ac2bee70b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_c0vMIjXjrDBORfgeVBdqw.jpeg</url>
            <title>Stories by Spoorthi on Medium</title>
            <link>https://medium.com/@spoorthi0811?source=rss-610ac2bee70b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:52:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@spoorthi0811/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[Catching Exceptions]]></title>
            <link>https://medium.com/@spoorthi0811/catching-exceptions-43f1558e46da?source=rss-610ac2bee70b------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f1558e46da</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[catch]]></category>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[exceptions-in-java]]></category>
            <dc:creator><![CDATA[Spoorthi]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 09:01:33 GMT</pubDate>
            <atom:updated>2023-01-04T09:01:33.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of us are aware of exception-handling mechanisms in any programming language, but do we know the mechanism in depth?</p><p>At least my answer was NO until I learned on few rules that need to be mostly considered for exception handling in Java. I am a newbie to Java, when was reading/learning Exception handling, I learned on few things that were worth sharing:</p><figure><img alt="try — catch blocks" src="https://cdn-images-1.medium.com/max/588/1*kEhyyY7FJCL1FmEFBwSqdw.png" /></figure><h4><strong>Catching Multiple Exceptions</strong></h4><p>There can be as many catch blocks as the number of exceptions that can/could be thrown from the try code block.</p><pre>try {<br>      arr[10] = 11;<br>}<br>    <br>catch (NumberFormatException e1) {<br>      System.out.println(&quot;NumberFormatException =&gt; &quot; + e1.getMessage());<br>}<br>    <br>catch (IndexOutOfBoundsException e2) {<br>      System.out.println(&quot;IndexOutOfBoundsException =&gt; &quot; + e2.getMessage());<br>} </pre><p>In the above example, we have NumberFormatException and IndexOutOfBoundsException exceptions being used. The try block can throw NumberFormatException if our code attempts to make a conversion of a string with an incorrect format to a numeric value. Similarly, the try block can throw IndexOutOfBoundsException when our code tries to access the element in any array that is out of range.</p><p>From Java 7 and later, we can now catch more than one exception with just one catch block. Each Exception type that can be handled by the catch blocks needs to be separated by a vertical bar | . The Syntax for the same is shown below:</p><pre>try {<br>  // code<br>} catch (ExceptionType1 | Exceptiontype2 ex) { <br>  // catch block<br>}</pre><p>Catching multiple exceptions in one catch block reduces any code duplication and increases efficiency. The bytecode generated while compiling the program will be much smaller than the program having multiple catch blocks as there is no code redundancy.</p><h4><strong>Order of Catch Block does matter</strong></h4><p>If the protected code can throw different exceptions which are not under the same inheritance tree, which means that they aren’t having a parent-child relationship, then the catch blocks can be placed in any order. However, if there exists a parent-child relationship, then we have to sort the most specific catch block at first, followed by the general ones.<br>For instance,</p><pre>class ListOfNumbers {<br><br>  // create an integer array<br>  private int[] list = {5, 6, 8, 9, 2};<br><br>  // method to write data from array to a fila<br>  public void writeList() {<br>    PrintWriter out = null;<br><br>    try {<br>      System.out.println(&quot;Entering try statement&quot;);<br><br>      // creating a new file OutputFile.txt<br>      out = new PrintWriter(new FileWriter(&quot;OutputFile.txt&quot;));<br><br>      // writing values from list array to Output.txt<br>      for (int i = 0; i &lt; 7; i++) {<br>        out.println(&quot;Value at: &quot; + i + &quot; = &quot; + list[i]);<br>      }<br>    }<br>    <br>    catch (FileNotFoundException e) {<br>      System.out.println(&quot;File not found&quot;);<br>    } catch (IOException ex) {<br>      System.out.println(&quot;Error reading file&quot;);<br>    }<br>    <br>  }<br>}</pre><p>In the above example, FileNotFoundException is the child of IOException so its catch block has to be placed first. If tried to place IOException before FileNotFoundException the compiler would yell stating:</p><blockquote>error: exception FileNotFoundException has already been caught</blockquote><p>This is because, if we catch the general block first, then the more specific one would be omitted, which is not a good thing. Java encourages the exceptions to be made as specific as possible.</p><p>Good practice recommends catching the specific exception so that the program can handle different situations well. However, Java doesn&#39;t prohibit you from catching one base exception</p><h4><strong>What should be done inside of a catch block?</strong></h4><p>The best answer that could be given to this question is that&#39;s totally up to you, what and how you want your program to behave or execute when an error is thrown. The main purpose of the Catch block is to recover from the exception and continue execution and maybe notify the user about the error or revert back to the steps that were performed.</p><p>Typically [not limited], these are the few that can be present in the catch block:</p><ul><li>Printing out the exception details with System.err class methods and may be exiting from the method</li></ul><pre>System.err.println(exception);<br>System.err.println(exception.getMessage());</pre><ul><li>Print the full stack trace of the exception and exit the method</li></ul><pre>exception.printStackTrace()</pre><ul><li>Log the exceptions and then exit the method. One can use Java’s built-in logging mechanism or some third-party libraries available for doing the same.</li><li>Redirect the Users to an error page to give more information about what possibly might have gone wrong, in case the program was a web application.</li></ul><p>Happy Coding!❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f1558e46da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ComparisonValidator in Rails 7]]></title>
            <link>https://towardsdev.com/comparisonvalidator-in-rails-7-4f3dd6ded03c?source=rss-610ac2bee70b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3dd6ded03c</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[validator]]></category>
            <dc:creator><![CDATA[Spoorthi]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 08:03:28 GMT</pubDate>
            <atom:updated>2022-09-01T05:54:09.663Z</atom:updated>
            <content:encoded><![CDATA[<p>Comparison with another value, proc, or attribute.</p><p>ActiveRecord Validations are the most widely used and well-known functionality in Rails. It provides a complete validation framework to validate the state of an object before it is saved in the database. There are various ActiveRecord Validators like presence , uniqueness , length and so on…</p><p>If you had a scenario of validating an attribute with some value, in the older versions of Rails we had to write our own custom validations for the same. However, Rails 7 has now added ComparisonValidtor. This provides us with an easy way to validate a comparison between two comparable values. This validator requires an option[value, proc, or symbol] to be supplied for comparing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDGawBwnVZ5H055E65zJHQ.png" /></figure><p>Let&#39;s assume we have a model appointment where we have attributes start_date and end_date along with others.</p><h3><strong>Before</strong></h3><p>If you had to validate end_date attribute for any provided value or another attribute, we had to write the custom validation as shown below:</p><pre>class Appointment &lt; ApplicationRecord<br>  <br>  validates :start_date, presence: true<br>  validates :end_date, presence: true</pre><pre>  validate :end_date_is_after_start_date</pre><pre>  def end_date_is_after_start_date<br>    if end_date &lt; start_date<br>      errors.add(:end_date, &#39;can not be before the start date&#39;)<br>    end<br>  end<br>end</pre><h3>With Rails 7</h3><p>You don&#39;t need to use any custom validation and the ComparisonValidtor comes to the rescue. Let&#39;s rewrite using the comparison</p><pre>class Appointment &lt; ApplicationRecord<br>  validates :start_date, presence: true<br>  validates :end_date, presence: true</pre><pre>  validates :end_date, comparison: { greater_than: :start_date }<br>  # OR<br>  validates_comparison_of :end_date, greater_than: :start_date</pre><pre>end</pre><p>ComparisonValidator provides support to the below-mentioned options:</p><ul><li>greater_than : Specifies that the value must be greater than the supplied value. The default error message would be “must be greater than %{value}”.</li><li>greater_than_or_equal_to : Specifies that the value must be greater or equal to the supplied value. The default error message is “must be greater than or equal to %{value}”.</li><li>equals_to : Specifies that the value should be equal to the supplied value.</li><li>less_than : Specifies that the value should be less than the supplied value.</li><li>less_than_or_equal_to : This signifies that the value should be less than or equal to the supplied value.</li><li>other_than : Specifies that the value must be other than the supplied value. The default error message is “must be other than the %{value}”</li></ul><h3>Can we combine multiple Compare options?</h3><p>Yes, absolutely! We can combine multiple compare options.</p><p>Let&#39;s say that the end_date must be greater than the start_date and also, wants to validate that the end_date is not today.</p><pre>class Appointment &lt; ApplicationRecord<br>  validates :start_date, presence: true<br>  validates :end_date, presence: true<br>  validates_comparison_of :end_date, greater_than: :start_date,                 other_than: Date.today<br>end</pre><h3>Is ComparisonValidator only for date comparison?</h3><p>Absolutely no, we can compare numeric , date and as well as the string values with the ComparisonValidator.</p><pre>class Author &lt; ApplicationRecord<br>   validates_comparison_of :books_count, greater_than: 5<br>end</pre><p>ComparisonValidator is definitely a great addition to Rails 7. As it allows us to compare the data without being to write the custom validations and validates the data effortlessly.</p><p>Happy Coding!❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3dd6ded03c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/comparisonvalidator-in-rails-7-4f3dd6ded03c">ComparisonValidator in Rails 7</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Pattern in Ruby]]></title>
            <link>https://medium.com/@spoorthi0811/singleton-pattern-in-ruby-c8bd49dd9f49?source=rss-610ac2bee70b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8bd49dd9f49</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[singleton-in-ruby]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <dc:creator><![CDATA[Spoorthi]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 11:52:21 GMT</pubDate>
            <atom:updated>2022-06-13T11:52:21.200Z</atom:updated>
            <content:encoded><![CDATA[<p>About the singleton pattern, its pros and cons!!!</p><p>Have you ever come across a situation where you want to only create one instance of that class? The answer could be yes, no, or maybe.</p><p>Well….</p><p>That’s precisely what is called the Singleton Pattern. To define it, the Singleton pattern is a creational pattern that lets you ensure that your class has only one instance while providing global access to that instance.</p><p>A real-world example would be, that you want to create a database object to connect with your DB and access the DB, we mostly will have a single database object to do all this.</p><p>Here’s how you can make a class to create a single instance of it:</p><ul><li>Make your <strong><em>new</em></strong> method of the class Private</li><li>Define a class method name <strong><em>instance</em></strong> that returns the unique instance of the class.</li></ul><p>Below is an example of one of the ways to implement the same:</p><pre># The Singleton class defines the `instance` method that <br># lets clients access the unique singleton instance.<br>class SingletonExample<br>  @instance = new</pre><pre>  private_class_method :new</pre><pre># The static method that controls the access to the <br># singleton instance.<br>  def self.instance<br>    @instance<br>  end</pre><pre>end</pre><pre># Client Code<br>obj1 = SingletonExample.instance<br>obj2 = SingletonExample.instance</pre><pre>obj1 == obj2 <br># Returns true</pre><p>Because this is also a very popular design pattern, the <em>Ruby Standard Library</em> also has a module called <strong><em>Singleton</em></strong> that you can include in your class for implementing the same. Below are the other ways to implement the same</p><pre>require &#39;singleton&#39;</pre><pre>class SingleInstance<br>  include Singleton<br>end</pre><p>Now, when you try to create an instance of SingleInstance class using new, you would notice as below</p><pre><strong>NoMethodError (private method `new&#39; called for SingleInstance:Class)</strong></pre><p>And if you want to get the one and only instance of the SingleInstance class is by</p><pre>SingleInstance.instance</pre><pre># &lt;SingleInstance:0x00007f90ae66c470&gt;</pre><pre>SingleInstance.instance.object_id</pre><pre>#<strong>118560</strong></pre><p>You can tell it&#39;s only one object because the <em>object_id</em> never changes.</p><p><strong>Pros</strong></p><ul><li>You can be sure that your class has <em>only one instance</em>.</li><li>You gain <em>global access</em> to that instance.</li><li>The Singleton object is initialized only when it&#39;s <em>requested for the first time</em>.</li></ul><p><strong>Cons</strong></p><ul><li>Violates the <em>Single Responsibility Principle</em>. The pattern solves two problems at the time.</li><li>The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8bd49dd9f49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resque-Scheduler implementation in Rails App!]]></title>
            <link>https://medium.com/@spoorthi0811/resque-scheduler-implementation-in-rails-app-d9f43c4a24dc?source=rss-610ac2bee70b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f43c4a24dc</guid>
            <category><![CDATA[resque]]></category>
            <category><![CDATA[scheduler]]></category>
            <category><![CDATA[resque-scheduler]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails-6]]></category>
            <dc:creator><![CDATA[Spoorthi]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 10:32:47 GMT</pubDate>
            <atom:updated>2021-08-17T06:51:59.588Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will cover how one can add the functionality of the resque scheduler gem inside their Rails Application. Before, deep-diving into the implementation. Let&#39;s, first understand what is the Resque Scheduler?</p><p>Resque Scheduler is an extension to <a href="https://github.com/resque/resque">Resque</a> which adds support for queuing the items in the future. Resque scheduler is the best to schedule jobs that a recurring in nature if your application has the resque(Redis-backend Library) implemented which helps in creating the background jobs and placing these on multiple queues and process them later.</p><p>Job schedules are of two types: Scheduling(Recurring) and Delayed Jobs.</p><p>Here, I would like to explain much about the scheduling jobs with resque-scheduler.</p><p><strong>Installation:</strong></p><p>To install the gem:</p><pre>gem install resque-scheduler</pre><p>To use it in our application, add this in the</p><pre>gem &#39;resque-scheduler&#39;</pre><p>Once the gem is installed, create a file under initializers and name it as resque_scheduler.rb . This file is important for passing the schedule file to the resque_scheduler . Below is the snippet that should reside in the resque_scheduler.rb file.</p><pre>require &#39;resque&#39;<br>require &#39;resque-scheduler&#39;<br>require &#39;resque/scheduler/server&#39;</pre><pre>Resque.schedule = YAML.load_file(&#39;your_schedule_file.yml&#39;)</pre><p>The Schedule file is the list of Resque job classes with arguments and the scheduling frequency. The schedule is nothing but a hash, and it is stored in YAML format as shown below.</p><pre># Crontab documentation: https://www.geeksforgeeks.org/crontab-in-linux-with-examples/</pre><pre>scheduling_job_in_app:<br>  every: 30mins<br>  class: QueuingJob<br>  args:<br>  description: &#39;The description one wants to give for this job&#39;<br>  queue: queue_name</pre><p>We can also use cron instead of every option. For example, cron: ’30 6 * * * 1&#39; instead of every, this will run the job every Monday at 6:30.</p><p>At last, restart your server and start the worker and the scheduler to schedule the jobs</p><pre>QUEUE=* bundle exec rake resque:work<br>bundle exec rake resque:schedule</pre><p>Now the scheduler should be set up and should be working. To view all the available scheduled jobs, we can use the web interface of the resque scheduler here <a href="http://localhost:3000/resque/scheduler.">http://localhost:3000/resque/scheduler.</a> We should be able to see the list of jobs that were added in our schedule yaml file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f43c4a24dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>