<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>learning &#8211; redpanthers.co</title>
	<atom:link href="/tag/learning/feed/" rel="self" type="application/rss+xml" />
	<link>/</link>
	<description>Red Panthers - Experts in Ruby on Rails, System Design and Vue.js</description>
	<lastBuildDate>Tue, 23 Aug 2016 09:45:09 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.2.7</generator>
	<item>
		<title>Lambda vs Proc Vs Blocks</title>
		<link>/lambda-vs-proc-vs-blocks/</link>
				<comments>/lambda-vs-proc-vs-blocks/#comments</comments>
				<pubDate>Tue, 23 Aug 2016 09:45:09 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Beginners]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[anonymous functions]]></category>
		<category><![CDATA[arugments]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[block]]></category>
		<category><![CDATA[difference]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[lambda vs proc vs bloc]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[proc]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=467</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[The difference between these three is one of the most baffling concepts to grasp while anyone starts to learn ruby. Since at Red Panthers we recruit and build our own team from freshers, we too will be blogging about it here to make it easy for the beginners.
But before we state the difference between the three, let me explain what all these three does to make it easy for you.
<strong>Blocks: </strong>They are called closures in other languages, it is a way of grouping code/statements. In ruby single line blocks are written in {} and multi-line blocks are represented using <strong>do..end</strong>
An interesting fact about ruby is that all methods in ruby accept a block, even if you don&#8217;t declare a variable to accept it. So for example, take the method below


<pre class="lang:default decode:true">def my_method
  puts "Hello World"
end</pre>


It can accept a block as below


<pre class="lang:default decode:true">my_method { puts 'Hello Reader' }</pre>


The code is valid, but the output will have only <strong>puts &#8220;Hello World&#8221;</strong>.
<strong>Why? </strong>because we passed in the block but it is not getting called. To run the block passed within your method you need to use the <em>yield </em>command.


<pre class="lang:default decode:true">def my_method
  puts 'Hello World'
  yield
end</pre>


Now it will print


<pre class="lang:default decode:true">Hello World.
Hello Reader.</pre>


But since we placed yield, it would now be expecting a block to be always passed in. So we need to write code to check if a block is given or not. The command to do that in ruby is <em>block_given?.</em>


<pre class="lang:default decode:true">def my_method
  puts 'Hello World'
  yield if block_given?
end</pre>


<strong>Proc</strong>
Is a block itself, but it&#8217;s bound to a variable. So proc lets us save a code block to a variable, and pass it around in our application.
A good example from the <a href="https://ruby-doc.org/core-2.2.0/Proc.html">ruby docs</a> is shown below


<pre class="lang:default decode:true">def gen_times(factor)
  return Proc.new {|n| n*factor }
end
times3 = gen_times(3)
times5 = gen_times(5)
times3.call(12)               #=&gt; 36
times5.call(5)                #=&gt; 25
times3.call(times5.call(4))   #=&gt; 60</pre>


<strong>Lambda</strong>
If you felt proc&#8217;s to be a refined version of block, then you can say lambda&#8217;s to be a refined version of proc.
Lambda is essentially a proc itself but, the argument management is rigid. If it doesn&#8217;t get an argument or if the argument count is more or less it would raise an error.
Example:


<pre class="lang:default decode:true">Proc.new {|a,b| [a,b] }.call(1,2,3)
=&gt; [1,2]</pre>




<pre class="lang:default decode:true">lambda {|a,b| [a,b] }.call(1,2,3)
=&gt;
ArgumentError: wrong number of arguments (3 for 2)
	from (irb):7:in `block in irb_binding'
	from (irb):7:in `call'
	from (irb):7
	from /home/dev1/.rvm/rubies/ruby-2.2.2/bin/irb:11:in `&lt;main&gt;'
2.2.2 :008 &gt; Proc.new {|a,b| [a,b] }.call(1,2,3)</pre>


Since it&#8217;s now clearer to you on what block, proc and lambda is, let&#8217;s start with the difference between the three.
Lambda shortcut notation.


<pre class="lang:default decode:true">code = -&gt; (x) { x*x }
code.call 4
=&gt; 16</pre>


&nbsp;
<strong>Lambda vs proc vs Blocks</strong>
Proc and Blocks are the same, block is actually creating a single instance of proc which can&#8217;t be moved about in a variable. You can read about the similarity of Proc and Block <a href="https://www.reddit.com/r/ruby/comments/4z86sg/another_lambda_vs_proc_vs_blocks_article/d6vj4a6">here</a>.
If we do return within a lambda, it would just return from lambda and the method will continue.


<pre class="lang:default decode:true">def lambda_method
  lambda { return puts 'lambda' }.call
  return 'method'
end
lambda_method
=&gt; method</pre>


If we do return with a proc, it would exit the method and return that value from proc.


<pre class="lang:default decode:true">def proc_method
  Proc.new { return puts 'proc' }.call
  puts 'method'
end
proc_method
=&gt; proc</pre>


Arguments:
The second difference between the three is the way they manage arguments. Block and Proc deal with them more or less the same, but lambda is totally different.
Proc and Bloc, doesn&#8217;t mind about the number of arguments passed. But if we access a variable that is not present then it would raise an error.


<pre class="lang:default decode:true">def my_method
  yield 1, 2, 3
end
my_method { |x, y| puts "#{x} &amp; #{y}" }
=&gt; "1 &amp; 2"</pre>




<pre class="lang:default decode:true">Proc.new { |x, y| puts "#{x} &amp; #{y}" }.call(4, 5, 6)
=&gt; "4 &amp; 5"</pre>


lambda will raise an error


<pre class="lang:default decode:true">def my_method
  yield
end
my_method { |x, y| puts "#{x} &amp; #{y}" }</pre>


<b>Takeaways</b>
Block, Proc &amp; Lambda are the three  different ways of grouping the code:
<span style="font-weight: 400;"><strong>Block:</strong></span>


<ul>
 	

<li><span style="font-weight: 400;">Is in between the curly braces and in between do and end.</span></li>


 	

<li>No issue with number of arguments.</li>


 	

<li>Blocks are basically a proc without a name</li>


</ul>


<span style="font-weight: 400;"><strong>Proc:</strong></span>


<ul>
 	

<li><span style="font-weight: 400;">Similar behaviour as Block.</span></li>


 	

<li>Can be stored in a variable and move around.</li>


 	

<li>No issue with number of arguments.</li>


 	

<li>Return within the proc would exit the method from where it is called.</li>


</ul>


<span style="font-weight: 400;"><strong>Lambda</strong></span>


<ul>
 	

<li><span style="font-weight: 400;">Same as Proc, but closer to a method.</span></li>


 	

<li>Strict regarding the arguments it gets and it needs.</li>


 	

<li>Return within a lambda would exit it from the lambda and the method would continue executing.</li>


</ul>


&nbsp;]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/lambda-vs-proc-vs-blocks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>Optimising PostgreSQL database query using indexes</title>
		<link>/optimising-postgresql-database-query-using-indexes/</link>
				<comments>/optimising-postgresql-database-query-using-indexes/#comments</comments>
				<pubDate>Thu, 11 Aug 2016 10:59:22 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[B Tree]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[GIN]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[migration]]></category>
		<category><![CDATA[multi column]]></category>
		<category><![CDATA[partial migration]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[single column]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[training]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=389</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[At Red Panthers PostgreSQL is our go to database we use it everywhere. So thinking about how to optimize our database performance is one of the most talked about topic at our office. The best way to speed up report generation and data retrieval within a rails application is to leave it to the database, as they have algorithms and optimizations build just for that. We always felt that most Ruby on Rails projects out there, do not use the full potential of a database and they usually just limit it to a data store. PostgreSQL or any database for that matter is much more than that.
We would be blogging on how we use PostgreSQL in our projects to speed up our client's applications. This particle is the first part of a series of article we would be writing on database optimization.
<img class="aligncenter" src="http://i.imgur.com/YSZE83d.jpg?1" width="231" height="172" />
<strong>Database Indexes:</strong>
Indexes are a special lookup table that the database search engine can use to speed up data retrieval. An Index is similar to a pointer to a particular row of a table. As a real world example, consider a Britannica Encyclopedia with 22 volumes of books, and an extra book listing  the index,with which you can find out the item you are searching for in those 22 books.
PostgreSQL 9.5, provides several index algorithms like B-tree, Hash, GiST, SP-GiST and GIN. When you create an index using Ruby on Rails migration, by <strong>default it would be using the B-Tree</strong> migration. Whereas, as we move on to the indexing algorithms, we need to check into the general classification of an index and the data to be indexed.
<strong>Primary Keys</strong>
In rails, when we generate a model , by default an ID column would be added to the table. It would have integers values and they would be unique as well. By default, when you set a column as a primary key, the database would build a <em><strong>unique index </strong></em>on it. So we don&#8217;t need to add migration for it.
<strong>Foreign Keys</strong>
When you build a relationship between two tables you add a <code>foreign_key</code> in the child table to point to parent, eg: <code>user_id</code>, <code>group_id</code>. We need to query through this relationship a lot in rails, for example to load all the comments of post or all members of a group.<strong> So we need to index that for speed.</strong>.
If you are using some non id value to reference a table, lets say in your application ,you give all your users a unique URL which has the username. (Eg: http://csnipp.com/coderhs), in that case we would be using the username to query the data, so we need to have it indexed. In fact you should index all the columns you might be using in your where queries. Like if you are searching for users of a particular age or income frequents in your reports, then you should create an index for them as well.
<strong>Note:</strong>  What we explained above are single column indexes and multi column indexes. So if you are indexing just a single column in a table, its single column indexes.


<pre class="lang:pgsql decode:true">CREATE INDEX index_name
ON prices (user_id);</pre>


Rails code:


<pre class="lang:ruby decode:true">add_index :prices, :user_id</pre>


When we index multiple columns, they are called multi column index.


<pre class="lang:pgsql decode:true">CREATE INDEX index_name
ON user_views (user_id, article_id);</pre>


Rails code:


<pre class="lang:ruby decode:true">add_index :user_views, [:user_id, :article_id]</pre>


If you are joining two tables, using a column (which is not the already indexed foreign key) then you should index that as well.
<strong>State column &amp; Boolean column</strong>
State and Boolean column are columns that should be indexed as there would be a lot of rows but only limited number of values in those columns. Boolean column would have only true or false (two values)and state columns will have more than two like eg: draft, published, pending. The speed of load would be faster for these columns as they are only limited keys that can be placed in the index, and on a single lookup we can load them.
<strong>Partial indexes</strong> can be used in the above case, as the name suggests it&#8217;s an index over a subset of your table. The index would be building if it satisfies certain conditions. They can be most useful <strong>while writing scopes in rails. </strong>Lets say that you have a scope that picks up all the articles which are marked as SPAM. In your model you will write a scope like below


<pre class="lang:ruby decode:true">scope :articles, where(:spam =&gt; 'true')</pre>


So internally it&#8217;s a where query, one can add a partial index migration as follows:


<pre class="lang:pgsql decode:true">CREATE INDEX index_name
on articles (spam is true);</pre>


Rails:


<pre class="lang:ruby decode:true">add_index :articles, :spam, name: "index_articles_on_spam", where: "(spam IS true)"</pre>


<strong>When not to use indexes</strong>
Using indexes speeds up the SELECT and WHERE command, but it does slows down the execution of INSERT.
<strong>So avoid indexing when we have table that has a lot of insert and update</strong>
So we should avoid using Indexes when we have a table that holds a huge number of raw data, where we do a lot of batch updates and insert. For example, in an IoT application we would pipe all the data from multiple devices to a single table , summarize  and insert it into its proper tables. And  by a lot of data, I am referring to at least 10+ MB of data per minute. In most cases, we would just truncate that table after processing, hence it would slow us down if we were to index it.
<strong>If the table is too small and you know it will always be small</strong>
If you have a setting table which just stores the application settings, that can be modified by an admin panel. Then it doesn&#8217;t seem to be worth having an index there.
<strong>When you are manipulating the values of a column a lot</strong>
Lets say the particular value of a column gets changes extremely a lot, like the website view count. Then indexing it is not highly recommended.
Finally to complete this article. If you want to drop an index:
SQL


<pre class="lang:pgsql decode:true">DROP INDEX index_name;</pre>


Rails


<pre class="lang:ruby decode:true">remove_index :books, :created_at</pre>


<strong>Summary</strong>:


<ul>
 	

<li>Index Primary key</li>


 	

<li>Index Foreign key</li>


 	

<li>Index all columns you would be passing into where clause</li>


 	

<li>Index the keys used to Join tables</li>


 	

<li>Index the date column (if you are going to call it frequent, like rankings of a particular date)</li>


 	

<li>Index the type column in an STI or polymorphism.</li>


 	

<li>Add partial index to scopes</li>


 	

<li>Do not index tables with a lot of read, write</li>


 	

<li>Do not index tables you know that will remain small, all through out its life time</li>


 	

<li>Do not index columns where you will be manipulating lot of its values.</li>


</ul>


Keep visiting here to know more about the PostgreSQL indexing algorithms in part 2 of this article.
<strong>References:</strong>
<a href="https://www.postgresql.org/docs/9.2/static/indexes-types.html">https://www.postgresql.org/docs/9.2/static/indexes-types.html</a>
<a href="http://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html">http://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html</a>
<a href="http://www.tutorialspoint.com/postgresql/postgresql_indexes.htm">http://www.tutorialspoint.com/postgresql/postgresql_indexes.htm</a>]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/optimising-postgresql-database-query-using-indexes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>Database transaction in Rails</title>
		<link>/database-transaction-rails/</link>
				<pubDate>Mon, 01 Aug 2016 11:38:48 +0000</pubDate>
		<dc:creator><![CDATA[coderhs]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DBA]]></category>
		<category><![CDATA[expert]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[nested transaction]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[transaction]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=377</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[

<blockquote>A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties called the <strong>atomicity</strong>, <strong>consistency</strong>, <strong>isolation</strong> and <strong>durability</strong> (<strong>ACID</strong>) properties, to qualify as a transaction.</blockquote>


We use database transactions to make sure that all the instructions we send to database are successful, and would cause changes to the database only if they are successful. Let&#8217;s say that you are working on a banking application which would withdraw money from one account and deposit into another account. The code for it would look like below


<pre class="lang:ruby decode:true">User.find(156).withdraw(1000)
User.find(157).deposit(1000)</pre>


But for some reason, the withdrawal was successful but the deposit was not, the amount was taken out but never deposited to the other user.To avoid these kind of issues, database has a functionality called transactions, in which you can  build up each sql query. But if for any reason, any of the sql statements fails or an exception rises in the block, all the transactions are rolled back to their original form.


<pre class="lang:default decode:true">User.transaction do
  User.find(156).withdraw(1000)
  User.find(157).deposit(1000)
end</pre>


In rails, the transaction method is available as class method and instance method, but the functionality for both is same. There is no difference when you will use.


<pre class="lang:default decode:true">@user.transaction do
end</pre>


and


<pre class="lang:default decode:true">User.transaction do
end</pre>


The reason why rails provides this, is for better readability.
One can also mix various model types in a transaction, as the transaction are bound to a database connection. So there is no issue in writing code like below.


<pre class="lang:default decode:true">User.transaction do
  Order.create order_attributes
  Purchase.create purchase_attribute
end</pre>


&nbsp;
<strong>Nested Transactions: </strong>It is possible to write nested transactions. But it is to be noted that,<strong> it would just make each child transaction a part of the parent transaction</strong>. Taking the example from the Rails documentation.
The below code


<pre class="lang:default decode:true">User.transaction do
  User.create(username: 'Kotori')
  User.transaction do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end</pre>


Creates both “Kotori” and “Nemu”. Reason is the ActiveRecord::Rollback exception in the nested block does not issue a ROLLBACK. Since these exceptions are captured in transaction blocks, the parent block does not see it and the real transaction is committed.
Reference:
https://technet.microsoft.com/en-us/library/ms190612(v=sql.105).aspx]]&gt;		</p>
]]></content:encoded>
										</item>
	</channel>
</rss>
