<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Subash</title>
    <description>The latest articles on Forem by Subash (@subash_ravichandran).</description>
    <link>https://forem.com/subash_ravichandran</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1065830%2F14a8ed17-0689-4463-85e6-813ce1934a97.jpg</url>
      <title>Forem: Subash</title>
      <link>https://forem.com/subash_ravichandran</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/subash_ravichandran"/>
    <language>en</language>
    <item>
      <title>Rails default port</title>
      <dc:creator>Subash</dc:creator>
      <pubDate>Sat, 13 May 2023 11:46:01 +0000</pubDate>
      <link>https://forem.com/subash_ravichandran/rails-default-port-5a7e</link>
      <guid>https://forem.com/subash_ravichandran/rails-default-port-5a7e</guid>
      <description>&lt;p&gt;There might be cases where you need to utilize more than one port for an application in your local. For example web-server might be utilizing port 3000 and if you start rails engine by using the command &lt;code&gt;rails server&lt;/code&gt; or &lt;code&gt;rails s&lt;/code&gt; you will get an error &lt;code&gt;Address already in use - bind(2) for "127.0.0.1" port 3000&lt;/code&gt;. So manually you need to specify rails to use a different port like &lt;code&gt;rails s -p 3001&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Actually there is a way you can specify the rails engine to use a specific port to use by default.&lt;/p&gt;

