<?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 Sandesh Bodke on Medium]]></title>
        <description><![CDATA[Stories by Sandesh Bodke on Medium]]></description>
        <link>https://medium.com/@sandeshbodake?source=rss-2fb346de55e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c_PfpNROhe4A1CSg56SZVw.png</url>
            <title>Stories by Sandesh Bodke on Medium</title>
            <link>https://medium.com/@sandeshbodake?source=rss-2fb346de55e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:48:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeshbodake/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[OTP-Based Authentication with Devise ]]></title>
            <link>https://sandeshbodake.medium.com/otp-based-authentication-with-devise-4265ced1b4ef?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4265ced1b4ef</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 05:49:35 GMT</pubDate>
            <atom:updated>2024-03-07T05:43:40.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>OTP-Based Authorization with Devise 🔐</h3><h3>What is OTP-Based Authorization?</h3><p>OTP-based authorization involves sending a unique one-time password to a user’s registered email or phone number. The user must enter this OTP to gain access to their account. This adds an extra layer of security beyond the traditional username and password combination, as the OTP is valid for a single use and expires quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tciEG_4YF0qxqEmNIM1XTg.png" /><figcaption>Image credits <a href="http://www.hoxhunt.com/">www.hoxhunt.com</a></figcaption></figure><h3>Setting Up Devise with Confirmable</h3><p>In this blog, our focus is solely on implementing email-based OTP verification. If you wish to implement mobile-based verification, you may need services like Twilio to manage that process. However, please note that such mobile-based verification is not covered in this blog.</p><p>Before implementing OTP-based authentication with Devise, ensure you have Devise integrated into your Ruby on Rails application. You can add Devise to your application by following the official documentation if you haven&#39;t already.</p><blockquote>Ensure that the Gemfile includes the <a href="https://github.com/heartcombo/devise">Devise</a> gem.</blockquote><p>Once <a href="https://github.com/heartcombo/devise">Devise</a> is set up, we can add Confirmable to our User model. Confirmable is a Devise module that allows users to confirm their email address or phone number. In our case, we will use it to confirm the OTP.</p><p>Here are the steps to add Confirmable to your User model:</p><ol><li><strong>Generate the Devise User Model:</strong></li></ol><pre>rails generate devise User</pre><p><strong>2. Add Confirmable to the User Model:</strong></p><p>Open the app/models/user.rb file and add the :confirmable option to your Devise configuration:</p><pre>class User &lt; ApplicationRecord<br>  devise :database_authenticatable, :registerable,<br>         :recoverable, :rememberable, :validatable,<br>         :lockable, :timeoutable, :confirmable<br>end</pre><p><strong>3. Migrate the Database:</strong></p><p>After adding Confirmable to your User model, generate and run a database migration to update your database schema:</p><pre>rails db:migrate</pre><blockquote>Ensure that the mailer is correctly configured by adding the necessary setup and configurations in the environment file.</blockquote><p><strong>4</strong>. <strong>Override Devise </strong><strong>send_confirmation_instructions method</strong></p><pre>class User<br>  devise :database_authenticatable, :registerable,<br>         :recoverable, :rememberable, :validatable,<br>         :lockable, :timeoutable, :confirmable<br><br>  OTP_LENGTH = 6 <br>  <br>  def send_confirmation_instructions<br>    token = SecureRandom.random_number(10**OTP_LENGTH).to_s.rjust(OTP_LENGTH, &quot;0&quot;)<br>    self.confirmation_token = token<br>    self.confirmation_sent_at = Time.now.utc<br>    save(validate: false)<br>    UserMailer.confirmation_instructions(self, self.confirmation_token).deliver_now<br>  end<br>end</pre><p>In summary, We’ve overridden send_confirmation_instructions to handle email confirmation. It generates a random OTP (6-digit number), associates it with the user, marks the timestamp when the confirmation instructions were sent, and sends a confirmation email to the user.</p><p>Additionally, it’s necessary to establish a distinct mailer responsible for dispatching confirmation instructions because we are customizing the functionality by overriding the default actions within Devise.</p><pre>def confirmation_instructions(user, otp)<br>  @user = user<br>  @otp = otp<br>  email = @user.email.presence || @user.unconfirmed_email<br>  mail(to: email, subject: &quot;Your Otp&quot;)<br>end</pre><p>Put your email view in app/views/user_mailer/users_instructions.html.erb file.</p><blockquote>Devise automatically dispatches confirmation instructions to the user’s email upon signing up.</blockquote><p>Let’s write some HTML code,</p><pre>&lt;div class=&quot;form-container mb-4&quot;&gt;<br>  &lt;p class=&quot;heading&quot;&gt;Confirm your email&lt;/p&gt;<br>  &lt;p class=&quot;content&quot;&gt;<br>    We have sent OTP to registered email, please confirm your email<br>  &lt;/p&gt;<br><br>  &lt;%= form_with model: [:invitations, @user], url: validate_otp_invitations_users_path, method: :post do |form| %&gt;<br>    &lt;%= form.hidden_field :id, value: @user.id %&gt;<br><br>    &lt;%= form.text_field :otp, placeholder: &quot;Type OTP&quot; %&gt;<br><br>    &lt;%= form.submit &quot;Validate OTP&quot; %&gt;<br>  &lt;% end %&gt;<br><br>  &lt;%= form_with model: [:invitations, @user], url: resend_otp_invitations_users_path, method: :post do |form| %&gt;<br>    &lt;%= form.hidden_field :id, value: @user.id %&gt;<br><br>    &lt;p class=&quot;text-center p-2 d-flex&quot;&gt;<br>      &lt;%= form.submit &quot;Resend OTP&quot;, style: &quot;color: #0073ff;background: none;&quot; %&gt;<br>    &lt;/p&gt;<br>  &lt;% end %&gt;<br>&lt;/div&gt;</pre><p>In the code above, we’ve incorporated two forms: one for validating the OTP and another for resending the OTP.</p><p>Similarly, we’ve to handle these form submissions on the backend side. Let’s write both functions now,</p><p><strong>5. Handle Devise confirmation on the controller side</strong></p><p>Let’s create confirmations_controller to validate enter OTP</p><pre>class InvitationsController &lt; ApplicationController<br>  OTP_EXPIRATION_TIME = 5.minutes.ago<br><br>  def validate_otp<br>    user = User.find_by_confirmation_token(permitted_params[:otp])<br><br>    if user &amp;&amp; user.confirmation_sent_at &gt;= OTP_EXPIRATION_TIME<br>      user.confirm<br>      user.update(confirmation_token: nil)<br>      redirect_to confirmations_success_invitations_users_path, notice: &quot;Email confirmed successfully!&quot;<br>    else<br>      flash[:alert] = &quot;Invalid or expired OTP. Please try again.&quot;<br>      redirect_to success_invitations_users_path(id: params[:user][:id])<br>    end<br>  end<br><br>  def resend_otp<br>    user = User.find_by(id: params[:user][:id])<br>    user.send_confirmation_instructions<br>    redirect_to success_invitations_users_path(id: params[:user][:id])<br>  end<br><br>  private<br><br>  def permitted_params<br>    params.require(:user).permit(:otp)<br>  end<br>end</pre><p>The function validate_otp locates the confirmation_token from the users&#39; table and uses it to confirm that specific user. It also incorporates an expiration time, typically set at 5 minutes in the above example.</p><p>On the other hand, the function resend_otp merely resends the confirmation instructions.</p><h3>Conclusion</h3><ul><li>This is a simple method to implement OTP-based authentication using Devise’s confirmable feature without relying on third-party libraries or extensive configurations.</li><li>For email-based OTP verification, if you intend to implement mobile-based verification, you may require services such as <a href="http://twilio.com/">Twilio</a> to handle the process.</li></ul><p>That’s all for implementation,</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>So, did you find this article helpful? If you did or like my other articles, feel free to buy me a coffee.</p><p>Thank you ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*NKmo68MdcIna0m3U.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4265ced1b4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍ Cooking Ruby Recipes  — Part 2]]></title>
            <link>https://sandeshbodake.medium.com/cooking-ruby-recipes-part-2-571a8394e131?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/571a8394e131</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Tue, 02 May 2023 14:14:22 GMT</pubDate>
            <atom:updated>2023-05-02T16:35:48.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>👨‍🍳 Cooking Ruby Recipes 🥣 — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N62__qmqlyt-iKOkYDxIcQ.png" /></figure><p>Hey developers 👋, welcome back to the second part of the series. In this article, I’ll walk you through more advanced recipes to cook your code tasty 😋 in Ruby.​ To be honest, you can find some concepts here that might be difficult to understand if you’re a beginner or new to Ruby. Still, I’ll try my best to explain it with some examples.​​</p><p>Before that, if you haven&#39;t read my previous blog here is the link of the blog:<br><a href="https://sandeshbodake.medium.com/cooking-ruby-recipes-part-1-1443b57a95da">https://sandeshbodake.medium.com/cooking-ruby-recipes-part-1-1443b57a95da</a></p><h4>⭐️ Classes and objects</h4><p>Ruby is Object Oriented. Many languages claim to be object-oriented, but most fall short in some area or another. When Ruby says it’s object-oriented, it really, really means it.</p><p>We have used lots of Ruby objects so far when we have done things like:</p><pre>&quot;Abracadabra&quot;.reverse.downcase</pre><p>Ruby has a class-based object model. This means we define classes, and then use them to stamp out as many objects as we like. Of course, this being Ruby, classes are objects and have methods in their own right, but we’ll get to this soon enough.</p><p>We define a class like so:</p><pre>class Pet<br>end</pre><p>Here we have defined a very simple class, called Pet. By convention, classes in Ruby always start with a capital letter. Now let&#39;s create a pet:</p><pre>flopsy = Pet.new</pre><p>This is great, we have created a new instance of the Pet class. Flopsy is an instance of Pet.</p><p>Note that all objects get a new method for free. This they inherit from the Object superclass. More on inheritance in a bit.</p><h4>⭐️ Monkey Patching for Great Justice 🐒</h4><p>Because Ruby is an interpreted language objects are open and can be modified at runtime. Classes can be reopened at any time.</p><p>As we’ve mentioned before existing classes can be extended. This includes built-in Ruby classes. This is a feature that can be used both for good and for evil:</p><p>For good:</p><pre>class String<br>  def put_times(n)<br>    for i in (1..n)<br>      puts self<br>    end<br>  end<br>end<br><br>&quot;Expecto patronum 🪄&quot;.put_times 5</pre><p>For Evil 🙈</p><pre>class Fixnum<br>  def *(num)<br>    self + num<br>  end<br>end<br>puts 5*4<br>  =&gt; 9</pre><h4>⭐️ Operator Overloading</h4><p>Did I mention that in Ruby everything is an object? This extends to operators, such as +, -, * and /. Operators in Ruby are actually methods, and we can define and redefine them, like so:</p><pre>class Car<br>    attr_accessor:name, :color<br> <br>    def initialize(name, color)<br>        @name = name<br>        @color = color<br>    end<br>    def +(obj)<br>        return Car.new(&quot;#{self.name}#{obj.name}&quot;,<br>                  &quot;#{self.color}#{obj.color}&quot;)<br>    end<br>end<br><br>a = Car.new(&quot;Mercedes&quot;, &quot;Red&quot;)<br>b = Car.new(&quot;Audi&quot;, &quot;Silver&quot;)<br>puts (a+b).inspect<br><br>=&gt; #&lt;Car:0x000000020a0620 @name=&quot;MercedesAudi&quot;, @color=&quot;RedSilver&quot;&gt;</pre><p>Here we have defined a plus method that receives another car object. This simply creates a new car with combined name.</p><p><strong>⭐️ Static Methods</strong></p><p>In Ruby, all methods exist within a class. When you create an object, the methods for that object exist within it’s class. Methods can be public, private or protected, but there is no concept of a static method. Instead, we have singleton classes, commonly referred to as eigenclasses.</p><p><strong>Singleton</strong></p><p>Instead, Ruby lets us define an unnamed singleton class that sits in the inheritance tree directly above any object. Lets do this now and create a static method.</p><pre>class Kitten<br>  class &lt;&lt; Kitten<br>    def max_size<br>      8<br>    end<br>  end<br>end</pre><p>The class « Kitten syntax opens up the eigenclass and pops the max_size method within it. We can then access it like this</p><pre>puts Kitten.max_size<br><br>=&gt; 8</pre><blockquote>Shorthand: We use the class « self syntax to explicitly open an object’s eigenclass. We can accomplish the same thing using the shorthand syntax: `Kitten.max_size`</blockquote><p>⭐️ <strong>Modules (Mixins)</strong></p><p>Modules can be used to add reusable functionality to a class. They are sometimes known as Mixins. A module consists of a whole bunch of methods. By importing it into a class, we gain access to all those methods. This is a handy way to get around the restrictions of single object inheritance, since we may import as many modules as we like.</p><p>Lets teach flopsy how to make an omelette. Then she will be able to help out in the kitchen. It would be nice if our omelette could accept a few options, so lets allow that too.</p><pre>module CookOmelette<br>  def cook_omelette(args={})<br>    number_of_eggs = args[:number_of_eggs] || args[:eggs] || 2<br>    cheese = args[:cheese] ? &quot;cheese&quot; : nil<br>    ham = args[:ham] ? &quot;ham&quot; : nil<br>    mushrooms = args[:mushrooms] ? &quot;mushrooms&quot; : nil<br>    ingredients = [cheese,ham,mushrooms].delete_if{ |ingredient| ingredient.nil? }<br>    ingredients = ingredients.join(&quot; &amp; &quot;)<br>    &quot;#{ ingredients } omelette with #{number_of_eggs} eggs&quot;.strip<br>  end<br>end</pre><p>Now include the mixin in the Pet class.</p><pre>class Pet<br>  include CookOmelette<br>end</pre><p>All our pets can now make delicious omelettes. Observe:</p><pre>mopsy.cook_omelette<br>  =&gt; &quot;omelette with 2 eggs&quot;<br>mopsy.cook_omelette :ham =&gt; true, :cheese =&gt; true, :eggs =&gt; 4<br>  =&gt; &quot;cheese &amp; ham omelette with 4 eggs&quot;</pre><p>⭐️ <strong>Extend vs. Include</strong></p><p>Include and Extend allow us to take methods from a module and add them to an object. They work slightly differently from each other though. Let’s take a look…</p><pre> module IndoorPet<br>    def can_be_housebroken?<br>       true<br>    end<br> end<br><br>class Animal <br>end <br><br>class Dog &lt; Animal <br>   include IndoorPet<br>end<br><br>roger = Dog.new(&quot;Roger&quot;)<br><br>roger.can_be_housebroken?<br>=&gt; true <br><br>Dog.can_be_housebroken?<br>=&gt; NoMethodError: undefined method `can_be_housebroken?&#39; for Dog:Class </pre><p>Include adds instance methods to a class, Include takes a more traditional approach. If you include a module in a class, the methods in the module will be added as instance methods, and will be available to all instances of that class.</p><pre>module IndoorPet<br>    def can_be_housebroken?<br>       true<br>    end<br> end<br><br>class Animal <br>end <br><br>class Dog &lt; Animal <br>   extend IndoorPet<br>end<br><br>roger = Dog.new(&quot;Roger&quot;)<br><br>roger.can_be_housebroken?<br>=&gt; &quot;NoMethodError: undefined method `can_be_housebroken?&#39; for  #&lt;Rabbit:0x00007fa84389c748&gt;&quot;<br><br>Rabbit.can_be_housebroken?<br>=&gt; true</pre><p>When you extend a module, ruby will provide the module’s methods to the class as class methods. However, unlike with include, when you extend a module, Ruby will not insert the module into the class&#39;s ancestry chain.</p><p>⭐️ <strong>Exception Handling</strong></p><h4>Raising an Exception</h4><p>Raising an exception in Ruby is trivially easy. We use raise.</p><pre>raise &quot;A Error Occurred&quot;</pre><p><strong>Raising a Specific Exception<br></strong>We can also raise a specific type of exception:</p><pre>value = &quot;Hi there&quot;<br>raise TypeError, &#39;Expected a Fixnum&#39; if value.class != Fixnum</pre><p><strong>Rescue<br></strong>We can rescue exceptions easily. Put the code that might raise an exception in a begin, rescue end block. If an exception occurs, control will be passed to the rescue section.</p><pre>begin<br>  raise &quot;A problem occurred&quot;<br>rescue =&gt; e<br>  puts &quot;Something bad happened&quot;<br>  puts e.message<br>end</pre><h4>⭐️ Send</h4><p>Send allows you to call a method identified by a symbol.</p><p>My app has classes for people and events. Each class has different attributes.</p><pre>class Calculator<br>  def add(a, b)<br>    a + b<br>  end<br><br>  def subtract(a, b)<br>    a - b<br>  end<br>end<br><br>calculator = Calculator.new<br>puts calculator.send(:add, 2, 3)       # output: 5<br>puts calculator.send(&quot;subtract&quot;, 10, 5)  # output: 5</pre><p>Using the send method allows us to invoke methods dynamically, which can be useful in situations where the method name or arguments are not known until runtime. However, it’s important to use the send method with caution, as it can bypass method visibility and potentially allow access to private methods that should not be accessible.</p><p>⭐️ <strong>Define method</strong></p><p>We use define method to create a method on the fly given a string as a name.</p><pre>class A<br>  define_method :c do<br>    puts &quot;Hey!&quot;<br>  end<br>end<br><br>A.new.b<br>A.new.c(1,2)</pre><p>⭐️ <strong>Method Missing</strong></p><p>Trying to call a method that doesn’t exist in Ruby is an exception rather than a language error. We can catch it, or we can simply implement a method_missing function which will be called when no matching method is found.</p><pre>class A<br>  def ary<br>    [:a,:b,:c]<br>  end<br><br>  def method_missing(method, *args)<br>    puts ary.include?(method)<br>  end<br>end<br><br>a = A.new<br>a.b<br># =&gt; true<br>a.d<br># =&gt; false</pre><p>⭐️ <strong>Instance Eval</strong></p><p>instance_eval method is a way to execute a block of code within the context of a particular object, as if the code was defined within the object’s instance scope. Here’s an example:</p><pre>class MyClass<br>  def initialize(value)<br>    @value = value<br>  end<br>end<br><br>obj = MyClass.new(42)<br><br>obj.instance_eval do<br>  puts &quot;The value of @value is #{@value}&quot;<br>end<br><br>=&gt; &quot;The value of @value is 42&quot;</pre><p>We then call the instance_eval method on the obj instance, passing in a block of code that uses the instance variable @value within the context of the obj instance. The instance_eval method executes the block of code as if it was defined within the instance scope of the obj instance, allowing us to access and modify the instance variables of obj.</p><p>That’s all for the Second and last part of <em>Cooking Ruby Recipes,</em></p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p><strong>So, did you find this article helpful?</strong> If you did or like my other articles, feel free to buy me a coffee.</p><p>Thank you ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*MUEnIfhx80JcU3t9.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=571a8394e131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍ Cooking Ruby Recipes  — Part 1]]></title>
            <link>https://sandeshbodake.medium.com/cooking-ruby-recipes-part-1-1443b57a95da?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1443b57a95da</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 04:51:58 GMT</pubDate>
            <atom:updated>2023-04-22T04:51:58.178Z</atom:updated>
            <content:encoded><![CDATA[<h3>👨‍🍳 Cooking Ruby Recipes 🥣 — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcUezyEUuPrM1H5mZtVtSQ.png" /></figure><p>Hello developers 👋,​ In this article, I’ll walk you through some basic recipes to cook your code tasty 😋 in Ruby. You’re here in the first part of this series. I’ll present some of my views to you and hope you’ll like them. This article is basically for people who are a beginner in Ruby, want to start development in Ruby or folks who are coming from other programming languages.</p><p>I have been working with Ruby for the last 4 years, Ruby is a really easy and developer-friendly programming language that is expressive and concise, allowing you to express your ideas with less code. This helps in reducing the amount of boilerplate code in your project and there are so many features of Ruby which can’t be explained in a single article 😄.​ That’s enough introduction I guess and now I think we should start talking about Ruby 🔸.</p><h4><strong>⭐️ Integers (Fixnums)</strong></h4><p>Everything in Ruby is an object including integers, or Fixnums as they are known in Ruby. Integers, therefore, have methods.</p><pre>x = 1<br>x.to_s<br>  =&gt; &#39;1&#39;</pre><ul><li>Basic Maths</li></ul><p>You can do all the maths you would like with integers. It all works as you would expect, You also have the common maths shortcuts you find in other languages like *= , += etc</p><pre>3 * 4<br>  =&gt; 12<br><br>x *= 2<br>  =&gt; 14</pre><p>Use ** for exponentiation should you feel that way inclined:</p><pre>2 ** 2<br>  =&gt; 4<br>2 ** 3<br>  =&gt; 8<br>2 ** 4<br>  =&gt; 16</pre><h4>⭐️ Strings</h4><p>Ruby has an unusually rich and detailed String manipulation toolkit. String creation is similar to other languages</p><pre>string = &quot;Hello Ruby&quot;<br><br>puts string<br>  =&gt; Hello Ruby</pre><p><em>Note: You are free to use single or double quotes around your string.</em></p><p>Strings are real objects and have methods, as Everything in Ruby is an Object</p><pre>s = &quot;Hello Ruby&quot;<br>puts s.reverse<br>  =&gt; &quot;ybuR olleH&quot;</pre><p>Ruby also has the support for String interpolation, using double quotes you can embed variables</p><pre>name = &quot;Derrick&quot;<br>puts &quot;Hello, my name is #{name}&quot;<br>  =&gt; &quot;Hello, my name us Derrick&quot; </pre><p>⭐️ <strong>Functions</strong></p><p>Functions are declared using the def keyword</p><pre>def greeting<br>  puts &quot;Hello Ruby&quot;<br>end<br><br>greeting()<br>  =&gt; Hello Ruby</pre><p>Functions can accept parameters as you would expect. We pass them like this</p><pre>def greet(name)<br>  puts &quot;hello #{name}&quot;<br>end<br><br>greet(&quot;dave&quot;)<br>=&gt; &quot;hello dave&quot;<br><br>greet &quot;dave&quot;<br>=&gt; &quot;hello dave&quot;</pre><p>Note: while calling functions braces are optional you can simply send a parameter like the below to call a function</p><p>We can set the default value of an argument, so if no value is passed, our function will still work:</p><pre>def get_greeting_for(name=&quot;anonymous&quot;)<br>  &quot;hello #{name}&quot;<br>end<br><br>puts get_greeting_for<br>=&gt; &quot;hello anonymous&quot;</pre><p><em>Note: you don’t need to write </em><em>return statement at the function end</em></p><p>⭐️<strong> Flow control</strong></p><p>Ruby loves it when you tell it what to do.</p><ul><li>if/elsif/else/end</li></ul><p>If statements are present. They work as you’d expect. Notice that no braces are required.</p><pre>bacon = true<br>fish = false<br>if fish<br>  puts &#39;I like fish&#39;<br>elsif bacon<br>  puts &#39;I like bacon&#39;<br>else<br>  puts &quot;I don&#39;t like fish or bacon&quot;<br>end<br>  =&gt; &#39;I like bacon&#39;</pre><ul><li>unless</li></ul><p>The unless the keyword is the opposite of the if keyword. It’s equivalent to !if (not if). It can make your code more readable.</p><pre>bacon = false<br>unless bacon<br>  puts &#39;fish&#39;<br>else  puts &#39;bacon&#39;<br>end<br>  =&gt; &quot;fish&quot;</pre><p>using unless code becomes more readable</p><ul><li>ternary operator</li></ul><p>Like most languages, Ruby includes a ternary operator. It works as you’d expect. If the first portion evaluates to true the first result is given, otherwise the second result is given:</p><pre>bacon = true<br>puts bacon ? &#39;bacon&#39; : &#39;fish&#39;<br>  =&gt; &quot;bacon</pre><ul><li>nil</li></ul><p>A variable is nil if it has been declared, but holds no value. Nil exists as a type and has methods. For example:</p><pre>a = nil<br>a.to_s<br>  =&gt; &quot;&quot;<br>a.nil?<br>  =&gt; true</pre><p>Nil is a very useful thing to be able to return. It means “no value”.</p><ul><li>Undefined</li></ul><p>A variable is undefined if it has not been declared. You can test for this using the defined? operator.</p><pre>a = 1<br>defined? a<br>  =&gt; &quot;local-variable&quot;<br>defined? b<br>  =&gt; nil</pre><ul><li>Boolean Algebra</li></ul><p>You can do all the standard things using Boolean algebra.</p><pre>true &amp;&amp; true<br>  =&gt; true<br>true || false<br>  =&gt; true<br>12 == 12<br>  =&gt; true</pre><ul><li>Special uses for logical OR ||</li></ul><pre>name = nil<br>user_name = name || &quot;Anonymous Coward&quot;<br>puts user_name<br><br>=&gt; &quot;Anonymous Coward&quot;</pre><p>That’s all about flow control, hope you’ll still be with me 😃, Let’s move to the blocks now</p><p>⭐️ <strong>Blocks</strong></p><p>Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do/end statement or between brackets {}, and they can have multiple arguments.</p><p>The argument names are defined between two pipe |characters.</p><p>If you have used each before, then you have used blocks!</p><pre>[1, 2, 3].each { |num| puts num }<br><br>=&gt; 1<br>2<br>3</pre><p>A Ruby block is useful because it allows you to save a bit of logic (code) &amp; use it later.</p><p>This could be something like writing data to a file, comparing if one element is equal to another, or even printing an error message.</p><ul><li>Yield</li></ul><p>Yield is a Ruby keyword that calls a block when you use it. It’s how methods USE blocks! When you use the yield keyword, the code inside the block will run &amp; do its work. Just like when you call a regular Ruby method.</p><pre>def print_once<br>  yield<br>end<br><br>print_once { puts &quot;Block is being run&quot; }<br><br>=&gt; &quot;Block is being run&quot;</pre><p>This runs any block passed to print_once, as a result, “Block is being run” will be printed on the screen.</p><ul><li>Creating your own block function</li></ul><p>Ruby provides really nice way to abstract your repeated code into blocks let’s take the below example:</p><pre><br>def error_handler<br>  yield<br>rescue StandardError =&gt; e<br>   Rails.logger.error e.backtrace<br>end</pre><p>We’ve declared simple error_handler block, now see the below snippet:</p><pre>error_handler do<br>  puts &quot;Hello World&quot;<br>end<br><br>=&gt; &quot;Hello World&quot;</pre><p>we can write our business logic inside error_handler block and exceptions are handled separately this will increase the code readability and code look clean</p><p>⭐️ <strong>Array</strong></p><p>In Ruby Create an array using square brackets like so:</p><pre>cakes = [&quot;florentine&quot;, &quot;lemon drizzle&quot;, &quot;jaffa&quot;]</pre><p>Access an array using square brackets:</p><pre>cakes[0]<br>  =&gt; &quot;florentine&quot;</pre><ul><li>Polymorphic</li></ul><p>As you might expect from Ruby, arrays can hold any type of element. This is allowed:</p><pre>[&quot;hello&quot;, 1, 0.5, false]</pre><ul><li>Manipulating arrays</li></ul><p>Arrays can be manipulated in a huge variety of ways For example:</p><pre>[1,2,3] + [4,5,6]<br>  =&gt; [1, 2, 3, 4, 5, 6]<br><br>[1,2,3] - [1,3]<br>  =&gt; [2]<br><br>[1,2,3] &lt;&lt; 4<br>  =&gt; [1, 2, 3, 4]<br><br>[1,2,3] * 2<br>  =&gt; [1, 2, 3, 1, 2, 3]</pre><p>There are also a raft of array methods we can use, such as:</p><pre>[1,2,3].reverse<br>  =&gt; [3, 2, 1]<br><br>[1,2,3].include? 2<br>  =&gt; true</pre><p>You might notice here that this method name has a question mark in it? This is a Ruby convention. Methods with a question mark return true or false.</p><pre>[4,9,1].sort<br>  =&gt; [1, 4, 9]</pre><ul><li>Array splitting</li></ul><p>Parallel assignment works when pulling values out of an array.</p><pre>array_of_numbers = [1,2,3,4]<br>a,b = array_of_numbers<br>a<br>  =&gt; 1<br>b<br>  =&gt; 2</pre><p>We can also pull the first element, and return the rest of the array should we wish to:</p><pre>arr = [1,2,3]<br>a,*arr = arr<br>a<br>  =&gt; 1<br>arr<br>  =&gt; [2, 3]</pre><ul><li>Range</li></ul><p>Ranges are useful objects that can be used to represent a sequence. Ranges are defined using the .. or … syntax.</p><p>For example:</p><pre>(1..10).to_a<br>  =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br><br>1...10<br>  =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9]<br><br>&#39;a&#39;..&#39;f&#39;<br>  =&gt; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;]</pre><p>⭐️ Hashes and symbols</p><ul><li>Symbols</li></ul><p>Symbols often seem like magic runes to Ruby newcomers. In fact, they’re just little objects that have some special features and syntax surrounding them to make them a little easier to use and a little lighter on the computer&#39;s memory.</p><pre>:price<br>:length<br>:outrageousness<br>&quot;My Price&quot;.to_sym</pre><p>Features of Symbols:</p><ul><li>Symbols are tiny little objects</li><li>Symbols don’t have a value, they are placeholders, not variables.</li><li>There can only ever be one symbol with a particular name, this is managed by Ruby. Because of this, they are not processor or memory intensive.</li><li>Symbols can potentially represent a memory leak if you create a lot of them.</li></ul><blockquote>A symbol will only exist once in memory, no matter how many times it is used. If for example, you create two symbols in different places both called :name for example, only one object would be created. This object would persist for as long as the Ruby interpreter was running.</blockquote><ul><li>Hashes</li></ul><p>Hashes are objects that associate lists of arbitrary objects with each other. For example:</p><pre>animals = Hash.new<br>animals[:tall] = &quot;giraffe&quot;<br>animals[:minute] = &quot;kitten&quot;<br>puts animals.inspect<br>=&gt; {:tall=&gt;&quot;giraffe&quot;, :minute=&gt;&quot;kitten&quot;}</pre><ul><li>Hash Assignment Shorthand</li></ul><pre>animals = {:tall =&gt; &quot;giraffe&quot;, :minute =&gt; &quot;kitten&quot;}<br>puts animals[:minute]<br>=&gt; kitten</pre><p>⭐️ RSpec</p><p>There are many test harnesses for Ruby. RSpec is the most popular.</p><p>Install RSpec using:</p><pre>gem install rspec</pre><p>RSpec is very easy to set up. Create a folder called spec in the same directory as your code. This is where your specs will live.</p><p>In the spec, folder create a file called test_spec.rb Place the following code in it:</p><pre>describe &quot;an example spec&quot; do<br>  it &quot;passes&quot; do<br>    expect(true).to be(true)<br>  end<br>end</pre><p>run your specs with:</p><pre>rspec spec/*</pre><p>You should see a message like this, telling you the specs have passed:</p><pre>Finished in 0.00105 seconds (files took 0.11919 seconds to load)<br>1 example, 0 failures</pre><p>Let’s try RSpec with some actual code,</p><p>Let’s write an alarm clock function to wake us up in the morning. When we call it it’s going to give us a message: “Beep beep beep”. This will help us wake up.</p><pre>def wake_me_up<br>  &quot;Beep beep beep&quot;<br>end</pre><p>Save this in a file called clock.rb</p><p>Now let’s write a spec for it. First, we need to import our clock, then we call the code, and then we say what the result should be:</p><pre>require_relative &#39;../clock&#39;<br>describe &quot;alarm clock&quot; do<br>  it &quot;beeps&quot; do<br>    expect(wake_me_up).to eq(&#39;Beep beep beep&#39;)<br>  end<br>end</pre><p><em>Note: </em><em>require_relative is a way to import files</em></p><h3>Test First Approach</h3><p>This is all well and good, but what about Test Driven Development (TDD). In this methodology, we write the test first, watch it fail, and then write code to make it pass.</p><p>Some days I feel sleepy and I’d like to be woken with more force. I’d like my alarm clock to accept an optional parameter and wake me up more strongly.</p><p>First, we write the spec</p><pre>require_relative &#39;../clock&#39;<br>describe &quot;alarm clock&quot; do<br>  it &quot;beeps&quot; do<br>    expect(wake_me_up).to eq(&#39;Beep beep beep&#39;)<br>  end<br>  it &quot;beeps louder&quot; do<br>    expect(wake_me_up(6)).to eq(&#39;Beep beep beep beep beep beep&#39;)<br>  end<br>end</pre><p>Now we run the spec and we see red:</p><pre>1) alarm clock beeps<br>   Failure/Error: expect(wake_me_up(6)).to eq(&#39;Beep beep beep beep beep beep&#39;)<br>   ArgumentError:<br>     wrong number of arguments (1 for 0)<br>   # ./clock.rb:5:in `wake_me_up&#39;<br>   # ./spec/clock_spec.rb:16:in `block (2 levels) in &lt;top (required)&gt;&#39;<br>Finished in 0.00161 seconds (files took 0.14819 seconds to load)<br>2 examples, 1 failure<br>Failed examples:<br>rspec ./spec/clock_spec.rb:15 # alarm clock beeps</pre><p>Notice it’s telling us exactly what and where the problem is. Let’s write code to make our test pass.</p><pre>def wake_me_up(i = 3)<br>  (&quot;beep &quot; * i).strip.capitalize<br>end</pre><p>Run the test again and success, we have a passing test.</p><p>For more TDD-related stuff check my blog <a href="https://medium.com/scalereal/test-driven-development-tdd-with-ruby-5a3a1a7421fc?source=user_profile---------7----------------------------">here</a></p><p>That’s all for the first part of <em>Cooking Ruby Recipes, </em>In the next part we’ll be covering class, inheritance etc</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p><strong>So, did you find this article helpful?</strong> If you did or like my other articles, feel free to buy me a coffee.</p><p>Thank you ;)</p><figure><a href="https://www.buymeacoffee.com/sandeshb"><img alt="https://www.buymeacoffee.com/sandeshb" src="https://cdn-images-1.medium.com/max/170/0*6qxbRZcYTayzHnOt.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1443b57a95da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design patterns with Kotlin Part 2]]></title>
            <link>https://medium.com/scalereal/design-patterns-with-kotlin-part-2-319b5d4faa66?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/319b5d4faa66</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 07:28:52 GMT</pubDate>
            <atom:updated>2022-08-18T05:24:38.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xxOt381Vyqg7-oC3" /><figcaption>Photo by <a href="https://unsplash.com/@ugmonk?utm_source=medium&amp;utm_medium=referral">Jeff Sheldon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Structural Design Pattern?</h3><p>Structural design patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient.</p><blockquote><em>In the last blog, we explore creational design patterns in Kotlin, if you haven&#39;t read it check the below link </em>👇</blockquote><p><a href="https://medium.com/scalereal/design-patterns-with-kotlin-part-1-dcd230d14c6e">Design patterns with Kotlin Part 1</a></p><p>Let’s start exploring <strong>structural patterns,</strong></p><h4><strong>1. Adapter Pattern</strong></h4><p><strong>Adapter</strong> design pattern allows objects with incompatible interfaces to collaborate.</p><p><strong>Problem:</strong></p><p>Imagine that you’re creating a stock market monitoring app. The app downloads the stock data from multiple sources in XML format and then displays nice-looking charts and diagrams for the user.</p><p>At some point, you decide to improve the app by integrating a smart 3rd-party analytics library. But there’s a catch: the analytics library only works with data in JSON format</p><p><strong>Solution:</strong></p><p>You can create an <em>adapter</em>. This is a special object that converts the interface of one object so that another object can understand it.</p><p>An adapter wraps one of the objects to hide the complexity of conversion happening behind the scenes. The wrapped object isn’t even aware of the adapter. For example, you can wrap an object that operates in meters and kilometres with an adapter that converts all of the data to imperial units such as feet and miles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3hI0nvEOhP0gTibP7JJYA.jpeg" /><figcaption><strong>Adapter Pattern 1.0</strong></figcaption></figure><p>This implementation uses the object composition principle: the adapter implements the interface of one object and wraps the other.</p><p>Let’s jump on code implementation,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2d19c053acc8a273554f2969c2458b3/href">https://medium.com/media/a2d19c053acc8a273554f2969c2458b3/href</a></iframe><p><strong>Pros:</strong></p><ul><li><em>Single Responsibility Principle</em>. You can separate the interface or data conversion code from the primary business logic of the program.</li><li><em>Open/Closed Principle</em>. You can introduce new types of adapters into the program without breaking the existing client code, as long as they work with the adapters through the client interface</li></ul><p><strong>Cons:</strong></p><ul><li>The overall complexity of the code increases because you need to introduce a set of new interfaces and classes. Sometimes it’s simpler just to change the service class so that it matches the rest of your code.</li></ul><p><strong>2. Decorator Pattern</strong></p><p><strong>Decorator</strong> design pattern that lets you attach new behaviours to objects by placing these objects inside special wrapper objects that contain the behaviours.</p><p>The <strong>Decorator pattern allows us to add behaviour either statically or dynamically by providing an enhanced interface to the original object</strong>. The static approach can be achieved using inheritance, overriding all the methods of the main class and adding the extra functionality that we want.</p><p>As an alternative to inheritance and to reduce the overhead of subclassing, we can use composition and delegation to add additional behaviour dynamically. In this article, we’ll follow these techniques for the implementation of this pattern.</p><p><strong>Problem:</strong></p><p>Suppose you’re working on a simple API where you have to read/write data for this you’ll create simple functions but what if tomorrow you want to do extra operations like encryption? you need to so many changes in functions and this will also break the <strong>Single-responsibility principle</strong></p><p><strong>Solution:</strong></p><p>The solution to the above problem is overriding all the methods of the main class and adding extra functionality i.e encryption/decryption to that respective action</p><p>Let’s jump into the code to understand it,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwgfC_jDaJeK5NkNeYGJAw.jpeg" /><figcaption><strong>Decorator Pattern 1.0</strong></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9366636c8a8c2b8ae1b0cdc388d28a10/href">https://medium.com/media/9366636c8a8c2b8ae1b0cdc388d28a10/href</a></iframe><p>See the above example we simply added EncryptionDecorator and all the necessary logic related to Encryption is in this class itself.</p><p><strong>Pros:</strong></p><ul><li>You can extend an object’s behaviour without making a new subclass.</li><li>You can add or remove responsibilities from an object at runtime.</li><li><em>Single Responsibility Principle</em>. You can divide a monolithic class that implements many possible variants of behaviour into several smaller classes.</li></ul><p><strong>Cons:</strong></p><ul><li>It’s hard to implement a decorator in such a way that its behaviour doesn’t depend on the order in the decorators stack.</li></ul><p><strong>3. Facade</strong></p><p><strong>Facade</strong> pattern provides a simplified interface to a library, a framework, or any other complex set of classes.</p><p><strong>Problem:</strong></p><p>Imagine that you must make your code work with a broad set of objects that belong to a sophisticated library or framework. Ordinarily, you’d need to initialize all of those objects, keep track of dependencies, execute methods in the correct order, and so on.</p><p>As a result, the business logic of your classes would become tightly coupled to the implementation details of 3rd-party classes, making it hard to comprehend and maintain.</p><p><strong>Solution:</strong></p><p>A facade is a class that provides a simple interface to a complex subsystem which contains lots of moving parts. A facade might provide limited functionality in comparison to working with the subsystem directly. However, it includes only those features that clients really care about.</p><p>Having a facade is handy when you need to integrate your app with a sophisticated library that has dozens of features, but you just need a tiny bit of its functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToLTj9rWXLe5sbvuwPcy2Q.jpeg" /><figcaption><strong>Facade 1.0</strong></figcaption></figure><p>Instead of making your code work with dozens of the framework classes directly, you create a facade class which encapsulates that functionality and hides it from the rest of the code. This structure also helps you to minimize the effort of upgrading to future versions of the framework or replacing it with another one. The only thing you’d need to change in your app would be the implementation of the facade’s methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a582c4b2d2c998bd4929ba61d12bcb46/href">https://medium.com/media/a582c4b2d2c998bd4929ba61d12bcb46/href</a></iframe><p><strong>Pros:</strong></p><ul><li>You can isolate your code from the complexity of a subsystem.</li></ul><p><strong>Cons:</strong></p><ul><li>Tightly coupled classes</li></ul><p><strong>4. Proxy Pattern</strong></p><p><strong>Proxy</strong> design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.</p><p><strong>Problem:</strong></p><p>Suppose you have a massive object that consumes a vast amount of system resources. You need it from time to time, but not always. In an ideal world, we’d want to put this code directly into our object’s class, but that isn’t always possible. For instance, the class may be part of a closed 3rd-party library.</p><p><strong>Solution:</strong></p><p>The Proxy pattern suggests that you create a new proxy class with the same interface as an original service object. Then you update your app so that it passes the proxy object to all of the original object’s clients. Upon receiving a request from a client, the proxy creates a real service object and delegates all the work to it.</p><p>In the Proxy Pattern, <strong>a client does not directly talk to the original object, it delegates its calls to the proxy object which calls the methods of the original object.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1acaa9df7a7fe485e754b2e5ef0c3a/href">https://medium.com/media/5f1acaa9df7a7fe485e754b2e5ef0c3a/href</a></iframe><p><strong>Pros:</strong></p><ul><li>You can control the service object without clients knowing about it.</li><li><em>Open/Closed Principle</em>. You can introduce new proxies without changing the service or clients.</li></ul><p><strong>Cons:</strong></p><ul><li>The code may become more complicated since you need to introduce a lot of new classes.</li></ul><p><strong>5. Bridge Pattern</strong></p><p>The bridge pattern allows the Abstraction and the Implementation to be developed independently and the client code can access only the Abstraction part without being concerned about the Implementation part.</p><p><strong>Problem:</strong></p><p>When there are inheritance hierarchies creating concrete implementation, you lose flexibility because of interdependence.</p><p><strong>Solution:</strong></p><p>Decouple implementation from the interface and hiding implementation details from the client is the essence of the bridge design pattern</p><p>Check the below code snippet 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a2edc1200245571380c26eff653b841/href">https://medium.com/media/0a2edc1200245571380c26eff653b841/href</a></iframe><p><strong>Pros:</strong></p><ul><li>Bridge pattern allows independent variation between two abstract and implementor systems.</li><li>It avoids the client code binding to a certain implementation.</li><li>Abstraction and implementation can be clearly separated allowing the easy future extension.</li></ul><p><strong>Cons:</strong></p><ul><li>You might make the code more complicated by applying the pattern to a highly cohesive class.</li></ul><p>In this blog, we covered structural design patterns with their example in Kotlin. For more examples check out our Github Repository <a href="https://github.com/scalereal/design-patterns">here</a>. In the upcoming blogs, we’ll be exploring <strong>Behavioural </strong>Patterns.</p><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p><strong>So, did you find this article helpful?</strong> If you did or like my other articles, feel free to buy me a coffee.</p><p>Thank you ;)</p><figure><a href="https://www.buymeacoffee.com/sandeshb"><img alt="https://www.buymeacoffee.com/sandeshb" src="https://cdn-images-1.medium.com/max/170/0*6qxbRZcYTayzHnOt.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=319b5d4faa66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/design-patterns-with-kotlin-part-2-319b5d4faa66">Design patterns with Kotlin Part 2</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design patterns with Kotlin Part 1]]></title>
            <link>https://medium.com/scalereal/design-patterns-with-kotlin-part-1-dcd230d14c6e?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcd230d14c6e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Mon, 09 May 2022 12:24:11 GMT</pubDate>
            <atom:updated>2022-05-09T12:24:11.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Design patterns are typical solutions to common problems in software design. Each pattern is a blueprint that you can customize to solve a particular design problem in your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XOkkzUOTSU91VJnn" /><figcaption>Photo by <a href="https://unsplash.com/@chriskaridis?utm_source=medium&amp;utm_medium=referral">Chris Karidis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is a Design pattern?</strong></h3><p>In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is <strong>a description or template for how to solve a problem that can be used in many different situations</strong>.</p><p>Patterns are often confused with algorithms because both concepts describe typical solutions to some known problems. While an algorithm always defines a clear set of actions that can achieve some goal, a pattern is a more high-level description of a solution. The code of the same pattern applied to two different programs may be different.</p><h3>Classification of patterns:</h3><ul><li><strong>Creational patterns</strong> provide object creation mechanisms that increase flexibility and reuse of existing code.</li><li><strong>Structural patterns</strong> explain how to assemble objects and classes into larger structures while keeping the structures flexible and efficient.</li><li><strong>Behavioural patterns</strong> take care of effective communication and the assignment of responsibilities between objects.</li></ul><p>Let’s start exploring types of patterns…</p><h3><strong>Creational design pattern</strong></h3><h3><strong>1. Factory Method</strong></h3><p><strong>Factory Method</strong> is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.</p><p><strong>Problem:</strong></p><p>Imagine that you’re creating a delivery management application. The first version of your app can only handle transportation by trucks, so the bulk of your code lives inside the Truck class.</p><p>After a while, your app becomes pretty popular worldwide. Each day you receive dozens of requests from Air transportation companies to incorporate worldwide deliveries.</p><p><strong>Challenge:</strong></p><p>But how about the code? At present, most of your code is coupled to the Truck class. Adding transport by Air into the app would require making changes to the entire codebase. Moreover, if later you decide to add another type of transportation to the app, you will probably need to make all of these changes again.</p><p>As a result, you will end up with pretty nasty code, riddled with conditionals that switch the app’s behaviour depending on the class of transportation objects.</p><p><strong>Solution:</strong></p><p>The below example illustrates how the <strong>Factory Method</strong> can be used for creating delivery transport without coupling the transportation type into the main class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UU5g72h0XB26PyJWs1Svw.jpeg" /><figcaption><strong>Factory Method Pattern 1.0</strong></figcaption></figure><p>Let’s jump into the implementation,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/826ab2116ae2edfa81915aa1ce3ca493/href">https://medium.com/media/826ab2116ae2edfa81915aa1ce3ca493/href</a></iframe><p>So using the Factory method pattern you can decouple your logic to specific classes, just based on the delivery type you can easily instantiate the respective class and invoke a particular method.</p><h3><strong>Pros:</strong></h3><ol><li>You avoid tight coupling between the creator and the concrete products.</li><li>Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.</li><li><em>Open/Closed Principle</em>. You can introduce new types of products into the program without breaking the existing client code.</li></ol><h3><strong>Cons:</strong></h3><ol><li>The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern. The best-case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes.</li></ol><h3><strong>2. Abstract Factory</strong></h3><p><strong>Abstract Factory</strong> is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.</p><p><strong>Problem:</strong></p><p>Imagine you’re creating a furniture shop simulator. Your code consists of classes that contain that represent</p><p>Let’s consider products Chair, Sofa and Cofee table</p><p>And varients of these products let’s say Modern, Victorian, and ArtDeco</p><p>You need a way to create individual furniture objects so that they match other objects of the same family. Customers get quite mad when they receive non-matching furniture.</p><p>Also, you don’t want to change existing code when adding new products or families of products to the program. Furniture vendors update their catalogues very often, and you wouldn’t want to change the core code each time it happens.</p><p><strong>Solution:</strong></p><p>The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all variants of products follow those interfaces. For example, all chair variants can implement the Chair interface; all coffee table variants can implement the CoffeeTable interface, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCmmrc5q8BsLC4-qwwykJA.jpeg" /><figcaption><strong>Abstract factory Method Pattern 1.0</strong></figcaption></figure><p>The next move is to declare the <em>Abstract Factory</em> — an interface with a list of creation methods for all products that are part of the product family (for example, createChair, createSofa and createCoffeeTable). These methods must return <strong>abstract</strong> product types represented by the interfaces we extracted previously: Chair, Sofa, CoffeeTable and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcluPzFG7dsC1oKFhIqIkQ.jpeg" /><figcaption><strong>Abstract factory Method Pattern 1.1</strong></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c87774f370cacea5e63275ee253ded5/href">https://medium.com/media/1c87774f370cacea5e63275ee253ded5/href</a></iframe><p>The client code has to work with both factories and products via their respective abstract interfaces. This lets you change the type of a factory that you pass to the client code, as well as the product variant that the client code receives, without breaking the actual client code.</p><h3><strong>Pros:</strong></h3><ul><li>You avoid tight coupling between concrete products and client code.</li><li>You can be sure that the products you’re getting from a factory are compatible with each other</li></ul><h3><strong>Cons:</strong></h3><ul><li>The code may become more complicated than it should be since a lot of new interfaces and classes are introduced along with the pattern.</li></ul><h3><strong>3. Builder Pattern</strong></h3><p><strong>Builder</strong> is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.</p><p><strong>Problem:</strong></p><p>Imagine an object need step by step initialization of many fields and nested objects. Such initialization of code usually makes our constructor with lots of parameters.</p><p>Let’s take an example,</p><p>To build a simple house, you need to construct four walls and a floor, install a door, fit a pair of windows, and build a roof. But what if you want a bigger, brighter house, with a backyard and other goodies (like a heating system, plumbing, and electrical wiring)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85oCA4Mus72g-pXeOlgJVQ.jpeg" /><figcaption><strong>Builder Pattern 1.0</strong></figcaption></figure><p>In the above example, there is Class House with n number of parameters, most of the parameters will be unused(Not necessary to have a swimming pool in every house) and making our constructor not readable.</p><p><strong>Solution:</strong></p><p>The Builder pattern suggests that you extract the object construction code out of its own class and move it to separate objects called <em>builders</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3RwOu1-WwXF_VWuOpf05w.jpeg" /><figcaption><strong>Builder Pattern 1.1</strong></figcaption></figure><p>Let’s jump into the implementation part,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ef9909a4be4b60a79953aee77970ff5/href">https://medium.com/media/6ef9909a4be4b60a79953aee77970ff5/href</a></iframe><blockquote>What does “.()” mean in Kotlin?</blockquote><blockquote>“.()” means that <strong>the function can be invoked using object of DrawerBuilderKt class</strong>. = {} means that setup parameter is optional. So the function takes no parameters and return nothing</blockquote><h3>Pros:</h3><ul><li>You can construct objects step-by-step, defer construction steps or run steps recursively.</li><li><em>Single Responsibility Principle</em>. You can isolate complex construction code from the business logic of the product</li></ul><h3><strong>Cons</strong>:</h3><ul><li>The overall complexity of the code increases since the pattern requires creating multiple new classes.</li></ul><p><strong>4. Prototype Pattern</strong></p><p><strong>Prototype design pattern </strong>lets you copy existing objects without making your code dependent on their classes.</p><p><strong>Problem:</strong></p><p>Let’s say you have an object and you want to copy that. How would you do it? First, you have to create a new object of the same class. Then you have to go through all the fields of the original object and copy their values over to the new object.</p><p><strong>Solution:</strong></p><p>The Prototype pattern delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning. This interface lets you clone an object without coupling your code to the class of that object. Usually, such an interface contains just a single clone method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WCpeFZzix8CF84K8UsWMw.jpeg" /><figcaption><strong>Prototype Pattern 1.0</strong></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6b5c88e460ac4b0bc32a27fafe1786/href">https://medium.com/media/cf6b5c88e460ac4b0bc32a27fafe1786/href</a></iframe><p>The above code explains the proper usage of the Cloneable interface to make the Object.clone() method legal. Classes that implement this interface should override the Object.clone() method (which is protected) so that it can be invoked.</p><p>Note: another way you can simply use original.copy(xCorrdinate=10) to clone objects.</p><h3><strong>Pros</strong>:</h3><ul><li>You can clone objects without coupling them to their concrete classes.</li><li>You can produce complex objects more conveniently.</li><li>You get an alternative to inheritance when dealing with configuration presets for complex objects.</li></ul><h3><strong>Cons:</strong></h3><ul><li>Cloning complex objects that have circular references might be very tricky.</li></ul><h3>Singleton Pattern</h3><p><strong>Singleton</strong> is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.</p><p><strong>Problem:</strong></p><p>Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource — for example, a database or a file.</p><p>Here’s how it works: imagine that you created an object, but after a while decided to create a new one. Instead of receiving a fresh object, you’ll get the one you already created.</p><p>Note that this behaviour is impossible to implement with a regular constructor since a constructor call <strong>must</strong> always return a new object by design.</p><p><strong>Solution:</strong></p><p>All implementations of the Singleton have these two steps in common:</p><ul><li>Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.</li><li>Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsPfP4mQpg5CR_uG4F-mIQ.jpeg" /><figcaption><strong>Singleton 1.0</strong></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f16be2e9f55f63d51d4ec53cff36aa61/href">https://medium.com/media/f16be2e9f55f63d51d4ec53cff36aa61/href</a></iframe><p><strong>Pros</strong>:</p><ul><li>You can be sure that a class has only a single instance.</li><li>The singleton object is initialized only when it’s requested for the first time.</li></ul><p><strong>Cons:</strong></p><ul><li>It may be difficult to unit test the client code of the Singleton because many test frameworks rely on inheritance when producing mock objects. Since the constructor of the singleton class is private and overriding static methods is impossible in most languages, you will need to think of a creative way to mock the singleton. Or just don’t write the tests. Or don’t use the Singleton pattern.</li></ul><p>In this blog, we covered all creational design patterns with their example in kotlin. For more examples check out our Github Repository <a href="https://github.com/scalereal/design-patterns">here</a>. In the upcoming blogs, we’ll be exploring <strong>Structural</strong> and <strong>Behavioural </strong>Patterns.</p><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>Thank you ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcd230d14c6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/design-patterns-with-kotlin-part-1-dcd230d14c6e">Design patterns with Kotlin Part 1</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Database indexes in Postgres]]></title>
            <link>https://medium.com/scalereal/demystifying-database-indexes-in-postgres-5c1a6d949943?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1a6d949943</guid>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 12:59:56 GMT</pubDate>
            <atom:updated>2021-10-19T09:33:39.781Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will explore how indexing optimizes the performance of your database queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WYAFhmx7XbB2lSfk" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is indexing?</strong></h3><p>Indexes are used to quickly locate data without having to search every row in a database table. indexes are usually created using one or more columns in the database table. Creating an index on a field in a table creates another data structure that holds the field value and pointer to that record it relates to.</p><p>In simple words, if you have to search a particular person <em>phone number </em>in thousands of pages of the <em>phonebook </em>it’ll be difficult for you to search but what if you have character labels like the following image? I’m sure within a few seconds you can able to find it. Database indexing also works in the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXOgZI9BWxY4Ni4uBELLgQ.png" /></figure><p>Postgres has <a href="https://www.postgresql.org/docs/9.1/indexes-types.html">a few index types</a> but B-trees are by far the most common. They’re good for sorting and matching; and once you understand what they look like under the hood, it’s immediately apparent why.</p><h3><strong>Let’s take a look at examples</strong> 🧐</h3><p>For explaining indexing I have created one sample database with having a table named <em>employees </em>with attributes id &amp; name with 1M records.</p><p>This is how our <em>employees</em> table looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSOWJ8SGbiXAiPcOQFa-0A.png" /></figure><p>If you see in the Indexes section there is already one index <em>employee_pkey (on creating a table index is created for the primary key column by default). </em>B-Tree indexes are the default option when creating an index without specifying the type</p><h3><strong>What is B-Tree?</strong></h3><p>B-Tree stands for <strong>Balanced Tree</strong>.</p><p>It’s NOT a <a href="https://en.wikipedia.org/wiki/Binary_tree">binary tree</a>, which allows a max of 2 child nodes per parent and was designed for in-memory search.</p><p><strong><em>From Wikipedia 👇</em></strong></p><blockquote>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, a <strong>B-tree</strong> is a self-balancing <a href="https://en.wikipedia.org/wiki/Tree_data_structure">tree data structure</a> that maintains sorted data and allows searches, sequential access, insertions, and deletions in <a href="https://en.wikipedia.org/wiki/Logarithmic_time">logarithmic time</a>. The B-tree generalizes the <a href="https://en.wikipedia.org/wiki/Binary_search_tree">binary search tree</a>, allowing for nodes with more than two children.<a href="https://en.wikipedia.org/wiki/B-tree#cite_note-FOOTNOTEComer1979-2">[2]</a> Unlike other <a href="https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree">self-balancing binary search trees</a>, the B-tree is well suited for storage systems that read and write relatively large blocks of data, such as disks. It is commonly used in <a href="https://en.wikipedia.org/wiki/Database">databases</a> and <a href="https://en.wikipedia.org/wiki/File_system">file systems</a>.</blockquote><p><strong>Let’s play with some queries to understand</strong></p><p>See below 👇 query,</p><p>For Demonstration, I have created <em>1 million</em> records in the <em>employees</em> table,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XdofPBdieFkWGu-ih0HzXQ.png" /></figure><pre>explain analyze select * from employess where id = 2000;</pre><blockquote><strong>explain analyze</strong> gives details like the Execution time, query planning time, Index scan etc.</blockquote><p>Look carefully what’s the output of the above query, you can see in the output for this query the execution time is less than a second.</p><p>But how this happens, we have around <em>1 million </em>records in DB and it takes a few <em>ms</em> to fetch a particular record.</p><h3><strong>Let’s understand how B-Tree indexing works,</strong></h3><p>Indexes in PostgreSQL, simply put, are a replica of the data on the column(s) that is/are indexed. For example, when you search for a record in a table, where the column in which you are searching is indexed, the index decreases the cost of the query because PostgreSQL looks up in the index and can easily find the location of the data on the disk.</p><p>B-Trees are “balanced” because the distance from the root to any leaf node is the same. A leaf node is a node without children. The root node is a node at the top.</p><p>The node has keys. In our root node below, [1000, 3000, 4000] are keys. keys map to values in a database but also bound keys in the child node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V5Mf4WYLFDq_NNU0GMPfw.jpeg" /></figure><p>The first child node [400, 500] has values less than 1000, hence the pointer on the left side of 1000.</p><p>The second child node [2000] has values greater than 1000, hence the pointer on the right side of 1000.</p><p>The third child node [5000] has values greater than 4000, hence the pointer on the right side of 4000.</p><p>Now if we wanted to look up the key 2000, we’d compare 2000 to values in the root node and see that it’s between 1000 and 3000. So we’d use the pointer between 1000 and 3000 to find the node containing 2000.</p><p>This is an abstraction over Postgres’ implementation but you can already imagine why this is faster than iterating over every number in a table and checking if it equals 2000.</p><p>This is why B-trees can search, insert and delete in <strong>O(logN)</strong> time. for more details about B-tree you can check <a href="https://www.cs.helsinki.fi/u/mluukkai/tirak2010/B-tree.pdf">this</a> link.</p><p><strong>Query without indexing,</strong></p><p>Now see below query,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhMs66J9IrFU5kuQi85kOw.png" /></figure><p>In this query, we’re retrieving employees having name <em>Dave,</em></p><p>See the output of this query,</p><p>Query taking more execution time than the first one and this will get worst if we add more data into the table.</p><p>You can see in the result <strong><em>Parallel Seq Scan</em></strong> which means the query did a sequential search on the <em>employees</em> table, and that’s why the query takes time to fetch records.</p><p>The difference in query time in ordering the indexed vs non-indexed column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oW3faOYbHGEktQSaPbqEA.png" /></figure><h3>Advantages of Indexing</h3><ul><li>It helps you to reduce the total number of I/O operations needed to retrieve that data, so you don’t need to access a row in the database from an index structure.</li><li>Offers Faster search and retrieval of data to users.</li><li>Indexing also helps you to reduce tablespace as you don’t need to link to a row in a table, as there is no need to store the ROWID in the Index. Thus you will be able to reduce the tablespace.</li><li>You can’t sort data in the lead nodes as the value of the primary key classifies it.</li></ul><h3><strong><em>Disadvantages of indexing</em></strong></h3><ul><li>SQL Indexing Decrease performance in INSERT, DELETE, and UPDATE query.</li><li>You are not allowed to partition an index-organized table.</li></ul><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>Thank you ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1a6d949943" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/demystifying-database-indexes-in-postgres-5c1a6d949943">Demystifying Database indexes in Postgres</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Encrypted Secrets(Credentials)  with Rails6]]></title>
            <link>https://medium.com/scalereal/managing-encrypted-secrets-credentials-with-rails6-7bb31ca65e02?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb31ca65e02</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 20:21:37 GMT</pubDate>
            <atom:updated>2021-04-10T05:11:48.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tkpCPRoB_kZ3u02M" /><figcaption>Photo by <a href="https://unsplash.com/@ewankennedy19?utm_source=medium&amp;utm_medium=referral">Ewan Kennedy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background:</h3><p>Generally in the application, there are various secret keys and credentials that we need to make use of API keys, Secret keys for eg. AWS CLI login credentials etc.</p><p>Let’s talk about rails credentials now,</p><p>The way for managing secret keys in the Rails ecosystem itself. <br>How different this approach is? Well, it will store secrets itself in the application but those are encrypted and to decrypt them we need a master key.</p><h3><strong>Interacting with credentials:</strong></h3><p>A set of files were used to manage credentials</p><ul><li>config/credentials.yml.enc</li><li>config/master.key</li></ul><p>So basically config/credentials.yml.enc is an encrypted file that store credentials, we can safely commit this file to version control systems.</p><p>config/master.key contain a <em>key</em> that is used to decrypt config/credentilas.yml.enc This file should be in .gitignore</p><h3><strong>How To add/update credentials:</strong></h3><p>By running the following command we can edit/update credentials.</p><pre>$ EDITOR=vim rails credentials:edit</pre><p>This command will open the credentials file in decrypted version.</p><blockquote>Note: you can change EDITOR anything you want like nano or if you’re in windows use notepad etc.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FPAQNuIn6cTz7vCiOxsBg.png" /></figure><p>When we save it, it encrypts again using the same master key.</p><h3>How To read credentials?</h3><p>We can access secrets following way,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFcyFMma3kMTrBrDVwoQaA.png" /><figcaption>database.yml</figcaption></figure><p>Rails.application.secrets will retrieve the credentials accordingly to the current rails enviroment.</p><blockquote>Note: We need to share samemaster.key to others specifically, so that they can decrypt the secrets.</blockquote><h3>Managing multi-environment credentials</h3><p>To create credentials file for other environments like staging, production etc we need to use the following command.</p><pre>rails credentials:edit --environment production</pre><p>In Rails6 we can create environment wise secrets and their keys.</p><p>This command will create the following files inside the folder of /config</p><ul><li>config/production.yml.enc</li><li>config/production.key</li></ul><p>For accessing keys we can use the following command</p><pre>Rails.application.secrets[:aws][:access_key_id]</pre><h3><strong>Conclusions:</strong></h3><ul><li>By encrypting secrets helps provide data <strong>security</strong> for sensitive information.</li><li>Managing secrets for different environments makes it easier.</li><li>Removes extra overhead for managing secrets.</li></ul><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>Thank you ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb31ca65e02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/managing-encrypted-secrets-credentials-with-rails6-7bb31ca65e02">Managing Encrypted Secrets(Credentials) 🔐 with Rails6</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing RBS, Ruby’s new type signature language.]]></title>
            <link>https://medium.com/scalereal/introducing-rbs-rubys-new-type-signature-language-1e088ca21dbf?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e088ca21dbf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby3]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Fri, 25 Dec 2020 19:31:43 GMT</pubDate>
            <atom:updated>2020-12-26T07:52:23.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMzw15M-422QD1jDoH6-Hw.jpeg" /></figure><p>This week, <a href="https://www.ruby-lang.org/en/">Ruby</a>’s development team released the major version 3.0</p><p>Among the countless cool changes and additions including some fantastic general performance boosts and a powerful new concurrency/parallel processing efficiency model a new built-in language has emerged for static type definitions: <a href="https://github.com/ruby/rbs">Ruby (Type) Signature language, or RBS</a>.</p><h3>Why Static Typing?</h3><p>Ruby is a dynamically typed language, which means the interpreter tries to infer the data type of variables and object properties at runtime. This generally leads to programs being more dynamic and easier (faster) to code, and the interpreter/compiler loading code faster. However, the need for type inference and its associated costs, as well as the difficulty in detecting errors at compile time with dynamically typed code, have caused a modern programming trend to move towards statically typed languages.</p><p>Static typing makes the development experience much smoother. Bugs are far easier to detect, especially with modern IDEs and their linting as you write. For most statically typed languages, their more explicit nature leads to faster-compiled code (more efficient resulting machine code.)</p><h3><strong>Background</strong></h3><p><em>Static typing versus dynamic typing</em> is an age-old issue for programming languages. Statically typed languages are suitable for larger projects but are often less flexible. Dynamically typed languages allow for rapid development, but scaling teams and codebases with them can be difficult.</p><p>Matz declared that Ruby 3 will support static type checking four years ago. After seeing multiple communities developed type checkers, the Ruby committer team decided to build a foundation for the community to build type checkers on. Ruby 3 will ship with the ability to write type signatures for Ruby programs as well as built-in type signatures for the Ruby standard libraries. The standard type signature language will make type definitions in Ruby code portable between type checkers and encourage the community to write types for their gems and apps.</p><h3>What does RBS look like?</h3><p><a href="https://github.com/ruby/rbs">RBS</a>, a type annotation language and tool for Ruby, is about to be bundled with Ruby 3.0. Gradual typing with RBS allows Rubyists to enjoy the benefits of static analysis.</p><p>The signatures are written in .rbs files which are different from Ruby code. You can consider the .rbs files are similar to .d.ts files in TypeScript or .h files in C/C++/ObjC. The benefit of having different files is it doesn&#39;t require changing Ruby code to start type checking. You can opt-in type checking safely without changing any part of your workflow.</p><p>The type signatures for Ruby classes in RBS will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lwkb7_Z9lwm54KFInt85wA.png" /></figure><p>The appointment.rbs the file defines a class called Appointment, and it helps the reader to understand the overview of the class.</p><p>The class has three attributes token, statusand agents. The type of token and status are String. RBS also supports generic classes like Array as we can see with the type of agents attribute. It is an Array of Agent&#39;s</p><p>RBS also describes methods defined in the class and their types. The class defines the initialize and each_agents methods. The initialize method requires token and status as keyword arguments. The each_agents method accepts a block, or it returns an Enumerator instance.</p><p>The biggest benefit is that the type definition can be validated against both the implementation and its execution!</p><h3>Ruby Programming with types.</h3><p>The following is a list of major benefits of having types. We can write types in RBS files, and the tools will help you writing ruby code by:</p><p><strong>1] Finding more bugs: </strong>We can detect an undefined method call, an undefined constant reference, and more things a dynamic language might have missed.</p><p><strong>2] Nil safety: </strong>Type checkers based on RBS have a concept of <em>optional types</em>, a type which allows the value to be nil. Type checkers can check the possibility of an expression to be nil and uncovers undefined method(save!)&#39; for `nil: NilClass`.</p><p><strong>3] Better IDE integration: </strong>Parsing RBS files gives IDEs better understanding of the Ruby code. Method name completions run faster. On-the-fly error reporting detects more problems. Refactoring can be more reliable!</p><p><strong>4] Guided duck typing:</strong> Interface types can be used for duck typing. It helps the API users understand what they can do more precisely. This is a safer version of duck typing.</p><h3>Conclusion</h3><p>With the industry-wide trend towards adopting static typing in large scalable applications, the addition of RBS in Ruby 3.0 is an exciting step forward. Taking the development experience efficiency improvements that typing brings and combining them with the big runtime performance boosts under the hood in Ruby 3.0, I think the future is looking really bright for Ruby in the software industry.</p><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>Thank you ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e088ca21dbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/introducing-rbs-rubys-new-type-signature-language-1e088ca21dbf">Introducing RBS, Ruby’s new type signature language.</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set up CI/CD for Rails app using GitHub actions <> AWS Beanstalk ☁️]]></title>
            <link>https://medium.com/scalereal/set-up-ci-cd-for-rails-app-using-github-actions-aws-beanstalk-%EF%B8%8F-1df0e2e3cbb9?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1df0e2e3cbb9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 11:58:43 GMT</pubDate>
            <atom:updated>2020-11-18T11:29:30.601Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’m going to demonstrate to you how easily you can set up CI/CD for Rails app with AWS elastic beanstalk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vv1g56LNn8o5vcrX" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is CI/CD?</h3><p>In software engineering, CI/CD or CICD generally refers to the combined practices of continuous integration and either continuous delivery or continuous deployment. CI/CD bridges the gaps between development and operation activities and teams by enforcing automation in building, testing and deployment of applications.</p><p>Let’s start the execution step by step.</p><h3>CI (Continues Integration)</h3><p><strong>Step 1</strong></p><p>Let’s start creating a new workflow in GitHub actions that will perform those tasks. in your root rails project.</p><pre>mkdir -p .github/workflows<br>touch .github/workflows/main.yml</pre><p><strong>Step 2</strong></p><p>The <strong><em>main.yml </em></strong>where we defined our workflow CI and CD. We name our workflow CI/CD, Then list the name of our events which will trigger our workflow.</p><pre># main.yml</pre><pre>name: CI/CD<br>on: [push, pull_request]</pre><p><strong>Step 3</strong></p><p>Use the ubuntu latest image to install all necessary libraries and PostgreSQL as database</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55040cc4bbaaa45aa9254ee5143bc67c/href">https://medium.com/media/55040cc4bbaaa45aa9254ee5143bc67c/href</a></iframe><p><strong>services</strong> can be used to create additional containers for a job or steps. In our case, we are using it to spin-off <strong>postgres</strong> and <strong>redis</strong> service.</p><p><strong>Step 4</strong></p><p>We can define a sequential task that we want to perform in the machine with <strong>steps</strong> statement.</p><p>Next thing we will do is check out our rails app. Github provides official, ready to use actions an one of those is <strong>action/checkout</strong> <br>we can directly use this action directly using statement <strong>use.</strong></p><p>Similarly other actions <strong>actions/setup-ruby </strong>and<strong> </strong><strong>bolares/actions-yarn </strong>is used to check out the ruby version and yarn package manager that we want to use for our rails app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f810d4a7e2704115958425d42eaabf/href">https://medium.com/media/88f810d4a7e2704115958425d42eaabf/href</a></iframe><p>In the above snippet 👆, we just added steps for setting up ruby environment and yarn.</p><blockquote>More about <strong>bolares/actions-yarn</strong> is <a href="https://github.com/Borales/actions-yarn">here</a></blockquote><p><strong>Step5</strong></p><p>Once the code has been checked out and correct ruby version is set up, we install the gems using <strong>bundler</strong> and then run the <strong>specs</strong></p><p>Let’s add one more step for setting up our rails application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8860088aa3f55f552c46d07b697ea028/href">https://medium.com/media/8860088aa3f55f552c46d07b697ea028/href</a></iframe><p>In the above 👆 snippet, we are adding some necessary environment variables and executing the necessary commands.</p><p>First, we installed <strong>bundler</strong>gem, then create and migrate the database and finally running <strong>Rspec</strong> test cases.</p><blockquote>Note: I’m using <strong>Rspec</strong> testing library you can put other as well</blockquote><p>That’s it, we successfully integrate CI workflow for our Rails app successfully, now if push the changes you can see GitHub actions start executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*l89KcXckCrLhKFElT_WRuw.png" /><figcaption>CI Workflow</figcaption></figure><p>You can see your actions are executing successfully 🙂.</p><p>If you missed something below 👇 is the full snippet for CI workflow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff9c75154c1c38ebd7884378a223d483/href">https://medium.com/media/ff9c75154c1c38ebd7884378a223d483/href</a></iframe><h3><strong>CD(</strong>Continuous delivery)</h3><p>Now Let’s move to the <strong>CD(continues delivery)</strong>part, before moving further you must have an account on<strong>AWS</strong></p><p><strong>Step1</strong></p><p>Install CLI elastic beanstalk on your local machine.</p><pre>brew install aws-elasticbeanstalk</pre><p>Go to your project directory and initialize elastic beanstalk using the command</p><pre>eb init</pre><p>During init, elastic beanstalk shows some CLI questions &amp; it will create config.yml like below 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76609621e246af8103281649c82668db/href">https://medium.com/media/76609621e246af8103281649c82668db/href</a></iframe><p><strong>Step2</strong></p><p>Create a project with Postgres.</p><pre>eb create staging -db.engine postgres</pre><p>Above 👆command will start creating our project ready for deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3099200c10c371328ded7c04451f0d8/href">https://medium.com/media/b3099200c10c371328ded7c04451f0d8/href</a></iframe><p>Here is the sample log once we start creating it.</p><p>You might get an error here because we haven&#39;t set up database.yml correctly.</p><p><strong>Step3</strong></p><p>Add production configure like below 👇 in your <strong>database.yml</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159b7426abfb317d6b44742b99e094e4/href">https://medium.com/media/159b7426abfb317d6b44742b99e094e4/href</a></iframe><p>Now, the setup environment variable</p><pre>eb setenv SECRET_KEY_BASE= xxxxxx</pre><p>For<strong>SECRET_KEY_BASE</strong><em> </em>just fire on terminal</p><pre>RAILS_ENV=production bundle exec rake secret</pre><p>That’s it we are done with all configuration lets deploy our application.</p><pre>eb deploy staging</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUR5Ob_-_rcObIFf7RGaig.png" /></figure><p>If you check on AWS Elastic Beanstalk dashboard you can see our application created successfully.</p><p><strong>Step4</strong></p><p>Beanstalk Deploy is a GitHub action (and command-line script) to deploy apps to AWS Elastic Beanstalk. It takes the application name, environment name, version name, region and filename as parameters, uploads the file to S3, creates a new version in Elastic Beanstalk, and then deploys that version to the environment. It will wait until the deployment is finished, logging any messages from the environment during the update and exiting with a non-zero exit code if the deployment fails. It does not handle rolling back the environment.</p><p>Now let’s add this to our Github Action workflow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd00bf195af612a1cfa7601d1b4eee34/href">https://medium.com/media/cd00bf195af612a1cfa7601d1b4eee34/href</a></iframe><p>Here you can see we need <strong>AWS_ACCESS_KEY </strong>and<strong> </strong><strong>AWS_SECRET_ACCESS_KEY , </strong>using GitHub secrets you can add your credentials and those environmental variables accessible in your GitHub workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*VHcbUiUrRNGQwu3uoRSy2A.png" /></figure><p>Now let’s push our workflow changes &amp; let&#39;s see the result…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4ezyZZeYJzxccRFwDVSCw.png" /></figure><p>Hureeeee 🎉, our code builds successfully and deployed to AWS Beanstalk.</p><p>Here is a full code snippet 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f1a2daf59dc8a60153d7023d7fbc55c/href">https://medium.com/media/3f1a2daf59dc8a60153d7023d7fbc55c/href</a></iframe><h3><strong>Conclusion</strong></h3><p>There are many tools that can help enable a smoother transition to a CI/CD process. Testing is a large part of that process because even if you are able to make your integrations and delivery faster, it would mean nothing if was done so without quality in mind. Also, the more steps of the CI/CD pipeline that can be automated, the faster quality releases can be accomplished.</p><h3>Resource</h3><ul><li><a href="https://github.com/sandeshbodake/testing-rails">sandeshbodake/testing-rails</a></li><li><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ruby-rails-tutorial.html">Deploying a rails application to Elastic Beanstalk</a></li></ul><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>Thank you ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1df0e2e3cbb9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/set-up-ci-cd-for-rails-app-using-github-actions-aws-beanstalk-%EF%B8%8F-1df0e2e3cbb9">Set up CI/CD for Rails app using GitHub actions &lt;&gt; AWS Beanstalk ☁️</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement a state machine with kotlin using Tinder’s library]]></title>
            <link>https://medium.com/scalereal/implement-a-state-machine-with-kotlin-using-tinders-library-f66c4603d183?source=rss-2fb346de55e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f66c4603d183</guid>
            <category><![CDATA[state-machine]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sandesh Bodke]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 21:12:43 GMT</pubDate>
            <atom:updated>2020-08-04T11:30:46.598Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will show you how to integrate a finite state machine in kotlin using Tinder’s library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ox-fDWQrOtTsg5-pMziysQ.jpeg" /></figure><h3>What is a state machine?</h3><p>A state machine is a behaviour model. It consists of a finite number of states and is therefore also called finite-state machine (FSM). Based on the current state and a given input the machine performs state transitions and produces outputs.</p><p>A <strong>finite-state machine</strong> (<strong>FSM</strong>) or simply a <strong>state machine</strong>, is a mathematical <a href="https://en.wikipedia.org/wiki/Model_of_computation">model of computation</a>. It is an <a href="https://en.wikipedia.org/wiki/Abstract_machine">abstract machine</a> that can be in exactly one of a finite number of <a href="https://en.wikipedia.org/wiki/State_(computer_science)"><em>states</em></a> at any given time. The FSM can change from one state to another in response to some <a href="https://en.wikipedia.org/wiki/Input_(computer_science)">inputs</a>; the change from one state to another is called a <em>transition</em>. An FSM is defined by a list of its states, its initial state, and the inputs that trigger each transition.</p><h3>Why State machine?</h3><blockquote>So much complexity in software comes from trying to make one thing do two things.<br><strong>- Ryan Singer</strong></blockquote><p>If we are able to breakdown large complex task into some smaller independent units, a state machine can help us to imagine &amp; manage those units in a more abstract way where we just need to configure when a state can move to another state &amp; we concentrate on defining what happens when the transition occurs.</p><p>After configuration, we don’t need to care about how the transition happens. We just focus on when &amp; what not on how. Also, state machine helps us to imagine the whole workflow of states in a very predictable way, once transitions are configured we don’t need to really care about mismanagement or wrong transitions of states, the wrong transition can only occur if we configure the state machine in a wrong way.</p><h3>Implementing State Machine</h3><p>We’ll be using Kotlin and Intellij IDE to create our project. We’ll select Gradle as our build tool.</p><p>We’ll add the dependency by adding this to out <strong><em>build.gradle</em></strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76ebd0ac17356ef644c776a0059323e4/href">https://medium.com/media/76ebd0ac17356ef644c776a0059323e4/href</a></iframe><p>In this example, we create a StateMachine from the following state diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4W0y7tLWXTrhTkevlLdbDw.jpeg" /><figcaption><strong>Finite state machine real-life example</strong></figcaption></figure><p>This is a basic real-life example of a finite state machine using this example we will easily understand StateMachine flow. A rectangle represents State and the blue dotted arrow represents a particular event on that state.</p><p>Let’s start with the implementation part</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQJvwBSGaoc4eI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQJvwBSGaoc4eI%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZ2o1aWwxN3ByNHdwemp6bnFxZ2U5M2h6bnlzZXE5Y2c1MXNiazgxZyZlcD12MV9naWZzX2dpZklkJmN0PWc%2FQJvwBSGaoc4eI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="315" frameborder="0" scrolling="no"><a href="https://medium.com/media/df73f6c09d1622acd356d392fa884949/href">https://medium.com/media/df73f6c09d1622acd356d392fa884949/href</a></iframe><h3>Define states, event, and side effects.</h3><p><strong><em>States</em></strong> and <strong><em>Event</em></strong> that can cause transitions are what we use to encode the rules/logic of our domain. <strong><em>SideEffect</em></strong> part represents what we want to do with our code once a transition succeeds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bdae4d03e4c17ca4b1995427420afda/href">https://medium.com/media/1bdae4d03e4c17ca4b1995427420afda/href</a></iframe><h3>Define StateMachine</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45bc68394d8f01756e4d99c2addece43/href">https://medium.com/media/45bc68394d8f01756e4d99c2addece43/href</a></iframe><p>Here you can see we simply used <strong><em>StateMachine </em></strong>class and invoked <strong><em>create</em></strong> method using states, event, and side effects class.</p><p>Next, we add the States and how different Actions will make them transition to other states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69542fffcc99db17d4e7b3b6b5895f32/href">https://medium.com/media/69542fffcc99db17d4e7b3b6b5895f32/href</a></iframe><p>Here we added all possible transitions with their side-effects.</p><p>Now, Let’s add <strong><em>SideEffects</em></strong> actions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50649cc35d4829dbd603c31d8514a70c/href">https://medium.com/media/50649cc35d4829dbd603c31d8514a70c/href</a></iframe><p>After Every valid transaction particular <strong><em>SideEffect</em></strong> will be invoked. In this example for the demo purpose, we are just maintaining <strong><em>logs</em></strong> of a particular effect.</p><p>And we’re done. We added all the necessary things for StateMachine, Now it’s time to test it.</p><h3>Perform state transitions</h3><p>To <strong>Perform state transitions</strong> we are going to use simple test cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b1475cae964fc1e134972b7c4b7dfb7/href">https://medium.com/media/0b1475cae964fc1e134972b7c4b7dfb7/href</a></iframe><p><strong><em>Note: For demo purpose, I performed the state transition using test cases.</em></strong></p><p>Refer <a href="https://github.com/sandeshbodake/tinder-statemachine-example"><strong><em>this</em></strong></a><strong><em> </em></strong>Github Repository for complete implementation of StateMachine.</p><h3>Benefits of the state machine</h3><ul><li>You get rid of hard coding conditions in your code. State machine abstracts all logic regarding states &amp; transitions on behalf of you</li><li>In reality, state machines usually have a finite number of states &amp; definite transitions are defined in the states, so it’s easy to track which transition/data/ event caused the current condition of a request.</li><li>Developers can just concentrate on defining actions &amp; preconditions after a state machine is configured. With proper validation &amp; precondition, state machine prevents out of order operations.</li><li>State machines can be highly maintainable. Logically action performed during each transition is independent of each other. So the corresponding piece of code can be isolated.</li></ul><p>At <a href="https://scalereal.com/">Scalereal</a> We believe in Sharing and Open Source.</p><p>So, If you found this helpful please give some claps 👏 and share it with everyone.</p><p>Sharing is Caring!</p><p>Thank you ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f66c4603d183" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalereal/implement-a-state-machine-with-kotlin-using-tinders-library-f66c4603d183">Implement a state machine with kotlin using Tinder’s library</a> was originally published in <a href="https://medium.com/scalereal">ScaleReal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>