&lt;p&gt;Just locate the rb file with the engine name under &lt;code&gt;/config&lt;/code&gt; directory. In my case puma is the engine so lets open &lt;code&gt;config/puma.rb&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The below line is responsible for using the port 3000 by default.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;port ENV.fetch("PORT") { 3000 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace the 3000 with port whichever you want to use. In my case it is 3001&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;port ENV.fetch("PORT") { 3001 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it. Now start the server by default port 3001 will be used by rails.&lt;/p&gt;

</description>
      <category>rails</category>
      <category>port</category>
    </item>
    <item>
      <title>Ruby Lambda VS Proc</title>
      <dc:creator>Subash</dc:creator>
      <pubDate>Thu, 27 Apr 2023 16:07:10 +0000</pubDate>
      <link>https://forem.com/subash_ravichandran/ruby-lambda-vs-proc-57ff</link>
      <guid>https://forem.com/subash_ravichandran/ruby-lambda-vs-proc-57ff</guid>
      <description>&lt;p&gt;Lambda and Proc - both are container for a block of code. Define a set of codes inside either of them and save them as a variable for later use.&lt;/p&gt;

&lt;p&gt;Let's see the usage of both in detail&lt;/p&gt;

&lt;h2&gt;
  
  
  Lambda
&lt;/h2&gt;

&lt;p&gt;A lambda is very similar to method, just the syntax varies. Below is the syntax for creation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_lambda = -&amp;gt; { puts 'something'}

# lambda using arguments
test_lambda = -&amp;gt; (x) { x + 1}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have defined a lambda and store in a variable &lt;code&gt;test_lambda&lt;/code&gt;, we have to call it to use. There are multiple ways to call a lambda. Below is the list of ways&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_lambda.call
test_lambda.call()
test_lambda.()
test_lambda.[]
test_lambda.[]
test_lambda.===
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I prefer &lt;code&gt;.call()&lt;/code&gt; as it is more readable than others&lt;/p&gt;

&lt;p&gt;If we call the defined lambda, the block of code is executed and result is displayed&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_lambda.call(5)
6
=&amp;gt; 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I stated earlier, lambda works very similar to methods if lambda is defined with args, the number of args should match during call, else it will raise an exception just like a regular method.&lt;/p&gt;

&lt;p&gt;Also like a regular method a lambda will return normally to it's &lt;code&gt;__callee__&lt;/code&gt; rather than returning from a context&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def demo_lambda(num)
  test_lambda = -&amp;gt; (x) { return x + 1 }
  new_value = test_lambda.call(num)
  puts 'new value returned'
  new_value
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the return of the test_lambda will return the value within the scope of the lambda (i.e returned value is stored in &lt;code&gt;new_value&lt;/code&gt;) and will proceed with the execution of below lines&lt;/p&gt;

&lt;h2&gt;
  
  
  Proc
&lt;/h2&gt;

&lt;p&gt;Procs are similar to lambda, but there are few differnces and the choice to use between Proc and Lambda depends on it&lt;/p&gt;

&lt;p&gt;Proc creation uses different syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_proc = Proc.new {|x| x+1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Calling Proc is similar to lambda. It can be called using &lt;code&gt;.call(), .(), .[], .===&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Proc doesn't care about the number of arguments passed. But if the argument is used for any kind of calculation or manipulation it will raise an error. &lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p = Proc.new{|x| puts 'something'}
p.call()
=&amp;gt; "Something"

p = Proc.new{|x| x*2 }
p.call()
(irb):61:in `block in &amp;lt;main&amp;gt;': undefined method `*' for nil:NilClass (NoMethodError)

p = Proc.new{|x| x*2 }

#since there is a calculation based on the args passed NilClass error is thrown
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One more major difference is proc will return from the current context. i.e if proc is inside an method, then calling return from proc is equivalent to returning from that method. Let's see an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def demo_proc(num)
  test_proc = Proc.new{ |x| return x + 1 }
  new_value = test_proc.call(num)
  puts 'new value returned'
  new_value
end

demo_proc(5)

irb(main):008:0&amp;gt; demo_proc(5)
=&amp;gt; 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above sample, the puts statement will not be printed. This is because the return in test_proc will return from the demo_proc itself.&lt;/p&gt;

&lt;p&gt;Source: &lt;a href="https://ruby-doc.org/core-2.6/Proc.html"&gt;Proc&lt;/a&gt; &lt;a href="https://ruby-doc.org/core-2.6.3/Proc.html#method-i-lambda-3F"&gt;Lambda&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>proc</category>
      <category>lambda</category>
    </item>
    <item>
      <title>Ruby Benchmarking</title>
      <dc:creator>Subash</dc:creator>
      <pubDate>Sun, 23 Apr 2023 05:30:55 +0000</pubDate>
      <link>https://forem.com/subash_ravichandran/ruby-benchmarking-36m5</link>
      <guid>https://forem.com/subash_ravichandran/ruby-benchmarking-36m5</guid>
      <description>&lt;p&gt;Benchmarking is one of the crucial part of code, since it can help developers to identify and fix the performance issues thereby improving the execution speed of the application. That said will see how can we benchmark a given code&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirements
&lt;/h2&gt;

&lt;p&gt;benchmark - gem. Rails comes with this gem installed by default. There are some external gems which also serves the same purpose. In this article we will cover the benchmark gem&lt;/p&gt;

&lt;p&gt;The usage is simple. Write scripts - load it in system-irb/rails-irb - execute and analyse&lt;/p&gt;

&lt;p&gt;Lets benchmark below select and detect methods&lt;br&gt;
launch irb or rails console&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# declare an array of 1 to 100
arr = (1...1000)

def get_matching_first_element_using_select(arr)
  return arr.select{|num| num == 1}.first
end

def get_matching_first_element_using_detect(arr)
  return arr.detect{|num| num == 1}
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is obvious that detect is much more effecient than select. Lets confirm this with benchmark&lt;/p&gt;

&lt;p&gt;Require the gem (if you are launching rails console requiring 'benchmark' is not needed as it is already loaded by default)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'benchmark'

Benchmark.measure{ get_matching_first_element_using_select(arr)}
=&amp;gt; 
#&amp;lt;Benchmark::Tms:0x00007fa96a532fd0                                        
 @cstime=0.0,                                                             
 @cutime=0.0,                                                             
 @label="",                                                               
 @real=0.00016800200000943732,                                            
 @stime=1.2999999999985246e-05,                                           
 @total=0.00017499999999998073,                                           
 @utime=0.00016199999999999548&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you just want to see the actual time taken in microseconds use &lt;code&gt;ms&lt;/code&gt; instead of &lt;code&gt;measure&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Benchmark.ms{ get_matching_first_element_using_select(arr)}
=&amp;gt; 0.16017500001908047 #we will get this simplified clutter free output
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is fine but we need to do benchmark for 2 different methods separately. Is there any way to run both of them together and compare side by side. Yes there is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Benchmark.bm do |x|
  x.report("select: ") {100.times do; get_matching_first_element_using_select(arr); end}
  x.report("detect: ") {100.times do; get_matching_first_element_using_detect(arr); end} 
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will yeild the below output which is easy to compare&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;              user     system      total        real
select:   0.004269   0.000015   0.004284 (  0.004280)
detect:   0.000052   0.000003   0.000055 (  0.000055)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the results are clear, Detect is faster than select since we are fetching the first element - which is like 78 times faster.&lt;/p&gt;

&lt;p&gt;There are multiple ways to benchmark, this is just the basic. Read more at &lt;a href="https://ruby-doc.org/stdlib-2.5.0/libdoc/benchmark/rdoc/Benchmark.html"&gt;source&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>benchmark</category>
      <category>performance</category>
    </item>
    <item>
      <title>Rails console sandbox mode</title>
      <dc:creator>Subash</dc:creator>
      <pubDate>Thu, 20 Apr 2023 02:38:16 +0000</pubDate>
      <link>https://forem.com/subash_ravichandran/rails-console-sandbox-mode-2g8d</link>
      <guid>https://forem.com/subash_ravichandran/rails-console-sandbox-mode-2g8d</guid>
      <description>&lt;p&gt;&lt;code&gt;rails c&lt;/code&gt; or &lt;code&gt;rails console&lt;/code&gt; starts the irb session, where we can execute, test and confirm queries. It is one of the helpful feature for developers. However we need to use it with caution as it is capable of modifying records. Any accidental modification in staging or production data might lead to problem.&lt;/p&gt;

&lt;p&gt;There is an option to avoid this. Rails comes with an inbuilt &lt;code&gt;sandbox&lt;/code&gt; mode. When you start the console with &lt;code&gt;--sanbox&lt;/code&gt; flag, we will see a message &lt;code&gt;Any modifications you make will be rolled back on exit&lt;/code&gt; because the whole irb session starts within an ActiveRecord::Transaction, which is rolled back when you exit the session.&lt;/p&gt;

&lt;p&gt;Here's a sample&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffeq2gf5ofmcg76f5s7gq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffeq2gf5ofmcg76f5s7gq.png" alt="rails console in sandbox mode"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But wait, There is a catch&lt;/p&gt;

&lt;p&gt;In sandbox mode, database rows are fully locked, which means that it prevents your live production services from modifying them. If you are holding a record for too long, all the live transactions related to it have to wait till the lock is released or in some cases might mess up the updations.&lt;/p&gt;

</description>
      <category>rails</category>
      <category>console</category>
      <category>sandbox</category>
    </item>
    <item>
      <title>Ruby - dig method</title>
      <dc:creator>Subash</dc:creator>
      <pubDate>Wed, 19 Apr 2023 04:14:14 +0000</pubDate>
      <link>https://forem.com/subash_ravichandran/ruby-dig-method-2b6a</link>
      <guid>https://forem.com/subash_ravichandran/ruby-dig-method-2b6a</guid>
      <description>&lt;p&gt;The &lt;code&gt;dig&lt;/code&gt; method is a useful tool to dig through all the keys of a given hash (recursively) and returns the value. If the value for final key or the intermediate key is not found a &lt;code&gt;nil&lt;/code&gt; value is returned&lt;/p&gt;

&lt;p&gt;Let's say we have the given params&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;params = Hash.new
params[:user1] = {
  name: 'Alice',
  gender: 'F',
  age: '40',
  job_details: {
    company: 'XYZ'
  },
  contact_details: {
    Landline: '00000000',
    mobile: '0000001'
  }
}
params[:user2] = {
  name: 'Bob',
  gender: 'M',
  age: '40',
  job_details: {
    company: 'ABC'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if we need the mobile number of all users, the following code will break because in case of Bob the contact_details hash is not available.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;params.map{|key,value| value[:contact_details][:mobile]}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we need to check if the key is available before diving into it. If there are more iterations then there would be more conditional checks. Luckily there is an alternative&lt;br&gt;
We can use &lt;code&gt;dig&lt;/code&gt; to fetch with single line of code as the dig handles the conditional checks internally. The code will look like this and it will work for both users&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;params.map{|key,value| value.dig(:contact_details, :mobile)}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which will give the following output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;=&amp;gt; ["0000001", nil]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;dig iterated through the given keys recursively, if any of the keys are not available it will break returning nil (as in case of Bob).&lt;/p&gt;

&lt;p&gt;Note: In scenarios where an error should be raised when a key is not found, dig will not be helpful as it returns nil.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://apidock.com/ruby/Hash/dig"&gt;Source&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>dig</category>
    </item>
    <item>
      <title>Rails - annotate method</title>
      <dc:creator>Subash</dc:creator>
      <pubDate>Sun, 16 Apr 2023 11:33:43 +0000</pubDate>
      <link>https://forem.com/subash_ravichandran/rails-annotate-method-2b3</link>
      <guid>https://forem.com/subash_ravichandran/rails-annotate-method-2b3</guid>
      <description>&lt;h2&gt;
  
  
  The &lt;code&gt;annotate&lt;/code&gt; method
&lt;/h2&gt;

&lt;p&gt;is used to add an SQL comment to queries generated from the relation. Here is an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Bullet.includes(:user).
  find_by_id(params[:id])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above query uses include to eager-load the user table. We can use annotate to add a sql comment to explain the same like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Bullet.includes(:user).
  annotate('Eager loading user table').
  find_by_id(params[:id])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it.&lt;/p&gt;

&lt;p&gt;Now when you see the rails server logs, you can find the sql comment which was added in the query explanation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Processing by BulletsController#show as HTML
  Parameters: {"id"=&amp;gt;"5"}
  Bullet Load (0.1ms)  SELECT "bullets".* FROM "bullets" WHERE 
"bullets"."id" = ? /* Eager loading user table */ LIMIT ?
  [["id", 5], ["LIMIT", 1]]
  ↳ app/controllers/bullets_controller.rb:73:in `set_bullet'
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE
 "users"."id" = ?  [["id", 2]]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Caution: Some escaping is performed, however untrusted user input should not be used.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/rails/rails/blob/7c70791470fc517deb7c640bead9f1b47efb5539/activerecord/lib/active_record/relation/query_methods.rb#L1221"&gt;Source-Code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>rails</category>
      <category>annotate</category>
    </item>
  </channel>
</rss>
