<?xml version="1.0" encoding="utf-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">
     <title>BigBinary Blog</title>
     <link href="https://www.bigbinary.com/feed.xml" rel="self"/>
     <link href="https://www.bigbinary.com/"/>
     <updated>2026-03-06T02:26:55+00:00</updated>
     <id>https://www.bigbinary.com/</id>
     <entry>
       <title><![CDATA[Rails 5 Active Record attributes API]]></title>
       <author><name>Abhay Nikam</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-attributes-api"/>
      <updated>2018-12-11T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-attributes-api</id>
      <content type="html"><![CDATA[<p>Rails 5 was a major release with a lot of new features like Action Cable, APIApplications, etc. Active Record attribute API was also one of the features ofRails 5 release which did not receive much attention.</p><p>Active Record attributes API is used by Rails internally for a long time. InRails 5 release, attributes API was made public and allowed support for customtypes.</p><h4>What is attribute API?</h4><p>Attribute API converts the attribute value to an appropriate Ruby type. Here ishow the syntax looks like.</p><pre><code class="language-ruby">attribute(name, cast_type, options)</code></pre><p>The first argument is the name of the attribute and the second argument is thecast type. Cast type can be <code>string</code>, <code>integer</code> or custom type object.</p><pre><code class="language-ruby"># db/schema.rbcreate_table :movie_tickets, force: true do |t|  t.float :priceend# without attribute APIclass MovieTicket &lt; ActiveRecord::Baseendmovie_ticket = MovieTicket.new(price: 145.40)movie_ticket.save!movie_ticket.price   # =&gt; Float(145.40)# with attribute APIclass MovieTicket &lt; ActiveRecord::Base  attribute :price, :integerendmovie_ticket.price   # =&gt; 145</code></pre><p>Before using attribute API, movie ticket price was a float value, but afterapplying attribute on price, the price value was typecast as integer.</p><p>The database still stores the price as float and this conversion happens only inRuby land.</p><p>Now, we will typecast movie <code>release_date</code> from <code>datetime</code> to <code>date</code> type.</p><pre><code class="language-ruby"># db/schema.rbcreate_table :movies, force: true do |t|  t.datetime :release_dateendclass Movie &lt; ActiveRecord::Base  attribute :release_date, :dateendmovie.release_date # =&gt; Thu, 01 Mar 2018</code></pre><p>We can also add default value for an attribute.</p><pre><code class="language-ruby"># db/schema.rbcreate_table :movies, force: true do |t|  t.string :license_number, :stringendclass Movie &lt; ActiveRecord::Base  attribute :license_number,            :string,            default: &quot;IN00#{Date.current.strftime('%Y%m%d')}00#{rand(100)}&quot;end# without attribute API with default value on license numberMovie.new.license_number  # =&gt; nil# with attribute API with default value on license numberMovie.new.license_number  # =&gt; &quot;IN00201805250068&quot;</code></pre><h4>Custom Types</h4><p>Let's say we want the people to rate a movie in percentage. Traditionally, wewould do something like this.</p><pre><code class="language-ruby">class MovieRating &lt; ActiveRecord::Base  TOTAL_STARS = 5  before_save :convert_percent_rating_to_stars  def convert_percent_rating_to_stars    rating_in_percentage = value.gsub(/\%/, '').to_f    self.rating = (rating_in_percentage * TOTAL_STARS) / 100  endend</code></pre><p>With attributes API we can create a custom type which will be responsible tocast to percentage rating to number of stars.</p><p>We have to define the <code>cast</code> method in the custom type class which casts thegiven value to the expected output.</p><pre><code class="language-ruby"># db/schema.rbcreate_table :movie_ratings, force: true do |t|  t.integer :ratingend# app/types/star_rating_type.rbclass StarRatingType &lt; ActiveRecord::Type::Integer  TOTAL_STARS = 5  def cast(value)    if value.present? &amp;&amp; !value.kind_of?(Integer)      rating_in_percentage = value.gsub(/\%/, '').to_i      star_rating = (rating_in_percentage * TOTAL_STARS) / 100      super(star_rating)    else      super    end  endend# config/initializers/types.rbActiveRecord::Type.register(:star_rating, StarRatingType)# app/models/movie.rbclass MovieRating &lt; ActiveRecord::Base  attribute :rating, :star_ratingend</code></pre><h4>Querying</h4><p>The attributes API also supports <code>where</code> clause. Query will be converted to SQLby calling <code>serialize</code> method on the type object.</p><pre><code class="language-ruby">class StarRatingType &lt; ActiveRecord::Type::Integer  TOTAL_STARS = 5  def serialize(value)    if value.present? &amp;&amp; !value.kind_of?(Integer)      rating_in_percentage = value.gsub(/\%/, '').to_i      star_rating = (rating_in_percentage * TOTAL_STARS) / 100      super(star_rating)    else      super    end  endend# Add new movie rating with rating as 25.6%.# So the movie rating in star will be 1 of 5 stars.movie_rating = MovieRating.new(rating: &quot;25.6%&quot;)movie_rating.save!movie_rating.rating   # =&gt; 1# Querying with rating in percentage 25.6%MovieRating.where(rating: &quot;25.6%&quot;)# =&gt; #&lt;ActiveRecord::Relation [#&lt;MovieRating id: 1000, rating: 1 ... &gt;]&gt;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Create module and class level variables]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-ability-to-create-module-and-class-level-variables-on-per-thread-basis"/>
      <updated>2016-09-05T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-ability-to-create-module-and-class-level-variables-on-per-thread-basis</id>
      <content type="html"><![CDATA[<p>Rails already provides methods for creating class level and module levelvariables in the form of<a href="http://guides.rubyonrails.org/active_support_core_extensions.html#cattr-reader-cattr-writer-and-cattr-accessor">cattr** and mattr** suite of methods</a>.</p><p>In Rails 5, we can go a step further and create<a href="https://github.com/rails/rails/pull/22630">thread specific class or module level variables</a>.</p><p>Here is an example which demonstrates an example on how to use it.</p><pre><code class="language-ruby">module CurrentScope  thread_mattr_accessor :user_permissionsendclass ApplicationController &lt; ActionController::Base  before_action :set_permissions  def set_permissions    user = User.find(params[:user_id])    CurrentScope.user_permissions = user.permissions  endend</code></pre><p>Now <code>CurrentScope.user_permissions</code> will be available till the lifetime ofcurrently executing thread and all the code after this point can use thisvariable.</p><p>For example, we can access this variable in any of the models without explicitlypassing <code>current_user</code> from the controller.</p><pre><code class="language-ruby">class BookingsController &lt; ApplicationController  def create    Booking.create(booking_params)  endendclass Booking &lt; ApplicationRecord  validate :check_permissions  private  def check_permissions    unless CurrentScope.user_permissions.include?(:create_booking)      self.errors.add(:base, &quot;Not permitted to allow creation of booking&quot;)    end  endend</code></pre><p>It internally uses<a href="https://ruby-doc.org/core-2.3.0/Thread.html#method-i-5B-5D-3D">Thread.current#[]=</a>method, so all the variables are scoped to the thread currently executing. Itwill also take care of namespacing these variables per class or module so that<code>CurrentScope.user_permissions</code> and <code>RequestScope.user_permissions</code> will notconflict with each other.</p><p>If you have used<a href="http://api.rubyonrails.org/classes/ActiveSupport/PerThreadRegistry.html">PerThreadRegistry</a>before for managing global variables, <code>thread_mattr_*</code> &amp; <code>thread_cattr_*</code>methods can be used in place of it starting from Rails 5.</p><p>Globals are generally bad and should be avoided but this change provides nicerAPI if you want to fiddle with them anyway!</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 silences assets logs in dev mode by default]]></title>
       <author><name>Midhun Krishna</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-silences-assets-logs-in-development-mode-by-default"/>
      <updated>2016-09-02T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-silences-assets-logs-in-development-mode-by-default</id>
      <content type="html"><![CDATA[<p>As a Rails developer, it was a familiar sign to see assets logs flooding thewhole terminal in development mode.</p><pre><code class="language-plaintext">Started GET &quot;/assets/application.self-4a04ce68c5ebf2d39fba46316802f17d0a73fadc4d2da50a138d7a4bf2d26a84.css?body=1&quot; for 127.0.0.1 at 2016-09-02 10:23:04 +0530Started GET &quot;/assets/bootstrap/transition.self-6ad2488465135ab731a045a8ebbe3ea2fc501aed286042496eda1664fdd07ba9.js?body=1&quot; for 127.0.0.1 at 2016-09-02 10:23:04 +0530Started GET &quot;/assets/bootstrap/collapse.self-2eb697f62b587bb786ff940d82dd4be88cdeeaf13ca128e3da3850c5fcaec301.js?body=1&quot; for 127.0.0.1 at 2016-09-02 10:23:04 +0530Started GET &quot;/assets/jquery_ujs.self-e87806d0cf4489aeb1bb7288016024e8de67fd18db693fe026fe3907581e53cd.js?body=1&quot; for 127.0.0.1 at 2016-09-02 10:23:04 +0530Started GET &quot;/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1&quot; for 127.0.0.1 at 2016-09-02 10:23:04 +0530</code></pre><p>Fortunately, we could include <code>quiet_assets</code> gem in our application. It turnsoff the Rails asset pipeline log in development mode.</p><pre><code class="language-plaintext">Started GET &quot;/assets/application.js&quot; for 127.0.0.1 at 2016-08-28 19:35:34</code></pre><h3>quiet_assets is part of Rails 5</h3><p>Now quiet_assets gem is folded into Rails 5 itself.</p><p>A new configuration <code>config.assets.quiet</code> which when set to <code>true</code>,<a href="https://github.com/rails/sprockets-rails/pull/355">loads a rack middleware named Sprockets::Rails::QuietAssets</a>.This middleware checks whether the current request matches assets prefix pathand if it does, it silences that request.</p><p>This eliminates the need to add external gem for this.</p><p>By default,<a href="https://github.com/rails/rails/pull/25351"><code>config.assets.quiet</code> is set to <code>true</code></a>in development mode. So we don't have to do anything. It just works out of thebox.</p><h3>Compatibility with older versions of Rails</h3><p>This functionality has been backported to sprockets-rails 3.1.0 and is availablein <a href="https://github.com/rails/rails/pull/25397">Rails 4.2.7</a> as well.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 disables autoloading while app in production]]></title>
       <author><name>Shailesh Kalamkar</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-disables-autoloading-after-booting-the-app-in-production"/>
      <updated>2016-08-29T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-disables-autoloading-after-booting-the-app-in-production</id>
      <content type="html"><![CDATA[<p>This blog requires understanding of what is <code>autoloading</code>. If you are notfamiliar with that then please refer to<a href="http://guides.rubyonrails.org/autoloading_and_reloading_constants.html">Autoloading and Reloading Constants</a>article on Rails Guide.</p><h2>Eagerload paths</h2><p>Autoloading is <a href="https://github.com/rails/rails/issues/13142">not thread-safe</a>and hence we need to make sure that all constants are loaded when applicationboots. The concept of loading all the constants even before they are actuallyneeded is called &quot;Eager loading&quot;. In a way it is opposite of &quot;Autoloading&quot;. Inthe case of &quot;Autoloading&quot; the application does not load the constant until it isneeded. Once a class is needed and it is missing then the application startslooking in &quot;autoloading paths&quot; to load the missing class.</p><p><code>eager_load_paths</code> contains a list of directories. When application boots inproduction then the application loads all constants found in all directorieslisted in <code>eager_load_paths</code>.</p><p>We can add directories to <code>eager_load_paths</code> as shown below.</p><pre><code class="language-ruby"># config/application.rbconfig.eager_load_paths &lt;&lt; Rails.root.join('lib')</code></pre><h2>In Rails 5 autoloading is disabled for production environment by default</h2><p>With<a href="https://github.com/rails/rails/commit/a71350cae0082193ad8c66d65ab62e8bb0b7853b">this commit</a>Rails will no longer do Autoloading in production after it has booted.</p><p>Rails will load all the constants from <code>eager_load_paths</code> but if a constant ismissing then it will not look in <code>autoload_paths</code> and will not attempt to loadthe missing constant.</p><p>This is a breaking change for some applications. For vast majority of theapplications this should not be an issue.</p><p>In the rare situation where our application still needs autoloading in the<code>production</code> environment, we can enable it by setting up<code>enable_dependency_loading</code> to <code>true</code> as follows:</p><pre><code class="language-ruby"># config/application.rbconfig.enable_dependency_loading = trueconfig.autoload_paths &lt;&lt; Rails.root.join('lib')</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds more control to fine tuning SSL usage]]></title>
       <author><name>Srihari K</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-more-control-to-fine-tuning-ssl-usage"/>
      <updated>2016-08-24T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-more-control-to-fine-tuning-ssl-usage</id>
      <content type="html"><![CDATA[<p>Adding HTTPS support is one of the first steps towards enhancing the security ofa web application.</p><p>Even when a web app is available over <code>https</code>, some users may end up visitingthe <code>http</code> version of the app, losing the security <code>https</code> provides.</p><p>It is important to redirect users to the <code>https</code> URLs whenever possible.</p><h2>Forcing HTTPS in Rails</h2><p>We can force users to use HTTPS by setting <code>config.force_ssl = true</code>.</p><p>If we look at Rails source code, we can see that when we set<code>config.force_ssl = true</code>, a middleware <code>ActionDispatch::SSL</code>, is inserted intoour apps middleware stack :</p><pre><code class="language-ruby">if config.force_sslmiddleware.use ::ActionDispatch::SSL,config.ssl_optionsend</code></pre><p>This middleware, <code>ActionDispatch::SSL</code> is responsible for doing three things :</p><ol><li><p>Redirect all <code>http</code> requests to their <code>https</code> equivalents.</p></li><li><p>Set <code>secure</code> flag on cookies to tell browsers that these cookies must not besent for <code>http</code> requests.</p></li><li><p>Add HSTS headers to response.</p></li></ol><p>Let us go through each of these.</p><h3>Redirect all http requests to their https equivalents</h3><p>In Rails 5, we can configure the behavior of redirection using the <code>redirect</code>key in the <code>config.ssl_options</code> configuration.</p><p>In previous versions of Rails, whenever an <code>http</code> request was redirected to<code>https</code> request, it was done with an HTTP <code>301</code> redirect.</p><p>Browsers cache 301 redirects. When forcing https redirects, if at any point wewant to test the <code>http</code> version of the page, it would be hard to browse it,since the browser would redirect to the <code>https</code> version. Although this is thedesired behavior, this is a pain during testing and deploying.</p><p>Rails 5 lets us<a href="https://github.com/rails/rails/pull/21520">specify the status code for redirection</a>,which can be set to <code>302</code> or <code>307</code> for testing, and later to <code>301</code> when we areready for deployment to production.</p><p>We can specify the options for redirection in Rails 5 as follows :</p><pre><code class="language-ruby">...  config.force_ssl = true  config.ssl_options = {  redirect: { status: 307, port: 81 } }...</code></pre><p>If a redirect status is not specified, requests are redirected with a <code>301</code>status code.</p><p>There is an <a href="https://github.com/rails/rails/pull/23941">upcoming change</a> to makethe status code used for redirecting any non-GET, non-HEAD http requests to<code>307</code> by default.</p><p>Other options accepted by <code>ssl_options</code> under <code>redirect</code> key are <code>host</code> and<code>body</code> .</p><h3>Set secure flags on cookies</h3><p>By setting the <code>Secure</code> flag on a cookie, the application can instruct thebrowser not to send the cookie in clear text. Browsers which support this flagwill send such cookies only through <code>HTTPS</code> connections.</p><p>Setting secure flag on cookies is important to prevent cookie hijacking by<a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">man in the middle attacks</a>.</p><p>In case of a &quot;man in the middle&quot; attack, the attacker places oneself between theuser and the server. By doing this, attacker aims to collect cookies which aresent from user to server on every request. However, if we mark the cookies withsensitive information as <code>Secure</code>, those cookies won't be sent on <code>http</code>requests. This ensures that the browser never sends cookies to an attacker whowas impersonating the webserver at an <code>http</code> end point.</p><p>Upon enabling <code>config.force_ssl = true</code>, the <code>ActionDispatch::SSL</code> middlewaresets the <code>Secure</code> flag on all cookies by default.</p><h3>Set HSTS Headers on Responses</h3><p><a href="https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security">HSTS</a> or &quot;HTTPStrict Transport Security&quot; is a security enhancement by which applications canspecify themselves as HTTPS-only to complying browsers.</p><p>HSTS capabilities of a browser can be used by sending appropriate responseheaders from the server. When a domain is added to the HSTS list of a browser,the browser redirects to the <code>https</code> version of the URL without the help of theserver.</p><p>Chrome maintains an <a href="https://hstspreload.appspot.com/">HSTS Preload List</a> with alist of domains which are hardcoded into chrome as HTTPS only. This list is alsoused by Firefox and Safari.</p><p>Rails 5 has a configuration flag to set the <code>preload</code> directive in the HSTSheader and can be used as follows :</p><pre><code class="language-ruby">config.ssl_options = { hsts: { preload: true } }</code></pre><p>We can also specify a <code>max-age</code> for the HSTS header.</p><p>Rails 5 by default sets the <code>max-age</code> of HSTS header to 180 days, which isconsidered as the lower bound by<a href="https://www.ssllabs.com/ssltest">SSL Labs SSL Test</a> . This period is alsoabove the 18 week requirement for HSTS <code>max-age</code> mandated for inclusion inbrowser preload list.</p><p>We can specify a custom max-age by :</p><pre><code class="language-ruby">  config.ssl_options = { hsts: { expires: 10.days } }</code></pre><p>In Rails 5, if we disable HSTS by setting :</p><pre><code class="language-ruby">config.ssl_options = { hsts: false }</code></pre><p>Rails 5 will set the value of expires header to 0, so that browsers immediatelystop treating the domain as HTTPS-only.</p><p>With custom redirect status and greater control over the HSTS header, Rails 5lets us roll out <code>HTTPS</code> in a controlled manner, and makes rolling back of thesechanges easier.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Discard some flash messages to trim storage]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-trims-session-storage-by-discarding-some-flash-messages"/>
      <updated>2016-08-23T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-trims-session-storage-by-discarding-some-flash-messages</id>
      <content type="html"><![CDATA[<p>Rails, by default, stores session data in cookies.</p><p>The cookies have a storage limit of 4K and cookie overflow exception is raisedif we attempt to store more than 4K of data in it.</p><h3>Cookie overflow issue with Rails 4.x</h3><p>Flash messages are persisted across requests with the help of session storage.</p><p>Flash messages like <code>flash.now</code> are marked as discarded for next request. So, onnext request, it gets deleted before reconstituting the values.</p><p>This unnecessary storage of discarded flash messages leads to more consumptionof data in the cookie store. When the data exceeds 4K limit, Rails throws<code>ActionDispatch::Cookies::CookieOverflow</code>.</p><p>Let us see an example below to demonstrate this.</p><pre><code class="language-ruby">class TemplatesController &lt; ApplicationControllerdef search@templates = Template.search(params[:search])flash.now[:notice] = &quot;Your search results for #{params[:search]}&quot;flash[:alert] = &quot;Alert message&quot;p session[:flash]endend#logs{&quot;discard&quot;=&gt;[&quot;notice&quot;],&quot;flashes&quot;=&gt;{&quot;notice&quot;=&gt;&quot;Your search results for #{Value of search params}&quot;,&quot;alert&quot;=&gt;&quot;Alert message&quot;}}</code></pre><p>In the above example, it might be possible that <code>params[:search]</code> is largeamount of data and it causes Rails to raise <code>CookieOverflow</code> as the sessionpersists both <code>flash.now[:notice]</code> and <code>flash[:alert]</code> .</p><h3>Rails 5 removes discarded flash messages</h3><p>In Rails 5,<a href="https://github.com/rails/rails/pull/18721">discarded flash messages are removed</a>before persisting into the session leading to less consumption of space andhence, fewer chances of <code>CookieOverflow</code> being raised.</p><pre><code class="language-ruby">class TemplatesController &lt; ApplicationControllerdef search@templates = Template.search(params[:search], params[:template])flash.now[:notice] = &quot;Your search results for #{params[:search]} with template #{params[:template]}&quot;flash[:alert] = &quot;Alert message&quot;p session[:flash]endend#logs{&quot;discard&quot;=&gt;[], &quot;flashes&quot;=&gt;{&quot;alert&quot;=&gt;&quot;Alert message&quot;}}</code></pre><p>We can see from above example, that <code>flash.now</code> value is not added in session inRails 5 leading to less chances of raising<code>ActionDispatch::Cookies::CookieOverflow</code>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 deprecates alias_method_chain]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-deprecates-alias-method-chain"/>
      <updated>2016-08-21T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-deprecates-alias-method-chain</id>
      <content type="html"><![CDATA[<p>Rails 5 has<a href="https://github.com/rails/rails/pull/19434">deprecated usage of alias_method_chain</a>in favor of Ruby's built-in method <code>Module#prepend</code>.</p><h2>What is alias_method_chain and when to use it</h2><p>A lot of good articles have been written by some very smart people on the topicof &quot;alias_method_chain&quot;. So we will not be attempting to describe it here.</p><p><a href="https://ernie.io">Ernier Miller</a> wrote<a href="https://ernie.io/2011/02/03/when-to-use-alias_method_chain/">When to use alias_method_chain</a>more than five years ago but it is still worth a read.</p><h2>Using Module#prepend to solve the problem</h2><p>Ruby 2.0 introduced <code>Module#prepend</code> which allows us to insert a module beforethe class in the class ancestor hierarchy.</p><p>Let's try to solve the same problem using <code>Module#prepend</code>.</p><pre><code class="language-ruby">module Flanderizer  def hello    &quot;#{super}-diddly&quot;  endendclass Person  def hello    &quot;Hello&quot;  endend# In ruby 2.0Person.send(:prepend, Flanderizer)# In ruby 2.1Person.prepend(Flanderizer)flanders = Person.newputs flanders.hello #=&gt; &quot;Hello-diddly&quot;</code></pre><p>Now we are back to being nice to our neighbor which should make Ernie happy.</p><p>Let's see what the ancestors chain looks like.</p><pre><code class="language-ruby">flanders.class.ancestors # =&gt; [Flanderizer, Person, Object, Kernel]</code></pre><p>In Ruby 2.1 both <code>Module#include</code> and <code>Module#prepend</code> became a public method.In the above example we have shown both Ruby 2.0 and Ruby 2.1 versions.</p>]]></content>
    </entry><entry>
       <title><![CDATA[New framework defaults in Rails 5 to make upgrade easier]]></title>
       <author><name>Srihari K</name></author>
      <link href="https://www.bigbinary.com/blog/new-framework-defaults-in-rails-5-to-make-upgrade-easier"/>
      <updated>2016-08-18T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/new-framework-defaults-in-rails-5-to-make-upgrade-easier</id>
      <content type="html"><![CDATA[<p>When a new version of Rails comes out, one of the pain points is upgradingexisting apps to the latest version.</p><p>A Rails upgrade can be boiled down to following essential steps :</p><ol><li>Have a green build</li><li>Update the Rails version in Gemfile and bundle</li><li>Run the update task to update configuration files</li><li>Run tests and sanity checks to see if anything is broken by the upgrade andfix the issues</li><li>Repeat step 4!</li></ol><p>Rails 5 comes with a lot of new features. Some of them, like<a href="rails-5-does-not-halt-callback-chain-when-false-is-returned">not halting the callback chain when a callback returns false</a>,are breaking changes for older apps.</p><p>To keep the upgrade process easier, Rails 5 has added feature flags for all ofthese breaking changes.</p><p>When we create a brand new Rails 5 app, all of the feature flags will be turnedon. We can see these feature flags in<a href="https://github.com/rails/rails/pull/25231"><code>config/initializers/new_framework_defaults.rb</code> file</a>.</p><p>But when we upgrade an app to Rails 5, just updating the Gemfile and bundling isnot enough.</p><p>We need to run the <code>bin/rails app:update</code> task which will update fewconfigurations and also add <code>config/initializers/new_framework_defaults.rb</code>file.</p><p>Rails will turn off all the feature flags in the<code>config/initializers/new_framework_defaults.rb</code> file while upgrading an olderapp. In this way our app won't break due to the breaking features.</p><p>Lets take a look at these configuration flags one by one.</p><h4>Enable per-form CSRF tokens</h4><p>Starting from Rails 5,<a href="per-form-csrf-token-in-rails-5">each form will get its own CSRF token</a>. Thischange will have following feature flag.</p><pre><code class="language-ruby">Rails.application.config.action_controller.per_form_csrf_tokens</code></pre><p>For new apps, it will be set to <code>true</code> and for older apps upgraded to Rails 5,it will be set to <code>false</code>. Once we are ready to use this feature in our upgradedapp, we just need to change it to <code>true</code>.</p><h4>Enable HTTP Origin Header checking for CSRF mitigation</h4><p>For additional defense against CSRF attacks, Rails 5 has a feature to check HTTPOrigin header against the site's origin. This will be disabled by default inupgraded apps using the following configuration option:</p><pre><code class="language-ruby">Rails.application.config.action_controller.forgery_protection_origin_check</code></pre><p>We can set it to <code>true</code> to enable HTTP origin header check when we are ready touse this feature.</p><h4>Make Ruby 2.4 preserve the timezone of the receiver</h4><p>In Ruby 2.4 the <code>to_time</code> method for both<a href="https://bugs.ruby-lang.org/issues/12271"><code>DateTime</code> and <code>Time</code> will preserve the timezone of the receiver</a><a href="https://bugs.ruby-lang.org/issues/12189">when converting to an instance of <code>Time</code></a>.For upgraded apps, this feature is disabled by setting the followingconfiguration option to <code>false</code> :</p><pre><code class="language-ruby">ActiveSupport.to_time_preserves_timezone</code></pre><p>To use the Ruby 2.4+ default of <code>to_time</code>, set this to <code>true</code> .</p><h4>Require <code>belongs_to</code> associations by default</h4><p>In Rails 5, when we define a <code>belongs_to</code> association,<a href="rails-5-makes-belong-to-association-required-by-default">the association record is required to be present</a>.</p><p>In upgraded apps, this validation is not enabled. It is disabled using thefollowing option:</p><pre><code class="language-ruby">Rails.application.config.active_record.belongs_to_required_by_default</code></pre><p>We can update our code to use this feature and turn this on by changing theabove option to <code>true</code>.</p><h4>Do not halt callback chain when a callback returns false</h4><p>In Rails 5,<a href="rails-5-does-not-halt-callback-chain-when-false-is-returned">callback chain is not halted when a callback returns false</a>.This change is turned off for backward compatibility with the following optionset to <code>true</code>:</p><pre><code class="language-ruby">ActiveSupport.halt_callback_chains_on_return_false</code></pre><p>We can use the new behavior of not halting the callback chain after making surethat our code does not break due to this change and changing the value of thisconfig to <code>false</code>.</p><h4>Configure SSL options to enable HSTS with subdomains</h4><p>HTTP Strict Transport Security or HSTS, is a web security policy mechanism whichhelps to protect websites against protocol downgrade attacks and cookiehijacking. Using HSTS, we can ask browsers to make connections using only HTTPS.In upgraded apps, HSTS is not enabled on subdomains. In new apps HSTS is enabledusing the following option :</p><pre><code class="language-ruby">Rails.application.config.ssl_options = { hsts: { subdomains: true } }</code></pre><p>Having all these backward incompatible features which can be turned on one byone after the upgrade, in one file, eases the upgrade process. This initializeralso has helpful comments explaining the features!</p><p>Happy Upgrading!</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Wildcard for specifying template dependencies]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-wildcard-for-specifying-template-dependencies"/>
      <updated>2016-08-17T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-wildcard-for-specifying-template-dependencies</id>
      <content type="html"><![CDATA[<h3>Cache Digests</h3><p>After cache digests were introduced in Rails, all calls to <code>#cache</code> in viewsautomatically append a digest of that template and all of its dependencies tothe cache key.</p><p>So developers no longer need to manually discard cache for the specifictemplates they make changes to.</p><pre><code class="language-ruby"># app/views/users/show.html.erb&lt;% cache user do %&gt;  &lt;h1&gt;All Posts&lt;/h1&gt;  &lt;%= render user.posts %&gt;&lt;% end %&gt;# app/views/posts/_post.html.erb&lt;% cache post do %&gt;  &lt;p&gt; &lt;%= post.content %&gt;&lt;/p&gt;  &lt;p&gt; &lt;%= post.created_at.to_s %&gt;  &lt;%= render 'posts/completed' %&gt;&lt;% end %&gt;</code></pre><p>This creates a caching key something like this<code>views/users/605416233-20129410191209/d9fb66b12bx8edf46707c67ab41d93cb2</code> whichdepends upon the template and its dependencies.</p><p>So, now if we change <code>posts/_completed.html.erb</code>, it will change cache key andthus it allows cache to expire automatically.</p><h3>Explicit dependencies</h3><p>As we saw in our earlier example, Rails was able to determine templatedependencies implicitly. But, sometimes it is not possible to determinedependencies at all.</p><p>Let's see an example below.</p><pre><code class="language-ruby"># app/views/users/show.html.erb&lt;% cache user do %&gt;  &lt;h1&gt;All Posts&lt;/h1&gt;  &lt;%= render user.posts %&gt;&lt;% end %&gt;# app/views/posts/_post.html.erb&lt;% cache post do %&gt;  &lt;p&gt; &lt;%= post.content %&gt;&lt;/p&gt;  &lt;p&gt; &lt;%= post.created_at.to_s %&gt;  &lt;%= render_post_complete_or_not(post) %&gt;&lt;% end %&gt;# app/helpers/posts_helper.rbmodule PostsHelper  def render_post_complete_or_not(post)    if post.completed?      render 'posts/complete'    else      render 'posts/incomplete'    end  endend</code></pre><p>To explicitly add dependency on this template, we need to add a<a href="http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html#method-i-cache-label-Explicit+dependencies">comment in special format</a>as follows.</p><pre><code class="language-ruby">  &lt;%# Template Dependency: posts/complete %&gt;  &lt;%# Template Dependency: posts/incomplete %&gt;</code></pre><p>If we have multiple dependencies, we need to add special comments for all thedependencies one by one.</p><pre><code class="language-ruby"># app/views/posts/_post.html.erb&lt;% cache post do %&gt;  &lt;p&gt; &lt;%= post.content %&gt;&lt;/p&gt;  &lt;p&gt; &lt;%= post.created_at.to_s %&gt;  &lt;%# Template Dependency: posts/complete %&gt;  &lt;%# Template Dependency: posts/incomplete %&gt;  &lt;%= render_post_complete_or_not(post) %&gt;&lt;% end %&gt;</code></pre><h3>Using Wildcard in Rails 5</h3><p>In Rails 5, we can now use a<a href="https://github.com/rails/rails/pull/20904">wildcard for adding dependencies</a> onmultiple files in a directory. So, instead of adding files one by one we can adddependency using wildcard.</p><pre><code class="language-ruby"># app/views/posts/_post.html.erb&lt;% cache post do %&gt;  &lt;p&gt; &lt;%= post.content %&gt;&lt;/p&gt;  &lt;p&gt; &lt;%= post.created_at.to_s %&gt;  &lt;%# Template Dependency: posts/* %&gt;  &lt;%= render_post_complete_or_not(post) %&gt;&lt;% end %&gt;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Passing records to fresh_when and stale?]]></title>
       <author><name>Ershad Kunnakkadan</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-supports-passing-collection-of-records-to-fresh_when-and-stale"/>
      <updated>2016-08-16T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-supports-passing-collection-of-records-to-fresh_when-and-stale</id>
      <content type="html"><![CDATA[<p>Rails has powerful tools to control<a href="http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html">caching of resources via HTTP</a>such as <code>fresh_when</code> and <code>stale?</code>.</p><p>Previously we could only pass a single record to these methods but now Rails 5adds support for accepting a collection of records as well. For example,</p><pre><code class="language-ruby">def index  @posts = Post.all  fresh_when(etag: @posts, last_modified: @posts.maximum(:updated_at))end</code></pre><p>or simply written as,</p><pre><code class="language-ruby">def index  @posts = Post.all  fresh_when(@posts)end</code></pre><p>This works with <code>stale?</code> method too, we can pass a collection of records to it.For example,</p><pre><code class="language-ruby">def index  @posts = Post.all  if stale?(@posts)    render json: @posts  endend</code></pre><p>To see this in action, let's begin by making a request at <code>/posts</code>.</p><pre><code class="language-bash">$ curl -I http://localhost:3000/postsHTTP/1.1 200 OKX-Frame-Options: SAMEORIGINX-XSS-Protection: 1; mode=blockX-Content-Type-Options: nosniffETag: W/&quot;a2b68b7a7f8c67f1b88848651a86f5f5&quot;Content-Type: text/html; charset=utf-8Cache-Control: max-age=0, private, must-revalidateX-Request-Id: 7c8457e7-9d26-4646-afdf-5eb44711fa7bX-Runtime: 0.074238</code></pre><p>In the second request, we would send the ETag in <code>If-None-Match</code> header to checkif the data has changed.</p><pre><code class="language-bash">$ curl -I -H 'If-None-Match: W/&quot;a2b68b7a7f8c67f1b88848651a86f5f5&quot;' http://localhost:3000/postsHTTP/1.1 304 Not ModifiedX-Frame-Options: SAMEORIGINX-XSS-Protection: 1; mode=blockX-Content-Type-Options: nosniffETag: W/&quot;a2b68b7a7f8c67f1b88848651a86f5f5&quot;Cache-Control: max-age=0, private, must-revalidateX-Request-Id: 6367b2a5-ecc9-4671-8a79-34222dc50e7fX-Runtime: 0.003756</code></pre><p>Since there's no change, the server returned <code>HTTP/1.1 304 Not Modified</code>. Ifthese requests were made from a browser, it would automatically use the versionin its cache on the second request.</p><p>The second request was obviously faster as the server was able to save the timeof fetching data and rendering it. This can be seen in Rails log,</p><pre><code class="language-plaintext">Started GET &quot;/posts&quot; for ::1 at 2016-08-06 00:39:44 +0530Processing by PostsController#index as HTML   (0.2ms)  SELECT MAX(&quot;posts&quot;.&quot;updated_at&quot;) FROM &quot;posts&quot;   (0.1ms)  SELECT COUNT(*) AS &quot;size&quot;, MAX(&quot;posts&quot;.&quot;updated_at&quot;) AS timestamp FROM &quot;posts&quot;  Rendering posts/index.html.erb within layouts/application  Post Load (0.2ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot;  Rendered posts/index.html.erb within layouts/application (2.0ms)Completed 200 OK in 31ms (Views: 27.1ms | ActiveRecord: 0.5ms)Started GET &quot;/posts&quot; for ::1 at 2016-08-06 00:39:46 +0530Processing by PostsController#index as HTML   (0.2ms)  SELECT MAX(&quot;posts&quot;.&quot;updated_at&quot;) FROM &quot;posts&quot;   (0.1ms)  SELECT COUNT(*) AS &quot;size&quot;, MAX(&quot;posts&quot;.&quot;updated_at&quot;) AS timestamp FROM &quot;posts&quot;Completed 304 Not Modified in 2ms (ActiveRecord: 0.3ms)</code></pre><p>Cache expires when collection of records is updated. For example, an addition ofa new record to the collection or a change in any of the records (which changes<code>updated_at</code>) would change the <code>ETag</code>.</p><p>Now that Rails 5 supports collection of records in <code>fresh_when</code> and <code>stale?</code>, wehave an improved system to cache resources and make our applications faster.This is more helpful when we have controller actions with time consuming dataprocessing logic.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Set model name in fixtures as metadata]]></title>
       <author><name>Srihari K</name></author>
      <link href="https://www.bigbinary.com/blog/set-model-name-in-fixtures-as-metadata"/>
      <updated>2016-08-09T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/set-model-name-in-fixtures-as-metadata</id>
      <content type="html"><![CDATA[<h2>Fixtures</h2><p>In Rails, for setting up test data we use fixtures. Fixtures are written as YAMLfiles placed in <code>test/fixtures</code> directory in the Rails app.</p><p>The model name of a fixture is automatically picked up from the fixture filename.</p><p>Generally in Rails, the model name and table name follow a strict convention.The table for <code>User</code> model will be <code>users</code>. By this convention, the fixture filefor <code>User</code> model is <code>test/fixtures/users.yml</code>.</p><p>But sometimes model names do not match directly with the table name. When we arebuilding on top of a legacy application or we have namespacing of models, wemight run into this scenario. In such cases detection of model name from fixturefile name becomes difficult.</p><p>When automatic detection of model name from fixture file name fails, we canspecify the table name using the<a href="http://api.rubyonrails.org/classes/ActiveRecord/TestFixtures/ClassMethods.html#method-i-set_fixture_class">set_fixture_class</a>method. Take a look at our older<a href="tricks-and-tips-for-using-fixtures-in-rails">blog</a> for an example of how to dothis.</p><p>One drawback of using this approach is that, the model name set using<code>set_fixture_class</code> is available only in the context of tests. When we run<code>rake db:fixtures:load</code> to load the fixtures, the tests are not run, and thefixture file is not associated with the model name we set using<code>set_fixture_class</code>. This will cause failure to load the fixtures correctly.</p><h2>The Rails 5 way</h2><p>In Rails 5 a new key is <a href="https://github.com/rails/rails/pull/20574">added</a> tospecify the model name for a fixture file.</p><p>Let us consider the example where our table was named <code>morning_appts</code>, and weused a more appropriately named model <code>MorningAppointment</code> to represent thistable.</p><p>We can now set the table name in our fixture file<code>test/fixtures/morning_appts.yml</code> as follows :</p><pre><code class="language-yaml">_fixture:  model_class: MorningAppointmentstandup:  name: Standup  priority: 1</code></pre><p>The special key <code>_fixture</code> in the fixture file is now used to store metadataabout the fixture. <code>model_class</code> is the key we can use to specify the model namefor the fixture.</p><p>We can now use this fixture to load test data using the rake task<code>rake db:fixtures:load</code> as well.</p><p>Happy Testing!</p>]]></content>
    </entry><entry>
       <title><![CDATA[ActionController::Parameters in Rails 5]]></title>
       <author><name>Rohit Arolkar</name></author>
      <link href="https://www.bigbinary.com/blog/parameters-no-longer-inherit-from-hash-with-indifferent-access-in-rails-5"/>
      <updated>2016-07-25T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/parameters-no-longer-inherit-from-hash-with-indifferent-access-in-rails-5</id>
      <content type="html"><![CDATA[<p>We are all guilty of treating <code>ActionController::Parameters</code> as a plain hash atsome point or the other. But with Rails 5, <code>ActionController::Parameters</code> willno longer inherit from <code>HashWithIndifferentAccess</code>.</p><p>Inheriting from <code>HashWithIndifferentAccess</code> allowed programmers to callenumerable methods over <code>ActionController::Parameters</code>, which caused<code>ActionController::Parameters</code> to lose its <code>@permitted</code> state there by renderingStrong Parameters as a barebone Hash. This<a href="https://github.com/rails/rails/pull/20868/commits/14a3bd520dd4bbf1247fd3e0071b59c02c115ce0">change</a>would discourage such operations.</p><p>However since this change would have meant a major impact on all of theupgrading applications as they would have crashed with a <code>NoMethodError</code>for allof those undesired methods. Hence this feature would go through a deprecationcycle, showing deprecation warnings for all of those <code>HashWithIndifferentAccess</code>method usages.</p><pre><code class="language-ruby">class Parameters...def method_missing(method_sym, *args, &amp;block)  if @parameters.respond_to?(method_sym)    message = &lt;&lt;-DEPRECATE.squish      Method #{method_sym} is deprecated and will be removed in Rails 5.1,      as `ActionController::Parameters` no longer inherits from      hash. Using this deprecated behavior exposes potential security      problems. If you continue to use this method you may be creating      a security vulnerability in your app that can be exploited. Instead,      consider using one of these documented methods which are not      deprecated: http://api.rubyonrails.org/v#{ActionPack.version}/classes/ActionController/Parameters.html    DEPRECATE    ActiveSupport::Deprecation.warn(message)    @parameters.public_send(method_sym, *args, &amp;block)  else    super  endend...end</code></pre><p>If you need to convert <code>ActionController::Parameters</code> in a true hash then itsupports <code>to_h</code> method. Also <code>ActionController::Parameters</code> will continue tohave methods like <code>fetch, slice, slice!, except, except!, extract!, delete</code> etc.You can take a detailed look at them<a href="https://github.com/rails/rails/blob/1a2f1c48bdeda5df88e8031fe51943527ebc381e/actionpack/lib/action_controller/metal/strong_parameters.rb">here</a>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 solves ambiguous column issue]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-fixes-ambiguous-cloumn-name-for-projected-fields-in-group-by-query"/>
      <updated>2016-07-21T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-fixes-ambiguous-cloumn-name-for-projected-fields-in-group-by-query</id>
      <content type="html"><![CDATA[<pre><code class="language-ruby">users(:id, :name)posts(:id, :title, :user_id)comments(:id, :description, :user_id, :post_id)&gt;&gt; Post.joins(:comments).group(:user_id).countMysql2::Error: Column 'user_id' in field list is ambiguous: SELECT COUNT(*) AS count_all, user_id AS user_id FROM `posts` INNER JOIN `comments` ON `comments`.`post_id` = `posts`.`id` GROUP BY user_id</code></pre><p>As we can see <code>user_id</code> has conflict in both <code>projection</code> and <code>GROUP BY</code> as theyare not prepended with the table name <code>posts</code> in the generated SQL and thus,raising SQL error <code>Column 'user_id' in field list is ambiguous</code>.</p><h2>Fix in Rails 5</h2><p>This issue has been addressed in Rails 5 with<a href="https://github.com/rails/rails/pull/21950">this pull request</a>.</p><p>With this fix, we can now <code>group by</code> columns having same name in both thetables.</p><pre><code class="language-ruby">users(:id, :name)posts(:id, :title, :user_id)comments(:id, :description, :user_id, :post_id)&gt;&gt; Post.joins(:comments).group(:user_id).countSELECT COUNT(*) AS count_all, &quot;posts&quot;.&quot;user_id&quot; AS posts_user_id FROM &quot;posts&quot; INNER JOIN &quot;comments&quot; ON &quot;comments&quot;.&quot;post_id&quot; = &quot;posts&quot;.&quot;id&quot; GROUP BY &quot;posts&quot;.&quot;user_id&quot;=&gt; { 1 =&gt; 1 }</code></pre><p>This shows that now both <code>projection</code> and <code>Group By</code> are prepended with the<code>posts</code> table name and hence fixing the conflict.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Expression Indexes & Operator Classes support]]></title>
       <author><name>Midhun Krishna</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-support-for-expression-indexes-for-postgresql"/>
      <updated>2016-07-20T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-support-for-expression-indexes-for-postgresql</id>
      <content type="html"><![CDATA[<p>Let's assume that in our health care application we have a page which shows allPatients. This page also has a filter and it allows us to filter patients bytheir name.</p><p>We could implement the filter as shown here.</p><pre><code class="language-ruby">Patient.where(&quot;lower(first_name) = ?&quot;, first_name.downcase)</code></pre><p>There might be many users with the same name. In such cases, to speed up thesearch process, we can add an index. But, adding a regular index will nottrigger an index scan since we are using an expression in the where clause i.e<code>lower(name)</code>. In such cases, we can leverage<a href="https://www.postgresql.org/docs/8.1/static/indexes-expressional.html">expression indexes given by PostgreSQL</a>.</p><p>Before Rails 5 adding an expression index is not straightforward since themigrate api does not support it. In order to add one we would need to ditch<code>schema.rb</code> and start using <code>structure.sql</code>. We would also need to add followingmigration.</p><pre><code class="language-ruby">def upexecute &lt;&lt;-SQLCREATE INDEX patient_lower_name_idx ON patients (lower(name));SQLenddef downexecute &lt;&lt;-SQLDROP INDEX patient_lower_name_idx;SQLend</code></pre><h2>Rails 5 adds support for expression indexes</h2><p>Rails 5 provides<a href="https://github.com/rails/rails/commit/edc2b7718725016e988089b5fb6d6fb9d6e16882">ability to add an expression index using add_index method</a>as follows:</p><pre><code class="language-ruby">def changeadd_index :patients,'lower(last_name)',name: &quot;index_patients_on_name_unique&quot;,unique: trueend</code></pre><p>And we also get to keep schema.rb.</p><p>Time goes on. everyone is happy with the search functionality until one day anew requirement comes along which is, in short, to have partial matches onpatient names.</p><p>We modify our search as follows:</p><pre><code class="language-ruby">User.where(&quot;lower(name) like ?&quot;, &quot;%#{name.downcase}%&quot;)</code></pre><p>Since the query is different from before, PostgreSQL query planner will not takethe already existing btree index into account and will revert to a sequentialscan.</p><p>Quoting directly from Postgresql documents,</p><pre><code class="language-plaintext">'The operator classes text_pattern_ops, varchar_pattern_ops, and bpchar_pattern_ops support B-tree indexes on the types text, varchar, and char respectively. The difference from the default operator classes is that the values are compared strictly character by character rather than according to the locale-specific collation rules. This makes these operator classes suitable for use by queries involving pattern matching expressions (LIKE or POSIX regular expressions) when the database does not use the standard &quot;C&quot; locale.'</code></pre><p>We need to add an operator class to the previous index for the query planner toutilize the index that we created earlier.</p><h2>Rails 5 adds support for specifying operator classes on expression indexes</h2><p>In order to add an index with an operator class we could write our migration asshown below.</p><pre><code class="language-ruby">def changeremove_index :patients, name: :index_patients_on_name_uniqueadd_index :patients, 'lower(last_name) varchar_pattern_ops',name: &quot;index_patients_on_name_unique&quot;,unique: trueend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Attach arbitrary metadata to an Active Job in Rails 5]]></title>
       <author><name>Midhun Krishna</name></author>
      <link href="https://www.bigbinary.com/blog/attach-arbitrary-metadata-to-an-active-job-in-rails-5"/>
      <updated>2016-07-18T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/attach-arbitrary-metadata-to-an-active-job-in-rails-5</id>
      <content type="html"><![CDATA[<p>Rails 4.2 came with built-in support for executing jobs in the background usingActive Job. Along with many enhancements to Active Job, Rails 5 provides theability to<a href="https://github.com/rails/rails/pull/18260">attach arbitrary metadata to any job</a>.</p><p>Consider the scenario where we would like to get notified when a job has failedfor more than three times. With the new enhancement, we can make it work byoverriding <code>serialize</code> and <code>deserialize</code> methods of the job class.</p><pre><code class="language-ruby">class DeliverWebhookJob &lt; ActiveJob::Base  def serialize    super.merge('attempt_number' =&gt; (@attempt_number || 0) + 1)  end  def deserialize(job_data)    super(job_data)    @attempt_number = job_data['attempt_number']  end  rescue_from(TimeoutError) do |ex|    notify_job_tried_x_times(@attempt_number) if @attempt_number == 3    retry_job(wait: 10)  endend</code></pre><p>Earlier, deserialization was performed by #deserialize class method andtherefore was inaccessible from the job instance. With the new changes,deserialization is delegated to the deserialize method on job instance therebyallowing it to attach arbitrary metadata when it gets serialized and read itback when it gets performed.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Partial template name without Ruby identifier Rails 5]]></title>
       <author><name>Prajakta Tambe</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-partial-template-name-need-not-be-a-valid-ruby-identifier"/>
      <updated>2016-07-14T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-partial-template-name-need-not-be-a-valid-ruby-identifier</id>
      <content type="html"><![CDATA[<p>Before Rails 5, partials name should start with underscore and should befollowed by any combination of letters, numbers and underscores.</p><p>This rule was required because before<a href="https://github.com/rails/rails/commit/c67005f221f102fe2caca231027d9b11cf630484">commit</a>,rendering a partial without giving <code>:object</code> or <code>:collection</code> used to generate alocal variable with the partial name by default and a variable name in rubycan't have dash and other things like that.</p><p>In the following case we have a file named <code>_order-details.html.erb</code>. Now let'stry to use this partial.</p><pre><code class="language-ruby">&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;  &lt;%= render :partial =&gt; 'order-details' %&gt;&lt;/body&gt;&lt;/html&gt;</code></pre><p>We will get following error, if we try to render above view in Rails 4.x.</p><pre><code class="language-ruby">ActionView::Template::Error (The partial name (order-details) is not a valid Ruby identifier;make sure your partial name starts with underscore,and is followed by any combination of letters, numbers and underscores.):2: &lt;html&gt;3: &lt;body&gt;4: Following code is rendered through partial named \_order-details.erb5: &lt;%= render :partial =&gt; 'order-details' %&gt;6: &lt;/body&gt;7: &lt;/html&gt;</code></pre><p>In the above the code failed because the partial name has a dash which is not avalid ruby variable name.</p><p>In Rails 5, we can give our<a href="https://github.com/rails/rails/commit/da9038e">partials any name which starts with underscore</a>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Passing current record for custom error]]></title>
       <author><name>Hitesh Rawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-passing-record-to-error-message-generator"/>
      <updated>2016-07-13T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-passing-record-to-error-message-generator</id>
      <content type="html"><![CDATA[<p><a href="http://guides.rubyonrails.org/active_record_validations.html">Active Record</a>validations by default provides an error messages, based on applied attributes.But some time we need to display a custom error message while validating arecord.</p><p>We can give custom error message by passing <code>String</code> or <code>Proc</code> to <code>:message</code>.</p><pre><code class="language-ruby">class Book &lt; ActiveRecord::Base  # error message with a string  validates_presence_of :title, message: 'You must provide the title of book.'  # error message with a proc  validates_presence_of :price,      :message =&gt; Proc.new { |error, attributes|      &quot;#{attributes[:key]} cannot be blank.&quot;      }end</code></pre><h2>What's new in Rails 5 ?</h2><p>Rails 5<a href="https://github.com/rails/rails/pull/24119">allows passing record to error message generator.</a>Now we can pass current record object in a proc as an argument, so that we canwrite custom error message based on current object.</p><p>Revised example with current record object.</p><pre><code class="language-ruby">class Book &lt; ActiveRecord::Base  # error message with simple string  validates_presence_of :title, message: 'You must provide the title of book.'  # error message with proc using current record object  validates_presence_of :price,      :message =&gt; Proc.new { |book, data|      &quot;You must provide #{data[:attribute]} for #{book.title}&quot;      }end</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Skip mailers while generating Rails 5 app]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/skip-mailers-while-generating-rails-5-app"/>
      <updated>2016-07-08T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/skip-mailers-while-generating-rails-5-app</id>
      <content type="html"><![CDATA[<p>We can now<a href="https://github.com/rails/rails/pull/18288">skip requiring Action Mailer</a> whilegenerating Rails 5 app.</p><pre><code class="language-bash">$ rails new my_app --skip-action-mailer# OR$ rails new my_app -M</code></pre><p>This comments out requiring <code>action_mailer/railtie</code> in <code>application.rb</code>.</p><p>It also omits mailer specific configurations such as<code>config.action_mailer.raise_delivery_errors</code> and<code>config.action_mailer.perform_caching</code> in <code>production/development</code> and<code>config.action_mailer.delivery_method</code> by default in <code>test</code> environment.</p><pre><code class="language-ruby"># application.rbrequire &quot;rails&quot;require &quot;active_model/railtie&quot;require &quot;active_job/railtie&quot;require &quot;active_record/railtie&quot;require &quot;action_controller/railtie&quot;# require &quot;action_mailer/railtie&quot;require &quot;action_view/railtie&quot;require &quot;action_cable/engine&quot;require &quot;sprockets/railtie&quot;require &quot;rails/test_unit/railtie&quot;</code></pre><p>As, we can see <code>action_mailer/railtie</code> is commented out.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Errors can be indexed with nested attributes in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/errors-can-be-indexed-with-nested-attrbutes-in-rails-5"/>
      <updated>2016-07-07T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/errors-can-be-indexed-with-nested-attrbutes-in-rails-5</id>
      <content type="html"><![CDATA[<p>We use <code>accepts_nested_attributes_for</code> when we want a single form to cater tomultiple models. By using this we can easily provide attributes for associatedmodels.</p><p>In Rails 4.x, if a validation fails for one or more of the associated models,then it is not possible to figure out from error message, which of theassociated model object is the error related to.</p><pre><code class="language-ruby">class Product &lt; ApplicationRecordhas_many :variantsaccepts_nested_attributes_for :variantsendclass Variant &lt; ApplicationRecordvalidates :display_name, :price, presence: trueend&gt; &gt; product = Product.new(name: 'Table')&gt; &gt; variant1 = Variant.new(price: 10)&gt; &gt; variant2 = Variant.new(display_name: 'Brown')&gt; &gt; product.variants = [variant1, variant2]&gt; &gt; product.save&gt; &gt; =&gt; false&gt; &gt; product.error.messages&gt; &gt; =&gt; {:&quot;variants.display_name&quot;=&gt;[&quot;can't be blank&quot;], :&quot;variants.price&quot;=&gt;[&quot;can't be blank&quot;]}</code></pre><p>In the example above we can see that if this error message is sent as JSON API,we cannot find out which variant save failed because of which attribute.</p><p>This works well when we render forms using Active Record models, as errors areavailable on individual instances. But, the issue arises with an API call, wherewe don't have access to these instances.</p><h2>Rails 5 allows indexing of errors on nested attributes</h2><p>In Rails 5, we can <a href="https://github.com/rails/rails/pull/19686">add an index</a> toerrors on nested models.</p><p>We can add the option <code>index_errors: true</code> to <code>has_many</code> association to enablethis behavior on individual association.</p><pre><code class="language-ruby">class Product &lt; ApplicationRecordhas_many :variants, index_errors: trueaccepts_nested_attributes_for :variantsendclass Variant &lt; ApplicationRecordvalidates :display_name, :price, presence: trueend&gt; &gt; product = Product.new(name: 'Table')&gt; &gt; variant1 = Variant.new(price: 10)&gt; &gt; variant2 = Variant.new(display_name: 'Brown')&gt; &gt; product.variants = [variant1, variant2]&gt; &gt; product.save&gt; &gt; =&gt; false&gt; &gt; product.error.messages&gt; &gt; =&gt; {:&quot;variants[0].display_name&quot;=&gt;[&quot;can't be blank&quot;], :&quot;variants[1].price&quot;=&gt;[&quot;can't be blank&quot;]}</code></pre><h2>Using global configuration</h2><p>In order to make this change global, we can set configuration<code>config.active_record.index_nested_attribute_errors = true</code> which is <code>false</code> bydefault.</p><pre><code class="language-ruby">config.active_record.index_nested_attribute_errors = trueclass Product &lt; ApplicationRecordhas_many :variantsaccepts_nested_attributes_for :variantsendclass Variant &lt; ApplicationRecordvalidates :display_name, :price, presence: trueend</code></pre><p>This will work exactly same as an example with<code>has_many :variants, index_errors: true</code> in <code>Product</code>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Conversion when deep munging params]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-does-not-convert-blank-array-to-nil-in-deep-munging"/>
      <updated>2016-07-06T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-does-not-convert-blank-array-to-nil-in-deep-munging</id>
      <content type="html"><![CDATA[<p>In older Rails version (&lt; 3.2), when an empty array was passed to a <code>where</code>clause or to a <code>find_by</code> query, it generated SQL with an <code>IS NULL</code> clause.</p><pre><code class="language-ruby">User.find_by_email([]).to_sql#=&gt; &quot;SELECT * FROM users WHERE email IS NULL&quot;User.find_by_email([nil]).to_sql#=&gt; &quot;SELECT * FROM users WHERE email IS NULL&quot;</code></pre><p>Also, when JSON data of the request was parsed and <code>params</code> got generated thedeep munging converted empty arrays to <code>nil</code>.</p><p>For example, When the following JSON data is posted to a Rails controller</p><pre><code class="language-javascript">{&quot;property_grouping&quot;:{&quot;project_id&quot;:289,&quot;name&quot;:&quot;test group2&quot;,&quot;property_ids&quot;:[]}}</code></pre><p>It gets converted into the following params in the controller.</p><pre><code class="language-javascript">{&quot;property_grouping&quot;=&gt;{&quot;project_id&quot;=&gt;289, &quot;name&quot;=&gt;&quot;test group2&quot;, &quot;property_ids&quot;=&gt;nil, },&quot;action&quot;=&gt;&quot;...&quot;, &quot;controller&quot;=&gt;&quot;...&quot;, &quot;format&quot;=&gt;&quot;json&quot;}</code></pre><p>This in combination with the fact that Active Record constructs <code>IS NULL</code> querywhen blank array is passed became one of the security threats and<a href="https://github.com/rails/rails/issues/13420">one of the most complained issues in Rails</a>.</p><p>The security threat we had was that it was possible for an attacker to issueunexpected database queries with &quot;IS NULL&quot; where clauses. Though there was nothreat of an insert being carried out, there could be scope for firing queriesthat would check for NULL even if it wasn't intended.</p><p>In later version of Rails(&gt; 3.2), we had a different way of handling blankarrays in Active Record <code>find_by</code> and <code>where</code> clauses.</p><pre><code class="language-ruby">User.find_by_email([]).to_sql#=&gt; &quot;SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE 1=0 LIMIT 1&quot;User.find_by_email([nil]).to_sql#=&gt; &quot;SELECT * FROM users WHERE email IS NULL&quot;</code></pre><p>As you can see a conditional for empty array doesn't trigger <code>IS NULL</code> query,which solved part of the problem.</p><p>We still had conversion of empty array to <code>nil</code> in the deep munging in place andhence there was still a threat of undesired behavior when request containedempty array.</p><p>One way to handle it was to add <code>before_action</code> hooks to the action that couldmodify the value to empty array if it were <code>nil</code>.</p><p>In Rails 5,<a href="https://github.com/rails/rails/pull/16924">empty array does not get converted to nil</a>in deep munging. With this change, the empty array will persist as is fromrequest to the <code>params</code> in the controller.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Specific mime types in controller tests in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/use-as-option-to-encode-request-with-specific-mime-type-in-rails-5"/>
      <updated>2016-07-05T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/use-as-option-to-encode-request-with-specific-mime-type-in-rails-5</id>
      <content type="html"><![CDATA[<p>Before Rails 5, while sending requests with integration test setup, we needed toadd <code>format</code> option to send request with different <code>Mime type</code>.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionController::TestCase  def test_create    post :create, { product: { name: 'Rails 5 book' } }.to_json,        format: :json,        headers: { 'Content-Type' =&gt; 'application/json' }    assert_equal 'application/json', request.content_type    assert_equal({ id: 1, name: 'Rails 5 book' }, JSON.parse(response.body))  endend</code></pre><p>This format for writing tests with <code>JSON</code> type is lengthy and needs too muchinformation to be passed to request as well.</p><h2>Improvement with Rails 5</h2><p>In Rails 5, we can provide <code>Mime type</code> while sending request by<a href="https://github.com/rails/rails/pull/21671">passing it with as option</a> and allthe other information like <code>headers</code> and format will be passed automatically.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionDispatch::IntegrationTest  def test_create    post products_url, params: { product: { name: 'Rails 5 book' } }, as: :json    assert_equal 'application/json', request.content_type    assert_equal({ 'id' =&gt; 1, 'name' =&gt; 'Rails 5 book' }, response.parsed_body)  endend</code></pre><p>As we can notice, we don't need to parse JSON anymore.</p><p>With changes in this <a href="https://github.com/rails/rails/pull/23597">PR</a>, we canfetch parsed response without needing to call <code>JSON.parse</code> at all.</p><h2>Custom Mime Type</h2><p>We can also register our own encoders for any registered <code>Mime Type</code>.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionDispatch::IntegrationTest  def setup    Mime::Type.register 'text/custom', :custom    ActionDispatch::IntegrationTest.register_encoder :custom,      param_encoder: -&gt; params { params.to_custom },      response_parser: -&gt; body { body }  end  def test_index    get products_url, params: { name: 'Rails 5 book' }, as: :custom    assert_response :success    assert_equal 'text/custom', request.content_type  endend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Default response with 204 No Content in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/controller-actions-default-no-content-in-rails-5-if-template-is-missing"/>
      <updated>2016-07-03T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/controller-actions-default-no-content-in-rails-5-if-template-is-missing</id>
      <content type="html"><![CDATA[<p>Before Rails 5, when we forget to add template for an action, we get<code>ActionView::MissingTemplate</code> exception.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  def index    @users = User.all  endendStarted GET &quot;/users&quot; for ::1 at 2016-06-10 17:10:40 +0530Processing by UsersController#index as HTMLCompleted 500 Internal Server Error in 5msActionView::MissingTemplate (Missing template users/index, application/index with {:locale=&gt;[:en], :formats=&gt;[:html], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby]}...</code></pre><p>Similarly, if we don't specify response for a POST request, we will also get<code>ActionView::MissingTemplate</code> exception.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  def create    @user = User.new(user_params)    @user.save  endend</code></pre><pre><code class="language-plaintext">Started POST &quot;/users&quot;Processing by UsersController#create as HTML  Parameters: {&quot;utf8&quot;=&gt;&quot;&quot;, &quot;user&quot;=&gt;{&quot;name&quot;=&gt;&quot;Max&quot;}, &quot;commit&quot;=&gt;&quot;Create User&quot;}   (0.1ms)  begin transaction  SQL (2.7ms)  INSERT INTO &quot;users&quot; (&quot;name&quot;, &quot;created_at&quot;, &quot;updated_at&quot;) VALUES (?, ?, ?)  [[&quot;name&quot;, &quot;Max&quot;], [&quot;created_at&quot;, 2016-06-10 12:29:09 UTC], [&quot;updated_at&quot;, 2016-06-10 12:29:09 UTC]]   (0.5ms)  commit transactionCompleted 500 Internal Server Error in 5msActionView::MissingTemplate (Missing template users/create, application/create with {:locale=&gt;[:en], :formats=&gt;[:html], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby]}...</code></pre><p>In Rails 5,<a href="https://github.com/rails/rails/pull/19377">if we don't specify response for an action then Rails returns <code>204: No content</code> response by default</a>.This change can cause some serious implications during the development phase ofthe app.</p><p>Let's see what happens with the POST request without specifying the response.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  def create    @user = User.new(user_params)    @user.save  endend</code></pre><pre><code class="language-plaintext">Started POST &quot;/users&quot;Processing by UsersController#create as HTML  Parameters: {&quot;utf8&quot;=&gt;&quot;&quot;, &quot;user&quot;=&gt;{&quot;name&quot;=&gt;&quot;Max&quot;}, &quot;commit&quot;=&gt;&quot;Create User&quot;}   (0.1ms)  begin transaction  SQL (2.7ms)  INSERT INTO &quot;users&quot; (&quot;name&quot;, &quot;created_at&quot;, &quot;updated_at&quot;) VALUES (?, ?, ?)  [[&quot;name&quot;, &quot;Max&quot;], [&quot;created_at&quot;, 2016-06-10 12:29:09 UTC], [&quot;updated_at&quot;, 2016-06-10 12:29:09 UTC]]   (0.5ms)  commit transactionNo template found for UsersController#create, rendering head :no_contentCompleted 204 No Content in 41ms (ActiveRecord: 3.3ms)</code></pre><p>Rails happily returns with <code>204: No content</code> response in this case.</p><p>This means users get the feel that nothing happened in the browser. BecauseRails returned with no content and browser happily accepted it. But in reality,the user record was created in the database.</p><p>Let's see what happens with the GET request in Rails 5.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  def index    @users = User.all  endend</code></pre><pre><code class="language-plaintext">ActionController::UnknownFormat (UsersController#index is missing a template for this request format and variant.request.formats: [&quot;text/html&quot;]request.variant: []NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.):</code></pre><p>Instead of <code>204: No Content</code>, we get<a href="https://github.com/rails/rails/pull/23827"><code>ActionController::UnknownFormat</code> exception</a>.Rails is being extra smart here and hinting that we are probably missingcorresponding template for this controller action. It is smart enough to show usthis message as we requested this page via browser via a GET request. But if thesame request is made via Ajax or through an API call or a POST request, Railswill return <code>204: No Content</code> response as seen before.</p><p>In general, this change can trip us in the development phase, as we are used toincremental steps like adding a route, then the controller action and then thetemplate or response. Getting 204 response can give a feel of nothing happeningwhere things have actually happened in the background. So don't forget torespond properly from your controller actions.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 ensures compatibility with Rack frameworks]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-ensures-compatibility-between-action-dispatch-session-and-rack-session"/>
      <updated>2016-06-30T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-ensures-compatibility-between-action-dispatch-session-and-rack-session</id>
      <content type="html"><![CDATA[<p>Before Rails 5,<a href="https://github.com/rails/rails/issues/15843">there were errors in running integration tests</a>when a Rack framework like <code>Sinatra</code>, <code>Grape</code> etc. were mounted within Railswith a motive of using its session.</p><p>Problems were reported at many places including<a href="https://gist.github.com/toolmantim/9597022">github gists</a> and<a href="http://stackoverflow.com/questions/22439361/rspec-testing-api-with-rack-protection">stackoverflow</a>regarding an error which was of the following form.</p><pre><code class="language-plaintext">NoMethodError (undefined method `each' for #&lt;ActionDispatch::Request::Session:0x7fb8dbe7f838 not yet loaded&gt;): rack (1.5.2) lib/rack/session/abstract/id.rb:158:in `stringify_keys'rack (1.5.2) lib/rack/session/abstract/id.rb:95:in `update' rack (1.5.2) lib/rack/session/abstract/id.rb:258:in `prepare_session'rack (1.5.2) lib/rack/session/abstract/id.rb:224:in `context' rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'</code></pre><p>As we can see, the error occurs due to absence of method <code>each</code> on an<code>ActionDispatch::Request::Session</code> object.</p><p>In Rails 5, <code>each</code> method<a href="https://github.com/rails/rails/pull/24820">was introduced to ActionDispatch::Request::Session</a>class making it compatible with Rack frameworks mounted in Rails and henceavoiding the above mentioned errors in integration testing.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 supports logging errors with tagged logging]]></title>
       <author><name>Sharang Dashputre</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-supports-logging-errors-with-tagged-logging"/>
      <updated>2016-06-28T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-supports-logging-errors-with-tagged-logging</id>
      <content type="html"><![CDATA[<p>We use<a href="http://guides.rubyonrails.org/debugging_rails_applications.html#tagged-logging">tagged logging</a>to better extract information from logs generated by Rails applications.</p><p>Consider a Rails 4.x application where the request id is used as a log tag byadding following in <code>config/environments/production.rb</code>.</p><pre><code class="language-ruby">config.log_tags = [:uuid]</code></pre><p>The log generated for that application would look like:</p><pre><code class="language-ruby">[df88dbaa-50fd-4178-85d7-d66279ea33b6] Started GET &quot;/posts&quot; for ::1 at 2016-06-03 17:19:32 +0530[df88dbaa-50fd-4178-85d7-d66279ea33b6] Processing by PostsController#index as HTML[df88dbaa-50fd-4178-85d7-d66279ea33b6]   Post Load (0.2ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot;[df88dbaa-50fd-4178-85d7-d66279ea33b6]   Rendered posts/index.html.erb within layouts/application (4.8ms)[df88dbaa-50fd-4178-85d7-d66279ea33b6] Completed 500 Internal Server Error in 10ms (ActiveRecord: 0.2ms)[df88dbaa-50fd-4178-85d7-d66279ea33b6]ActionView::Template::Error (divided by 0):    29: &lt;br&gt;    30:    31: &lt;%= link_to 'New Post', new_post_path %&gt;    32: &lt;%= 1/0 %&gt;  app/views/posts/index.html.erb:32:in `/'  app/views/posts/index.html.erb:32:in `_app_views_posts_index_html_erb___110320845380431566_70214104632140'</code></pre><p>As we can see the request id tag is not prepended to the lines containing errordetails. If we search the log file by the request id then the error detailswould not be shown.</p><p>In Rails 5<a href="https://github.com/rails/rails/pull/23203">errors in logs show log tags as well</a>to overcome the problem we saw above.</p><p>Please note that the log tag name for request id has changed in Rails 5. Thesetting would thus look like as shown below.</p><pre><code class="language-ruby">config.log_tags = [:request_id]</code></pre><p>This is how the same log will look like in a Rails 5 application.</p><pre><code class="language-ruby">[7efb4d18-8e55-4d51-b31e-119f49f5a410] Started GET &quot;/&quot; for ::1 at 2016-06-03 17:24:59 +0530[7efb4d18-8e55-4d51-b31e-119f49f5a410] Processing by PostsController#index as HTML[7efb4d18-8e55-4d51-b31e-119f49f5a410]   Rendering posts/index.html.erb within layouts/application[7efb4d18-8e55-4d51-b31e-119f49f5a410]   Post Load (0.9ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot;[7efb4d18-8e55-4d51-b31e-119f49f5a410]   Rendered posts/index.html.erb within layouts/application (13.2ms)[7efb4d18-8e55-4d51-b31e-119f49f5a410] Completed 500 Internal Server Error in 30ms (ActiveRecord: 0.9ms)[7efb4d18-8e55-4d51-b31e-119f49f5a410][7efb4d18-8e55-4d51-b31e-119f49f5a410] ActionView::Template::Error (divided by 0):[7efb4d18-8e55-4d51-b31e-119f49f5a410]     29: &lt;br&gt;[7efb4d18-8e55-4d51-b31e-119f49f5a410]     30:[7efb4d18-8e55-4d51-b31e-119f49f5a410]     31: &lt;%= link_to 'New Post', new_post_path %&gt;[7efb4d18-8e55-4d51-b31e-119f49f5a410]     32: &lt;%= 1/0 %&gt;[7efb4d18-8e55-4d51-b31e-119f49f5a410][7efb4d18-8e55-4d51-b31e-119f49f5a410] app/views/posts/index.html.erb:32:in `/'[7efb4d18-8e55-4d51-b31e-119f49f5a410] app/views/posts/index.html.erb:32:in `_app_views_posts_index_html_erb___1136362343261984150_70232665530320'</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 makes sql statements even more colorful]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-makes-sql-statements-even-more-colorful"/>
      <updated>2016-06-27T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-makes-sql-statements-even-more-colorful</id>
      <content type="html"><![CDATA[<p>In Rails 5, SQL statements have<a href="https://github.com/rails/rails/pull/20607">much more granular level of coloration</a>.</p><h3>INSERT statement</h3><p>Font color for <code>INSERT</code> command is green</p><p><img src="/blog_images/2016/rails-5-makes-sql-statements-even-more-colorful/insert-coloration.png" alt="insert statement in green color"></p><h3>UPDATE and SELECT statement</h3><p>Font color for <code>UPDATE</code> command is yellow and for <code>SELECT</code> it is blue.</p><p><img src="/blog_images/2016/rails-5-makes-sql-statements-even-more-colorful/update-coloration.png" alt="update statement in yellow color"></p><h3>DELETE statement</h3><p>Font color for <code>DELETE</code> command is red.</p><p><img src="/blog_images/2016/rails-5-makes-sql-statements-even-more-colorful/delete-coloration.png" alt="delete statement in red color"></p><p>As you might have noticed from above that font color for <code>transaction</code> is cyan.</p><h3>Rollback statement</h3><p>Font color for <code>Rollback transaction</code> is red.</p><p><img src="/blog_images/2016/rails-5-makes-sql-statements-even-more-colorful/rollback-coloration.png" alt="rollback statement in red color"></p><h3>Other statements</h3><p>For <a href="https://github.com/rails/rails/pull/20921">custom SQL statements color</a> ismagenta and Model Load/exists color is cyan.</p><p><img src="/blog_images/2016/rails-5-makes-sql-statements-even-more-colorful/misc-coloration.png" alt="magenta"></p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds helpers method in controllers for ease]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-add-helpers-method-to-ease-usage-of-helper-modules-in-controllers"/>
      <updated>2016-06-26T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-add-helpers-method-to-ease-usage-of-helper-modules-in-controllers</id>
      <content type="html"><![CDATA[<p>Before Rails 5, when we wanted to use any of the helper methods in controllerswe used to do the following.</p><pre><code class="language-ruby">module UsersHelper  def full_name(user)    user.first_name + user.last_name  endendclass UsersController &lt; ApplicationController  include UsersHelper  def update    @user = User.find params[:id]    if @user.update_attributes(user_params)      redirect_to user_path(@user), notice: &quot;#{full_name(@user) is successfully updated}&quot;    else      render :edit    end  endend</code></pre><p>Though this works, it adds all public methods of the included helper module inthe controller.</p><p>This can lead to some of the methods in the helper module conflict with themethods in controllers.</p><p>Also if our helper module has dependency on other helpers, then we need toinclude all of the dependencies in our controller, otherwise it won't work.</p><h2>New way to call helper methods in Rails 5</h2><p>In Rails 5, by using<a href="https://github.com/rails/rails/pull/24866">the new instance level helpers method</a>in the controller, we can access helper methods in controllers.</p><pre><code class="language-ruby">module UsersHelper  def full_name(user)    user.first_name + user.last_name  endendclass UsersController &lt; ApplicationController  def update    @user = User.find params[:id]    if @user.update_attributes(user_params)      notice = &quot;#{helpers.full_name(@user) is successfully updated}&quot;      redirect_to user_path(@user), notice: notice    else      render :edit    end  endend</code></pre><p>This removes some of the drawbacks of including helper modules and is muchcleaner solution.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 supports adding comments in migrations]]></title>
       <author><name>Prajakta Tambe</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-supports-adding-comments-migrations"/>
      <updated>2016-06-21T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-supports-adding-comments-migrations</id>
      <content type="html"><![CDATA[<p>Database schemas change rapidly as project progresses. And it can be difficultto track purpose of each table and each column in a large project with multipleteam members.</p><p>The solution for this problem is to document data models right from Railsmigrations.</p><h3>Solution in Rails 4</h3><p>You can add comments in Rails 4.x migrations using gems like<a href="https://github.com/pinnymz/migration_comments">migration_comments</a> and<a href="https://github.com/albertosaurus/pg_comment">pg_comment</a>.</p><h3>Solution in Rails 5</h3><p>Rails 5 <a href="https://github.com/rails/rails/pull/22911">allows to specify comments</a>for tables, column and indexes in migrations.</p><p>These comments are stored in database itself.</p><p>Currently only MySQL and PostgreSQL supports adding comments.</p><p>We can add comments in migration as shown below.</p><pre><code class="language-ruby">class CreateProducts &lt; ActiveRecord::Migration[5.0]  def change    create_table :products, comment: 'Products table' do |t|      t.string :name, comment: 'Name of the product'      t.string :barcode, comment: 'Barcode of the product'      t.string :description, comment: 'Product details'      t.float :msrp, comment: 'Maximum Retail Price'      t.float :our_price, comment: 'Selling price'      t.timestamps    end    add_index :products, :name,              name: 'index_products_on_name',              unique: true,              comment: 'Index used to lookup product by name.'  endend</code></pre><p>When we run above migration output will look as shown below.</p><pre><code class="language-ruby">  rails_5_app rake db:migrate:up VERSION=20160429081156== 20160429081156 CreateProducts: migrating ===================================-- create_table(:products, {:comment=&gt;&quot;Products table&quot;})   -&gt; 0.0119s-- add_index(:products, :name, {:name=&gt;&quot;index_products_on_name&quot;, :unique=&gt;true, :comment=&gt;&quot;Index used to lookup product by name.&quot;})   -&gt; 0.0038s== 20160429081156 CreateProducts: migrated (0.0159s) ==========================</code></pre><p>The comments are also dumped in <code>db/schema.rb</code> file for PostgreSQL and MySQL.</p><p><code>db/schema.rb</code> of application will have following content after running<code>products</code> table migration .</p><pre><code class="language-ruby">ActiveRecord::Schema.define(version: 20160429081156) do  # These are extensions that must be enabled in order to support this database  enable_extension &quot;plpgsql&quot;  create_table &quot;products&quot;, force: :cascade, comment: &quot;Products table&quot; do |t|      t.string   &quot;name&quot;,                     comment: &quot;Name of the product&quot;      t.string   &quot;barcode&quot;,                  comment: &quot;Barcode of the product&quot;      t.string   &quot;description&quot;,              comment: &quot;Product details&quot;      t.float    &quot;msrp&quot;,                     comment: &quot;Maximum Retail Price&quot;      t.float    &quot;our_price&quot;,                comment: &quot;Selling price&quot;      t.datetime &quot;created_at&quot;,  null: false      t.datetime &quot;updated_at&quot;,  null: false      t.index [&quot;name&quot;], name: &quot;index_products_on_name&quot;, unique: true, using: :btree, comment: &quot;Index used to lookup product by name.&quot;    endend</code></pre><p>We can view these comments with Database Administration Tools such as MySQLWorkbench or PgAdmin III.</p><p>PgAdmin III will show database structure with comments as shown below.</p><pre><code class="language-plaintext">-- Table: products-- DROP TABLE products;CREATE TABLE products(  id serial NOT NULL,  name character varying, -- Name of the product  barcode character varying, -- Barcode of the product  description character varying, -- Product details with string data type  msrp double precision, -- Maximum Retail price  our_price double precision, -- Selling price  created_at timestamp without time zone NOT NULL,  updated_at timestamp without time zone NOT NULL,  CONSTRAINT products_pkey PRIMARY KEY (id))WITH (  OIDS=FALSE);ALTER TABLE products  OWNER TO postgres;COMMENT ON TABLE products  IS 'Products table';COMMENT ON COLUMN products.name IS 'Name of the product';COMMENT ON COLUMN products.barcode IS 'Barcode of the product';COMMENT ON COLUMN products.description IS 'Product details with string data type';COMMENT ON COLUMN products.msrp IS 'Maximum Retail price';COMMENT ON COLUMN products.our_price IS 'Selling price';-- Index: index_products_on_name-- DROP INDEX index_products_on_name;CREATE UNIQUE INDEX index_products_on_name  ON products  USING btree  (name COLLATE pg_catalog.&quot;default&quot;);COMMENT ON INDEX index_products_on_name  IS 'Index used to lookup product by name.';</code></pre><p>If we update comments through migrations, corresponding comments will be updatedin <code>db/schema.rb</code> file.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 allows UUID as column type in create_join_table]]></title>
       <author><name>Hitesh Rawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-create-join-table-with-uuid"/>
      <updated>2016-06-16T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-create-join-table-with-uuid</id>
      <content type="html"><![CDATA[<p>In Rails 4.x<a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_join_table">create_join_table</a>allows us to create new join table with name given in first two arguments.</p><pre><code class="language-ruby">class CreateJoinTableCustomerProduct &lt; ActiveRecord::Migration  def change    create_join_table(:customers, :products)  endend</code></pre><p>It will create new join table <code>customer_products</code> with columns <code>customer_id</code> and<code>product_id</code>. We can also use block with <code>create_join_table</code>.</p><pre><code class="language-ruby">class CreateJoinTableCustomerProduct &lt; ActiveRecord::Migration  def change    create_join_table :customers, :products do |t|      t.index :customer_id      t.index :product_id    end  endend</code></pre><p>However <code>create_join_table</code> won't allows us to define the column type. It willalways create column of <code>integer</code> type. Because Rails 4.x ,by default, supportsprimary key column type as an auto increment <code>integer</code>.</p><p>If we wish to set <code>uuid</code> as a column type, then <code>create_join_table</code> won't work.In such case we have to create join table manually using <code>create_table</code>.</p><p>Here is an example with Rails 4.x.</p><pre><code class="language-ruby">class CreateJoinTableCustomerProduct &lt; ActiveRecord::Migration  def change    create_table :customer_products do |t|      t.uuid :customer_id      t.uuid :product_id    end  endend</code></pre><h2>Rails 5 allows to have UUID as column type in join table</h2><p>Rails 5 has started supporting UUID as a column type for primary key, so<code>create_join_table</code> should also support UUID as a column type instead of onlyintegers. Hence now Rails 5 allows us to use<a href="https://github.com/rails/rails/pull/24221">UUID as a column type with create_join_table</a>.</p><p>Here is revised example.</p><pre><code class="language-ruby">class CreateJoinTableCustomerProduct &lt; ActiveRecord::Migration[5.0]  def change    create_join_table(:customers, :products, column_options: {type: :uuid})  endend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds another base class Application Job for jobs]]></title>
       <author><name>Hitesh Rawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-application-jobs-for-jobs"/>
      <updated>2016-06-12T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-application-jobs-for-jobs</id>
      <content type="html"><![CDATA[<p>Rails 5 has added another base class<a href="https://github.com/rails/rails/pull/19034">ApplicationJob</a> which inherits from<code>ActiveJob::Base</code>. Now by default all new Rails 5 applications will have<code>application_job.rb</code>.</p><pre><code class="language-ruby"># app/jobs/application_job.rbclass ApplicationJob &lt; ActiveJob::Baseend</code></pre><p>In Rails 4.x if we want to use<a href="http://guides.rubyonrails.org/active_job_basics.html">ActiveJob</a> then first weneed to generate a job and all the generated jobs directly inherit from<code>ActiveJob::Base</code>.</p><pre><code class="language-ruby"># app/jobs/guests_cleanup_job.rbclass GuestsCleanupJob &lt; ActiveJob::Base  queue_as :default  def perform(*guests)    # Do something later  endend</code></pre><p>Rails 5 adds explicit base class <code>ApplicationJob</code> for <code>ActiveJob</code>. As you cansee this is not a big change but it is a good change in terms of beingconsistent with how controllers have <code>ApplicationController</code> and models have<a href="application-record-in-rails-5">ApplicationRecord</a>.</p><p>Now <code>ApplicationJob</code> will be a single place to apply all kind of customizationsand extensions needed for an application, instead of applying patch on<code>ActiveJob::Base</code>.</p><h2>Upgrading from Rails 4.x</h2><p>When upgrading from Rails 4.x to Rails 5 we need to create <code>application_job.rb</code>file in <code>app/jobs/</code> and add the following content.</p><pre><code class="language-ruby"># app/jobs/application_job.rbclass ApplicationJob &lt; ActiveJob::Baseend</code></pre><p>We also need to change all the existing job classes to inherit from<code>ApplicationJob</code> instead of <code>ActiveJob::Base</code>.</p><p>Here is the revised code of <code>GuestCleanupJob</code> class.</p><pre><code class="language-ruby"># app/jobs/guests_cleanup_job.rbclass GuestsCleanupJob &lt; ApplicationJob  queue_as :default  def perform(*guests)    # Do something later  endend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Updating records in AR Relation]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-updating-relation-objects-along-with-callbacks-and-validations"/>
      <updated>2016-06-10T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-updating-relation-objects-along-with-callbacks-and-validations</id>
      <content type="html"><![CDATA[<p>The <code>update_all</code> method when called on an <code>ActiveRecord::Relation</code> objectupdates all the records without invoking any callbacks and validations on therecords being updated.</p><p>Rails 5 supports<a href="https://github.com/rails/rails/pull/11898">update method on an ActiveRecord::Relation object</a>that runs callbacks and validations on all the records in the relation.</p><pre><code class="language-ruby">people = Person.where(country: 'US')people.update(language: 'English', currency: 'USD')</code></pre><p>Internally, the above code runs <code>update</code> method on each <code>Person</code> record whosecountry is <code>'US'</code>.</p><p>Let's see what happens when <code>update</code> is called on a relation in whichvalidations fail on few records.</p><p>We have a Note model. For simplicity let's add a validation that <code>note_text</code>field cannot be blank for first three records.</p><pre><code class="language-ruby">class Note &lt; ApplicationRecord  validate :valid_note  def valid_note   errors.add(:note_text, &quot;note_text is blank&quot;) if id &lt;= 3 &amp;&amp; note_text.blank?  endend</code></pre><p>Now let's try and update all the records with blank <code>note_text</code>.</p><pre><code class="language-ruby"> &gt; Note.all.update(note_text: '')  Note Load (0.3ms)  SELECT `notes`.* FROM `notes`   (0.1ms)  BEGIN   (0.1ms)  ROLLBACK   (0.1ms)  BEGIN   (0.1ms)  ROLLBACK   (0.1ms)  BEGIN   (0.1ms)  ROLLBACK   (0.1ms)  BEGIN  SQL (2.9ms)  UPDATE `notes` SET `note_text` = '', `updated_at` = '2016-06-16 19:42:21' WHERE `notes`.`id` = 3   (0.7ms)  COMMIT   (0.1ms)  BEGIN  SQL (0.3ms)  UPDATE `notes` SET `note_text` = '', `updated_at` = '2016-06-16 19:42:21' WHERE `notes`.`id` = 4   (1.2ms)  COMMIT   (0.1ms)  BEGIN  SQL (0.3ms)  UPDATE `notes` SET `note_text` = '', `updated_at` = '2016-06-16 19:42:21' WHERE `notes`.`id` = 5   (0.3ms)  COMMIT   (0.1ms)  BEGIN  SQL (3.4ms)  UPDATE `notes` SET `note_text` = '', `updated_at` = '2016-06-16 19:42:21' WHERE `notes`.`id` = 6   (0.2ms)  COMMIT =&gt; [#&lt;Note id: 1, user_id: 1, note_text: &quot;&quot;, created_at: &quot;2016-06-03 10:02:54&quot;, updated_at: &quot;2016-06-16 19:42:21&quot;&gt;, #&lt;Note id: 2, user_id: 1, note_text: &quot;&quot;, created_at: &quot;2016-06-03 10:03:54&quot;, updated_at: &quot;2016-06-16 19:42:21&quot;&gt;, #&lt;Note id: 3, user_id: 1, note_text: &quot;&quot;, created_at: &quot;2016-06-03 12:35:20&quot;, updated_at: &quot;2016-06-03 12:35:20&quot;&gt;, #&lt;Note id: 4, user_id: 1, note_text: &quot;&quot;, created_at: &quot;2016-06-03 14:15:15&quot;, updated_at: &quot;2016-06-16 19:14:20&quot;&gt;, #&lt;Note id: 5, user_id: 1, note_text: &quot;&quot;, created_at: &quot;2016-06-03 14:15:41&quot;, updated_at: &quot;2016-06-16 19:42:21&quot;&gt;, #&lt;Note id: 6, user_id: 1, note_text: &quot;&quot;, created_at: &quot;2016-06-03 14:16:20&quot;, updated_at: &quot;2016-06-16 19:42:21&quot;&gt;]</code></pre><p>We can see that failure of validations on records in the relation does not stopus from updating the valid records.</p><p>Also the return value of update on AR Relation is an array of records in therelation. We can see that the attributes in these records hold the values thatwe wanted to have after the update.</p><p>For example in the above mentioned case, we can see that in the returned array,the records with ids 1, 2 and 3 have blank <code>note_text</code> values even though thoserecords weren't updated.</p><p>Hence we may not be able to rely on the return value to know if the update issuccessful on any particular record.</p><p>For scenarios where running validations and callbacks is not important and/orwhere performance is a concern it is advisable to use <code>update_all</code> methodinstead of <code>update</code> method.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 prevents destructive action on production database]]></title>
       <author><name>Hitesh Rawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-prevents-destructive-action-on-production-db"/>
      <updated>2016-06-07T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-prevents-destructive-action-on-production-db</id>
      <content type="html"><![CDATA[<p>Sometimes while debugging production issue mistakenly developers executecommands like <code>RAILS_ENV=production rake db:schema:load</code>. This wipes out data inproduction.</p><p>Users of heroku download all the config variables to local machine to debugproduction problem and sometimes developers mistakenly execute commands whichwipes out production data. This has happened enough number of times to herokuusers that <a href="https://twitter.com/schneems">Richard Schneeman</a> of heroku decidedto do something about this issue.</p><h2>Rails 5 prevents destructive action on production database</h2><p>Rails 5 <a href="https://github.com/rails/rails/pull/22967">has added</a> a new table<code>ar_internal_metadata</code> to store <code>environment</code> version which is used at the timeof migrating the database.</p><p>When the first time <code>rake db:migrate</code> is executed then new table stores thevalue <code>production</code>. Now whenever we load<a href="https://github.com/rails/rails/pull/24399">database schema</a> or<a href="https://github.com/rails/rails/pull/24484">database structure</a> by running<code>rake db:schema:load</code> or <code>rake db:structure:load</code> Rails will check if Railsenvironment is &quot;production&quot; or not. If not then Rails will raise an exceptionand thus preventing the data wipeout.</p><p>To skip this environment check we can manually pass<code>DISABLE_DATABASE_ENVIRONMENT_CHECK=1</code> as an argument with load schema/structuredb command.</p><p>Here is an example of running <code>rake db:schema:load</code> when development db ispointing to production database.</p><pre><code class="language-ruby">$ rake db:schema:loadrake aborted!ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your 'production' database.If you are sure you want to continue, run the same command with the environment variable:DISABLE_DATABASE_ENVIRONMENT_CHECK=1</code></pre><p>As we can see Rails prevented data wipeout in production.</p><p>This is one of those features which hopefully you won't notice. However if youhappen to do something destructive to your production database then this featurewill come in handy.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds finish option in find_in_batches]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-provides-finish-option-for-find-in-batches"/>
      <updated>2016-06-06T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-provides-finish-option-for-find-in-batches</id>
      <content type="html"><![CDATA[<p>In Rails 4.x we had <code>start</code> option in <code>find_in_batches</code> method.</p><pre><code class="language-ruby">Person.find_in_batches(start: 1000, batch_size: 2000) do |group|  group.each { |person| person.party_all_night! }end</code></pre><p>The above code provides batches of <code>Person</code> starting from record whose value ofprimary key is equal to 1000.</p><p>There is no end value for primary key. That means in the above case all therecords that have primary key value greater than 1000 are fetched.</p><p>Rails 5 <a href="https://github.com/rails/rails/pull/12257">introduces finish option</a>that serves as an upper limit to the primary key value in the records beingfetched.</p><pre><code class="language-ruby">Person.find_in_batches(start: 1000, finish: 9500, batch_size: 2000) do |group|  group.each { |person| person.party_all_night! }end</code></pre><p>The above code ensures that no record in any of the batches has the primary keyvalue greater than 9500.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 introduces country_zones helper method]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-introduces-helpers-for-country-zones"/>
      <updated>2016-06-01T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-introduces-helpers-for-country-zones</id>
      <content type="html"><![CDATA[<p>Before Rails 5, we could fetch all time zones for US by using <code>us_zones</code> methodas follows.</p><pre><code class="language-ruby">&gt; puts ActiveSupport::TimeZone.us_zones.map(&amp;:to_s)(GMT-10:00) Hawaii(GMT-09:00) Alaska(GMT-08:00) Pacific Time (US &amp; Canada)(GMT-07:00) Arizona(GMT-07:00) Mountain Time (US &amp; Canada)(GMT-06:00) Central Time (US &amp; Canada)(GMT-05:00) Eastern Time (US &amp; Canada)(GMT-05:00) Indiana (East)</code></pre><p>Such functionality of getting all the <code>TimeZone</code> objects for a country wasimplemented only for one country, US.</p><p>The <code>TimeZone</code> class internally uses the <code>TzInfo</code> gem which does have an api forproviding timezones for all the countries.</p><p>Realizing this, the Rails community decided to<a href="https://github.com/rails/rails/pull/20625">introduce a helper method country_zones</a>to <code>ActiveSupport::TimeZone</code> class that is able to fetch a collection of<code>TimeZone</code> objects belonging to a country specified by its ISO 3166-1 Alpha2code.</p><pre><code class="language-ruby">&gt; puts ActiveSupport::TimeZone.country_zones('us').map(&amp;:to_s)(GMT-10:00) Hawaii(GMT-09:00) Alaska(GMT-08:00) Pacific Time (US &amp; Canada)(GMT-07:00) Arizona(GMT-07:00) Mountain Time (US &amp; Canada)(GMT-06:00) Central Time (US &amp; Canada)(GMT-05:00) Eastern Time (US &amp; Canada)(GMT-05:00) Indiana (East)&gt;puts ActiveSupport::TimeZone.country_zones('fr').map(&amp;:to_s) (GMT+01:00) Paris</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 provides fragment caching in Action Mailer views]]></title>
       <author><name>Prajakta Tambe</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-provides-fragment-caching-in-action-mailer-view"/>
      <updated>2016-05-31T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-provides-fragment-caching-in-action-mailer-view</id>
      <content type="html"><![CDATA[<p>Fragment cache helps in caching parts of the view instead of caching the entireview. Fragment caching is used when different parts of the view need to becached and expired separately. Before Rails 5, fragment caching was supportedonly in Action View templates.</p><p>Rails 5 provides<a href="https://github.com/rails/rails/commit/e40518f5d44303ed91641b342a53bdfb32753de3">fragment caching in Action Mailer views</a>. To use this feature, we need to configure our application as follows.</p><pre><code class="language-ruby">config.action_mailer.perform_caching = true</code></pre><p>This configuration specifies whether mailer templates should perform fragmentcaching or not. By default, this is set to <code>false</code> for all environments.</p><h2>Fragment caching in views</h2><p>We can do caching in mailer views similar to application views using <code>cache</code>method. Following example shows usage of fragment caching in mailer view of thewelcome mail.</p><pre><code class="language-ruby">&lt;body&gt; &lt;% cache 'signup-text' do %&gt;   &lt;h1&gt;Welcome to &lt;%= @company.name %&gt;&lt;/h1&gt;   &lt;p&gt;You have successfully signed up to &lt;%= @company.name %&gt;, Your username is: &lt;% end %&gt;     &lt;%= @user.login %&gt;.     &lt;br /&gt;   &lt;/p&gt; &lt;%= render :partial =&gt; 'footer' %&gt;&lt;/body&gt;</code></pre><p>When we render view for the first time, we can see cache digest of the view andits partial.</p><pre><code class="language-ruby">  Cache digest for app/views/user_mailer/_footer.erb: 7313427d26cc1f701b1e0212498cee38  Cache digest for app/views/user_mailer/welcome_email.html.erb: 30efff0173fd5f29a88ffe79a9eab617  Rendered user_mailer/_footer.erb (0.3ms)  Rendered user_mailer/welcome_email.html.erb (26.1ms)  Cache digest for app/views/user_mailer/welcome_email.text.erb: 77f41fe6159c5736ab2026a44bc8de55  Rendered user_mailer/welcome_email.text.erb (0.2ms)UserMailer#welcome_email: processed outbound mail in 190.3ms</code></pre><p>We can also use fragment caching in partials of the action mailer views with<code>cache</code> method. Fragment caching is also supported in multipart emails.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds OR support in Active Record]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-or-support-in-active-record"/>
      <updated>2016-05-30T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-or-support-in-active-record</id>
      <content type="html"><![CDATA[<p>Rails 5<a href="https://github.com/rails/rails/commit/b0b37942d729b6bdcd2e3178eda7fa1de203b3d0">has added OR method</a>to Active Relation for generating queries with OR clause.</p><pre><code class="language-ruby">&gt;&gt; Post.where(id: 1).or(Post.where(title: 'Learn Rails'))   SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE (&quot;posts&quot;.&quot;id&quot; = ? OR &quot;posts&quot;.&quot;title&quot; = ?)  [[&quot;id&quot;, 1], [&quot;title&quot;, &quot;Learn Rails&quot;]]=&gt; &lt;ActiveRecord::Relation [#&lt;Post id: 1, title: 'Rails'&gt;]&gt;</code></pre><p>This returns <code>ActiveRecord::Relation</code> object, which is logical union of tworelations.</p><h3>Some Examples of OR usage</h3><h5>With group and having</h5><pre><code class="language-ruby">&gt;&gt; posts = Post.group(:user_id)&gt;&gt; posts.having('id &gt; 3').or(posts.having('title like &quot;Hi%&quot;'))SELECT &quot;posts&quot;.* FROM &quot;posts&quot; GROUP BY &quot;posts&quot;.&quot;user_id&quot; HAVING ((id &gt; 2) OR (title like &quot;Rails%&quot;))=&gt; &lt;ActiveRecord::Relation [#&lt;Post id: 3, title: &quot;Hi&quot;, user_id: 4&gt;,#&lt;Post id: 6, title: &quot;Another new blog&quot;, user_id: 6&gt;]&gt;</code></pre><h5>With scope</h5><pre><code class="language-ruby">class Post &lt; ApplicationRecord  scope :contains_blog_keyword, -&gt; { where(&quot;title LIKE '%blog%'&quot;) }end&gt;&gt; Post.contains_blog_keyword.or(Post.where('id &gt; 3'))SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE ((title LIKE '%blog%') OR (id &gt; 3))=&gt; &lt;ActiveRecord::Relation [#&lt;Post id: 4, title: &quot;A new blog&quot;, user_id: 6&gt;,#&lt;Post id: 5, title: &quot;Rails blog&quot;, user_id: 4&gt;,#&lt;Post id: 6, title: &quot;Another new blog&quot;, user_id: 6&gt;]&gt;</code></pre><h5>With combination of scopes</h5><pre><code class="language-ruby">class Post &lt; ApplicationRecord  scope :contains_blog_keyword, -&gt; { where(&quot;title LIKE '%blog%'&quot;) }  scope :id_greater_than, -&gt; (id) {where(&quot;id &gt; ?&quot;, id)}  scope :containing_blog_keyword_with_id_greater_than, -&gt;(id) { contains_blog_keyword.or(id_greater_than(id)) }end&gt;&gt; Post.containing_blog_keyword_with_id_greater_than(2)SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE ((title LIKE '%blog%') OR (id &gt; 2)) ORDER BY &quot;posts&quot;.&quot;id&quot; DESC=&gt; &lt;ActiveRecord::Relation [#&lt;Post id: 3, title: &quot;Hi&quot;, user_id: 6&gt;,#&lt;Post id: 4, title: &quot;A new blog&quot;, user_id: 6&gt;,#&lt;Post id: 5, title: &quot;Another new blog&quot;, user_id: 6&gt;,&lt;#Post id: 6, title: &quot;Another new blog&quot;, user_id: 6&gt;]&gt;</code></pre><h4>Constraints for using OR method</h4><p>The two relations must be structurally compatible, they must be scoping the samemodel, and they must differ only by <code>WHERE</code> or <code>HAVING</code>.</p><p>In order to use OR operator, neither relation should have a <code>limit</code>, <code>offset</code>,or <code>distinct</code>.</p><pre><code class="language-ruby">&gt;&gt; Post.where(id: 1).limit(1).or(Post.where(:id =&gt; [2, 3]))ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:limit]</code></pre><p>When <code>limit</code>, <code>offset</code> or <code>distinct</code> is passed only with one relation, then itthrows <code>ArgumentError</code> as shown above.</p><p>As of now, we can use <code>limit</code>, <code>offset</code> or <code>distinct</code> when passed with both therelations and with same the parameters.</p><pre><code class="language-ruby">&gt;&gt; Post.where(id: 1).limit(2).or(Post.where(:id =&gt; [2, 3]).limit(2))SELECT  &quot;posts&quot;.* FROM &quot;posts&quot; WHERE (&quot;posts&quot;.&quot;id&quot; = ? OR &quot;posts&quot;.&quot;id&quot; IN (2, 3)) LIMIT ?  [[&quot;id&quot;, 1], [&quot;LIMIT&quot;, 2]]=&gt; &lt;ActiveRecord::Relation [#&lt;Post id: 1, title: 'Blog', user_id: 3, published: true&gt;,#&lt;Post id: 2, title: 'Rails 5 post', user_id: 4, published: true&gt;]&gt;</code></pre><p>There is an <a href="https://github.com/rails/rails/issues/24055">issue</a> open in whichdiscussions are ongoing regarding completely stopping usage of <code>limit</code>, <code>offset</code>or <code>distinct</code> when using with <code>or</code>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 ArrayInquirer and checking array contents]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-introduces-active-support-array-inquirer"/>
      <updated>2016-05-27T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-introduces-active-support-array-inquirer</id>
      <content type="html"><![CDATA[<p>Rails 5 <a href="https://github.com/rails/rails/pull/18939">introduces Array Inquirer</a>that wraps an array object and provides friendlier methods to check for thepresence of elements that can be either a string or a symbol.</p><pre><code class="language-ruby">pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])&gt; pets.cat?#=&gt; true&gt; pets.rabbit?#=&gt; true&gt; pets.elephant?#=&gt; false</code></pre><p>Array Inquirer also has <code>any?</code> method to check for the presence of any of thepassed arguments as elements in the array.</p><pre><code class="language-ruby">pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])&gt; pets.any?(:cat, :dog)#=&gt; true&gt; pets.any?('cat', 'dog')#=&gt; true&gt; pets.any?(:rabbit, 'elephant')#=&gt; true&gt; pets.any?('elephant', :tiger)#=&gt; false</code></pre><p>Since <code>ArrayInquirer</code> class inherits from <code>Array</code> class, its <code>any?</code> methodperforms same as <code>any?</code> method of <code>Array</code> class when no arguments are passed.</p><pre><code class="language-ruby">pets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit'])&gt; pets.any?#=&gt; true&gt; pets.any? { |pet| pet.to_s == 'dog' }#=&gt; true</code></pre><h2>Use inquiry method on array to fetch Array Inquirer version</h2><p>For any given array we can have its Array Inquirer version by calling <code>inquiry</code>method on it.</p><pre><code class="language-ruby">pets = [:cat, :dog, 'rabbit'].inquiry&gt; pets.cat?#=&gt; true&gt; pets.rabbit?#=&gt; true&gt; pets.elephant?#=&gt; false</code></pre><h2>Usage of Array Inquirer in Rails code</h2><p>Rails 5<a href="https://github.com/georgeclaghorn/rails/blob/c64b99ecc98341d504aced72448bee758f3cfdaf/actionpack/lib/action_dispatch/http/mime_negotiation.rb#L89">makes use of Array Inquirer</a>and provides a better way of checking for the presence of given variant.</p><p>Before Rails 5 code looked like this.</p><pre><code class="language-ruby">request.variant = :phone&gt; request.variant#=&gt; [:phone]&gt; request.variant.include?(:phone)#=&gt; true&gt; request.variant.include?('phone')#=&gt; false</code></pre><p>Corresponding Rails 5 version is below.</p><pre><code class="language-ruby">request.variant = :phone&gt; request.variant.phone?#=&gt; true&gt; request.variant.tablet?#=&gt; false</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Renaming transactional fixtures to tests]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-renamed-transactional-fixtures-to-transactional-tests"/>
      <updated>2016-05-26T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-renamed-transactional-fixtures-to-transactional-tests</id>
      <content type="html"><![CDATA[<p>In Rails 4.x we have transactional fixtures that wrap each test in a databasetransaction. This transaction rollbacks all the changes at the end of the test.It means the state of the database, before the test is same as after the test isdone.</p><p>By default this functionality is enabled. We can choose to disable it in a testcase class by setting the class attribute <code>use_transactional_fixtures</code> to<code>false</code></p><pre><code class="language-ruby">class FooTest &lt; ActiveSupport::TestCase  self.use_transactional_fixtures = falseend</code></pre><p>Rails also comes with fixtures for tests. So it may seem that<code>use_transactional_fixtures</code> has something to do with the Rails fixtures. A lotof people don't use fixtures and they think that they should disable<code>use_transactional_fixtures</code> because they do not use fixtures.</p><p>To overcome this confusion, Rails 5 has<a href="https://github.com/rails/rails/pull/19282">renamed transactional fixtures to transactional tests</a>making it clear that it has nothing to do with the fixtures used in tests.</p><p>In Rails 5, the above example will be written as follows.</p><pre><code class="language-ruby">class FooTest &lt; ActiveSupport::TestCase  self.use_transactional_tests = falseend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds ignored_columns for Active Record]]></title>
       <author><name>Hitesh Rawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-active-record-ignored-columns"/>
      <updated>2016-05-24T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-active-record-ignored-columns</id>
      <content type="html"><![CDATA[<p>Sometimes we need to ignore a database column. However Rails 4.x doesn't haveany officially defined method which ignores a database column from ActiveRecord. We can apply our patch on model to ignore certain columns.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  # Ignoring employee_email column  def self.columns    super.reject {|column| column.name == 'employee_email'}  endend</code></pre><h3>Rails 5 added ignored_columns</h3><p>Rails 5 <a href="https://github.com/rails/rails/pull/21720">has added ignored_columns</a>to <code>ActiveRecord::Base</code> class.</p><p>Here is revised code after using <code>ignored_columns</code> method.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  self.ignored_columns = %w(employee_email)end</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds a hidden field on collection radio buttons]]></title>
       <author><name>Prajakta Tambe</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-add-a-hidden-field-on-collection-radio-buttons"/>
      <updated>2016-05-18T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-add-a-hidden-field-on-collection-radio-buttons</id>
      <content type="html"><![CDATA[<p>Consider the following form which has only one input <code>role_id</code> which is acceptedthrough <code>collection_radio_button</code>.</p><pre><code class="language-ruby">&lt;%= form_for(@user) do |f| %&gt;  &lt;%= f.collection_radio_buttons :role_id, @roles, :id, :name %&gt;  &lt;div class=&quot;actions&quot;&gt;    &lt;%= f.submit %&gt;  &lt;/div&gt;&lt;% end %&gt;</code></pre><p>In the controller, we can access <code>role_id</code> using the strong parameters.</p><pre><code class="language-ruby">def user_params  params.require(:user).permit(:role_id)end</code></pre><p>When we try to submit this form without selecting any radio button in Rails 4.x,we will get <code>400 Bad Request</code> error with following message.</p><pre><code class="language-ruby">ActionController::ParameterMissing (param is missing or the value is empty: user):.</code></pre><p>This is because following parameters were sent to server in Rails 4.x .</p><pre><code class="language-ruby">Parameters: {&quot;utf8&quot;=&gt;&quot;&quot;, &quot;authenticity_token&quot;=&gt;&quot;...&quot;, &quot;commit&quot;=&gt;&quot;Create User&quot;}</code></pre><p>According to HTML specification, when multiple parameters are passed to<code>collection_radio_buttons</code> and no option is selected, web browsers do not sendany value to the server.</p><h2>Solution in Rails 5</h2><p>Rails 5<a href="https://github.com/rails/rails/pull/18303">adds hidden field on the collection_radio_buttons</a>to avoid raising an error when the only input on the form is<code>collection_radio_buttons</code>. The hidden field has the same name as collectionradio button and has blank value.</p><p>Following parameters will be sent to server in Rails 5 when above user form issubmitted:</p><pre><code class="language-ruby">Parameters: {&quot;utf8&quot;=&gt;&quot;&quot;, &quot;authenticity_token&quot;=&gt;&quot;...&quot;, &quot;user&quot;=&gt;{&quot;role_id&quot;=&gt;&quot;&quot;}, &quot;commit&quot;=&gt;&quot;Create User&quot;}</code></pre><p>In case we don't want the helper to generate this hidden field, we can specify<code>include_hidden: false</code>.</p><pre><code class="language-ruby">&lt;%= f.collection_radio_buttons :role_id, Role.all, :id, :name, include_hidden: false %&gt;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Attributes from Active Record to Active Model]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-moved-assign-attributes-from-activerecord-to-activemodel"/>
      <updated>2016-05-17T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-moved-assign-attributes-from-activerecord-to-activemodel</id>
      <content type="html"><![CDATA[<p>Before Rails 5, we could use <code>assign_attributes</code> and have bulk assignment ofattributes only for objects whose classes are inherited from<code>ActiveRecord::Base</code> class.</p><p>In Rails 5 we can make use of <code>assign_attributes</code> method and have bulkassignment of attributes even for objects whose classes are not inherited from<code>ActiveRecord::Base</code>.</p><p>This is possible because the attributes assignment code<a href="https://github.com/rails/rails/pull/10776">is now moved</a> from<code>ActiveRecord::AttributeAssignment</code> to <code>ActiveModel::AttributeAssignment</code>module.</p><p>To have this up and running, we need to include<code>ActiveModel::AttributeAssignment</code> module to our class.</p><pre><code class="language-ruby">class User  include ActiveModel::AttributeAssignment  attr_accessor :email, :first_name, :last_nameenduser = User.newuser.assign_attributes({email:      'sam@example.com',                        first_name: 'Sam',                        last_name:  'Smith'})&gt; user.email#=&gt; &quot;sam@example.com&quot;&gt; user.first_name#=&gt; &quot;Sam&quot;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Configure Active Job backend adapter for jobs]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-to-inherit-activejob-queue-adapter"/>
      <updated>2016-05-15T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-to-inherit-activejob-queue-adapter</id>
      <content type="html"><![CDATA[<p>Before Rails 5 we had ability to configure Active Job <code>queue_adapter</code> at anapplication level. If we want to use <code>sidekiq</code> as our backend queue adapter wewould configure it as following.</p><pre><code class="language-ruby">config.active_job.queue_adapter = :sidekiq</code></pre><p>This <code>queue_adapter</code> would be applicable to all jobs.</p><p>Rails 5 provides ability to configure <code>queue_adapter</code><a href="https://github.com/rails/rails/pull/16992">on a per job basis</a>. It means<code>queue_adapter</code> for one job can be different to that of the other job.</p><p>Let's suppose we have two jobs in our brand new Rails 5 application. <code>EmailJob</code>is responsible for processing basic emails and <code>NewsletterJob</code> sends out newsletters.</p><pre><code class="language-ruby">class EmailJob &lt; ActiveJob::Base  self.queue_adapter = :sidekiqendclass NewletterJob &lt; ActiveJob::BaseendEmailJob.queue_adapter =&gt; #&lt;ActiveJob::QueueAdapters::SidekiqAdapter:0x007fb3d0b2e4a0&gt;NewletterJob.queue_adapter =&gt; #&lt;ActiveJob::QueueAdapters::AsyncAdapter:0x007fb3d0c61b88&gt;</code></pre><p>We are now able to configure <code>sidekiq</code> queue adapter for <code>EmailJob</code>. In case of<code>NewsletterJob</code> we fallback to the global default adapter which in case of a newRails 5 app <a href="rails-5-changed-default-active-job-adapter-to-async">is async</a>.</p><p>Moreover, in Rails 5, when one job inherits other job, then queue adapter of theparent job gets persisted in the child job unless child job has configuration tochange queue adapter.</p><p>Since news letters are email jobs we can make <code>NewsLetterJob</code> inherit from<code>EmailJob</code>.</p><p>Below is an example where <code>EmailJob</code> is using <code>rescue</code> while <code>NewsLetterJob</code> isusing <code>sidekiq</code>.</p><pre><code class="language-ruby">class EmailJob &lt; ActiveJob::Base  self.queue_adapter = :resqueendclass NewsletterJob &lt; EmailJobendEmailJob.queue_adapter =&gt; #&lt;ActiveJob::QueueAdapters::ResqueAdapter:0x007fe137ede2a0&gt;NewsletterJob.queue_adapter =&gt; #&lt;ActiveJob::QueueAdapters::ResqueAdapter:0x007fe137ede2a0&gt;class NewsletterJob &lt; EmailJob  self.queue_adapter = :sidekiqendNewsletterJob.queue_adapter =&gt; #&lt;ActiveJob::QueueAdapters::SidekiqAdapter:0x007fb3d0b2e4a0&gt;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 accepts 1 or true for acceptance validation]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-accepts-1-or-true-for-acceptance-validation"/>
      <updated>2016-05-13T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-accepts-1-or-true-for-acceptance-validation</id>
      <content type="html"><![CDATA[<p><code>validates_acceptance_of</code> is a good validation tool for asking users to accept&quot;terms of service&quot; or similar items.</p><p>Before Rails 5, the only acceptable value for a <code>validates_acceptance_of</code>validation was <code>1</code>.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  validates_acceptance_of :terms_of_serviceend&gt; user = User.new(terms_of_service: &quot;1&quot;)&gt; user.valid?#=&gt; true</code></pre><p>Having acceptable value of <code>1</code> does cause some ambiguity because general purposeof acceptance validation is for attributes that hold boolean values.</p><p>So in order to have <code>true</code> as acceptance value we had to pass <code>accept</code> option to<code>validates_acceptance_of</code> as shown below.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  validates_acceptance_of :terms_of_service, accept: trueend&gt; user = User.new(terms_of_service: true)&gt; user.valid?#=&gt; true&gt; user.terms_of_service = '1'&gt; user.valid?#=&gt; false</code></pre><p>Now this comes with the cost that <code>1</code> is no longer an acceptable value.</p><p>In Rails 5, we have <code>true</code> as a<a href="https://github.com/rails/rails/pull/18439">default value for acceptance</a> alongwith the already existing acceptable value of <code>1</code>.</p><p>In Rails 5 the previous example would look like as shown below.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  validates_acceptance_of :terms_of_serviceend&gt; user = User.new(terms_of_service: true)&gt; user.valid?#=&gt; true&gt; user.terms_of_service = '1'&gt; user.valid?#=&gt; true</code></pre><h2>Rails 5 allows user to have custom set of acceptable values</h2><p>In Rails 5, <code>:accept</code> option of <code>validates_acceptance_of</code> method supports anarray of values unlike a single value that we had before.</p><p>So in our example if we are to validate our <code>terms_of_service</code> attribute withany of <code>true</code>, <code>&quot;y&quot;</code>, <code>&quot;yes&quot;</code> we could have our validation as follows.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  validates_acceptance_of :terms_of_service, accept: [true, &quot;y&quot;, &quot;yes&quot;]end&gt; user = User.new(terms_of_service: true)&gt; user.valid?#=&gt; true&gt; user.terms_of_service = 'y'&gt; user.valid?#=&gt; true&gt; user.terms_of_service = 'yes'&gt; user.valid?#=&gt; true</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 supports bi-directional destroy dependency]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/Rails-5-supports-bi-directional-destroy-dependency"/>
      <updated>2016-05-12T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/Rails-5-supports-bi-directional-destroy-dependency</id>
      <content type="html"><![CDATA[<p>In Rails 4.x, it is not possible to have destroy dependency on both sides of abi-directional association between the two models as it would result in aninfinite callback loop causing <code>SystemStackError: stack level too deep</code>.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  has_one :profile, dependent: :destroyendclass Profile &lt; ActiveRecord::Base  belongs_to :user, dependent: :destroyend</code></pre><p>Calling <code>User#destroy</code> or <code>Profile#destroy</code> would lead to an infinite callbackloop.</p><pre><code class="language-ruby">&gt;&gt; user = User.first=&gt; &lt;User id: 4, name: &quot;George&quot;&gt;&gt;&gt; user.profile=&gt; &lt;Profile id: 4&gt;&gt;&gt; user.destroy=&gt; DELETE FROM `profiles` WHERE `profiles`.`id` = 4   ROLLBACKSystemStackError: stack level too deep</code></pre><p>Rails 5<a href="https://github.com/rails/rails/pull/18548">supports bi-directional destroy dependency</a>without triggering infinite callback loop.</p><pre><code class="language-ruby">&gt;&gt; user = User.first=&gt; &lt;User id: 4, name: &quot;George&quot;&gt;&gt;&gt; user.profile=&gt; &lt;Profile id: 4, about: 'Rails developer', works_at: 'ABC'&gt;&gt;&gt; user.destroy=&gt; DELETE FROM &quot;profiles&quot; WHERE &quot;posts&quot;.&quot;id&quot; = ?  [[&quot;id&quot;, 4]]   DELETE FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;id&quot; = ?  [[&quot;id&quot;, 4]]=&gt; &lt;User id: 4, name: &quot;George&quot;&gt;</code></pre><p>There are many instances like above where we need to destroy an association whenit is destroying itself, otherwise it may lead to orphan records.</p><p>This feature adds responsibility on developers to ensure adding destroydependency only when it is required as it can have unintended consequences asshown below.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  has_many :posts, dependent: :destroyendclass Post &lt; ApplicationRecord  belongs_to :user, dependent: :destroyend&gt;&gt; user = User.first=&gt; &lt;User id: 4, name: &quot;George&quot;&gt;&gt;&gt; user.posts=&gt; &lt;ActiveRecord::Associations::CollectionProxy [&lt;Post id: 11, title: 'Ruby', user_id: 4&gt;, #&lt;Post id: 12, title: 'Rails', user_id: 4&gt;]&gt;</code></pre><p>As we can see &quot;user&quot; has two posts. Now we will destroy first post.</p><pre><code class="language-ruby">&gt;&gt; user.posts.first.destroy=&gt; DELETE FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;id&quot; = ?  [[&quot;id&quot;, 11]]   SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;user_id&quot; = ?  [[&quot;user_id&quot;, 4]]   DELETE FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;id&quot; = ?  [[&quot;id&quot;, 12]]   DELETE FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;id&quot; = ?  [[&quot;id&quot;, 4]]</code></pre><p>As we can see, we wanted to remove post with id &quot;11&quot;. However post with id &quot;12&quot;also got deleted. Not only that but user record got deleted too.</p><p>In Rails 4.x this would have resulted in<code>SystemStackError: stack level too deep</code> .</p><p>So we should use this option very carefully.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds after_commit callbacks aliases]]></title>
       <author><name>Hitesh Rawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-after_create-aliases"/>
      <updated>2016-05-11T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-after_create-aliases</id>
      <content type="html"><![CDATA[<p>Rails 4.x has<a href="http://guides.rubyonrails.org/active_record_callbacks.html">after_commit</a>callback. <code>after_commit</code> is called after a record has been created, updated ordestroyed.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  after_commit :send_welcome_mail, on: create  after_commit :send_profile_update_notification, on: update  after_commit :remove_profile_data, on: destroy  def send_welcome_mail    EmailSender.send_welcome_mail(email: email)  endend</code></pre><h2>Rails 5 added new aliases</h2><p>Rails 5 <a href="https://github.com/rails/rails/pull/22516">had added</a> following threealiases.</p><ul><li>after_create_commit</li><li>after_update_commit</li><li>after_destroy_commit</li></ul><p>Here is revised code after using these aliases.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  after_create_commit:send_welcome_mail  after_update_commit:send_profile_update_notification  after_destroy_commit:remove_profile_data  def send_welcome_mail    EmailSender.send_welcome_mail(email: email)  endend</code></pre><h3>Note</h3><p>We earlier stated that <code>after_commit</code> callback is executed at the end oftransaction. Using <code>after_commit</code> with a transaction block can be tricky. Pleasecheckout our earlier post about<a href="gotcha-with-after_commit-callback-in-rails">Gotcha with after_commit callback in Rails</a>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Updating a record without updating timestamps]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-updating-without-updating-timestamps"/>
      <updated>2016-05-09T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-updating-without-updating-timestamps</id>
      <content type="html"><![CDATA[<p>In Rails 4.x, when we save an <code>ActiveRecord</code> object then Rails automaticallyupdates fields <code>updated_at</code> or <code>updated_on</code>.</p><pre><code class="language-ruby">&gt;&gt; user = User.new(name: 'John', email: 'john@example.com')&gt;&gt; user.save INSERT INTO &quot;users&quot; (&quot;name&quot;, &quot;created_at&quot;, &quot;updated_at&quot;, &quot;email&quot;) VALUES (?, ?, ?, ?)  [[&quot;name&quot;, &quot;John&quot;], [&quot;created_at&quot;, 2016-03-16 09:12:44 UTC], [&quot;updated_at&quot;, 2016-03-16 09:12:44 UTC], [&quot;email&quot;, &quot;john@example.com&quot;]]=&gt; true&gt;&gt; user.updated_at=&gt; Wed, 16 Mar 2016 09:12:44 UTC +00:00&gt;&gt; user.name = &quot;Mark&quot;&gt;&gt; user.save  UPDATE &quot;users&quot; SET &quot;name&quot; = ?, &quot;updated_at&quot; = ? WHERE &quot;users&quot;.&quot;id&quot; = ?  [[&quot;name&quot;, &quot;Mark&quot;], [&quot;updated_at&quot;, 2016-03-16 09:15:30 UTC], [&quot;id&quot;, 12]]=&gt; true&gt;&gt; user.updated_at=&gt; Wed, 16 Mar 2016 09:15:30 UTC +00:00</code></pre><h2>Addition of touch option in ActiveRecord::Base#save</h2><p>In Rails 5, by passing <code>touch: false</code> as an option to <code>save</code>, we can update theobject without updating timestamps. The default option for <code>touch</code> is <code>true</code>.</p><pre><code class="language-ruby">&gt;&gt; user.updated_at=&gt; Wed, 16 Mar 2016 09:15:30 UTC +00:00&gt;&gt; user.name = &quot;Dan&quot;&gt;&gt; user.save(touch: false)  UPDATE &quot;users&quot; SET &quot;name&quot; = ? WHERE &quot;users&quot;.&quot;id&quot; = ?  [[&quot;name&quot;, &quot;Dan&quot;], [&quot;id&quot;, 12]]=&gt; true&gt;&gt; user.updated_at=&gt; Wed, 16 Mar 2016 09:15:30 UTC +00:00</code></pre><p>This works only when we are updating a record and does not work when a record iscreated.</p><pre><code class="language-ruby">&gt;&gt; user = User.new(name: 'Tom', email: 'tom@example.com')&gt;&gt; user.save(touch: false) INSERT INTO &quot;users&quot; (&quot;name&quot;, &quot;created_at&quot;, &quot;updated_at&quot;, &quot;email&quot;) VALUES (?, ?, ?, ?)  [[&quot;name&quot;, &quot;Tom&quot;], [&quot;created_at&quot;, 2016-03-21 06:57:23 UTC], [&quot;updated_at&quot;, 2016-03-21 06:57:23 UTC], [&quot;email&quot;, &quot;tom@example.com&quot;]])&gt;&gt; user.updated_at=&gt; Mon, 21 Mar 2016 07:04:04 UTC +00:00</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Retrieving info of failed validations]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-a-way-to-get-information-about-types-of-failed-validations"/>
      <updated>2016-05-03T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-a-way-to-get-information-about-types-of-failed-validations</id>
      <content type="html"><![CDATA[<p>Let's look at a validation example in Rails 4.x.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  validates :email, presence: trueend&gt;&gt; user = User.new&gt;&gt; user.valid?=&gt; false&gt;&gt; user.errors.messages=&gt; {:email=&gt;[&quot;can't be blank&quot;]}</code></pre><p>In this case, we do not get any information about the type of failed validationas <code>ActiveModel#Errors</code> only gives the attribute name and the translated errormessage.</p><p>This works out well for normal apps. But in case of API only applications,sometimes we want to allow the client consuming the API to generate customizederror message as per their needs. We don't want to send the final translatedmessages in such cases. Instead if we could just send details that <code>presence</code>validation failed for <code>:name</code> attribute, the client app would be able tocustomize the error message based on that information.</p><p>In Rails 5, it is now possible to get such details about which validationsfailed for a given attribute.</p><p>We can check this by calling<a href="https://github.com/rails/rails/pull/18322">details method</a> on the<code>ActiveModel#Errors</code> instance.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  validates :email, presence: trueend&gt;&gt; user = User.new&gt;&gt; user.valid?=&gt; false&gt;&gt; user.errors.details=&gt; {:email=&gt;[{:error=&gt;:blank}]}</code></pre><p>We can also add custom validator types as per our need.</p><pre><code class="language-ruby"># Custom validator type&gt;&gt; user = User.new&gt;&gt; user.errors.add(:name, :not_valid, message: &quot;The name appears invalid&quot;)&gt;&gt; user.errors.details=&gt; {:name=&gt;[{:error=&gt;:not_valid}]}# Custom error with default validator type :invalid&gt;&gt; user = User.new&gt;&gt; user.errors.add(:name)&gt;&gt; user.errors.details=&gt; {:name=&gt;[{:error=&gt;:invalid}]}# More than one error on one attribute&gt;&gt; user = User.new&gt;&gt; user.errors.add(:password, :invalid_format, message: &quot;Password must start with an alphabet&quot;)&gt;&gt; user.errors.add(:password, :invalid_length, message: &quot;Password must have at least 8 characters&quot;)&gt;&gt; user.errors.details=&gt; {:password=&gt;[{:error=&gt;:invalid_format}, {:error=&gt;:invalid_length}]}</code></pre><h2>Passing contextual information about the errors</h2><p>We can also send contextual data for the validation to the <code>Errors#add</code> method.This data can be later accessed via <code>Errors#details</code> method because <code>Errors#add</code>method forwards all options except <code>:message</code>, <code>:if</code>, <code>:unless</code>, and <code>:on</code> to<code>details</code>.</p><p>For eg. we can say that the <code>password</code> is invalid because <code>!</code> is not allowed, asfollows.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  validate :password_cannot_have_invalid_character  def password_cannot_have_invalid_character    if password.scan(&quot;!&quot;).present?      errors.add(:password, :invalid_character, not_allowed: &quot;!&quot;)    end  endend&gt;&gt; user = User.create(name: 'Mark', password: 'Ra!ls')&gt;&gt; user.errors.details=&gt; {:password=&gt;[{:error=&gt;:invalid_character, :not_allowed=&gt;&quot;!&quot;}]}</code></pre><p>We can also use this feature in our Rails 4.x apps by simply installing gem<a href="https://github.com/cowbell/active_model-errors_details">active_model-errors_details</a>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 - What's in it for me?]]></title>
       <author><name>Prathamesh Sonpatki</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-webinar"/>
      <updated>2016-04-22T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-webinar</id>
      <content type="html"><![CDATA[<p>I recently did a webinar with Srijan on upcoming changes in Rails 5. In thiswebinar I discussed various features and additions coming up in Rails 5.</p><p>&lt;div class=&quot;youtube-video-container&quot;&gt;&lt;iframewidth=&quot;640&quot;height=&quot;480&quot;src=&quot;https://www.youtube.com/embed/ECDX1NH7yWE&quot;frameborder=&quot;0&quot;allowfullscreen</p><blockquote><p>&lt;/iframe&gt;&lt;/div&gt;</p></blockquote><h2>Major Features</h2><p>Ruby 2.2.2+ dependency.</p><p>Action Cable.</p><p>API only apps.</p><h2>Features for Development mode</h2><p>Puma as default web server.</p><p><code>rails</code> CLI over <code>rake</code>.</p><p>Restarting app using <code>rails restart</code>.</p><p>Enable caching using <code>rails dev:cache</code>.</p><p>Enhanced filtering of routes using <code>rails routes -g</code></p><p>Evented file system monitor.</p><h2>Features for Test mode</h2><p>Test Runner.</p><p>Changes to controller tests.</p><h2>Features related to Caching</h2><p>Cache content forever using <code>http_cache_forever</code>.</p><p>Collection caching using <code>ActiveRecord#cache_key</code>.</p><p>Partials caching using multi_fetch_fragments.</p><p>Caching in Action Mailer views.</p><h2>Changes in Active Record</h2><p>Introduction of <code>ApplicationRecord</code>.</p><p><code>ActiveRelation#or</code>.</p><p><code>has_secure_token</code> for generating secure tokens.</p><p>Versioned migrations for backward compatibility.</p><h2>Changes in Active Support</h2><p>Improvements to Date/Time.</p><p><code>Enumerable#pluck</code>, <code>Enumerable#without</code>.</p><p>Change in behavior related to halting callback chains.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 officially supports MariaDB]]></title>
       <author><name>Vipul</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-official-supports-mariadb"/>
      <updated>2016-04-21T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-official-supports-mariadb</id>
      <content type="html"><![CDATA[<p><a href="https://mariadb.org/">MariaDB</a> is an open source fork of the MySQL database andit acts as a drop-in replacement for MySQL.</p><p>After the Oracle's<a href="https://www.theguardian.com/technology/2009/dec/14/monty-widenius-oracle-protest">take over</a>of<a href="http://www.infoworld.com/article/2630216/database/many-open-sourcers-back-an-oracle-takeover-of-mysql.html">MySQL</a>there was some confusion about the future of MySQL. To remove any ambiguityabout whether in future MySQL will remain free or not MariaDB<a href="https://en.wikipedia.org/wiki/MariaDB?oldformat=true">was started</a> .</p><p>Some of you might be wondering what advantages MariaDB offers over MySQL.Here isan article which lists<a href="https://seravo.fi/2015/10-reasons-to-migrate-to-mariadb-if-still-using-mysql">10 reasons</a>to migrate to MariaDB from MySQL.</p><p>MariaDB is bundled as default on systems like<a href="http://www.itwire.com/business-it-news/open-source/60292-red-hat-ditches-mysql-switches-to-mariadb">Redhat's RHEL 7+</a>,<a href="https://www.archlinux.org/news/mariadb-replaces-mysql-in-repositories/">Archlinux</a>,<a href="http://www.slackware.com/index.html">Slackware</a> and<a href="http://marc.info/?l=openbsd-ports-cvs&amp;m=141063182731679&amp;w=2">OpenBSD</a>.</p><p>Some of the users of MariaDB are Google, Mozilla, Facebook and<a href="http://blog.wikimedia.org/2013/04/22/wikipedia-adopts-mariadb/">Wikipedia</a>.Later we found out that <a href="https://basecamp.com/">Basecamp</a> has<a href="https://github.com/rails/rails/pull/24454#issuecomment-206994634">already been using MariaDB</a>for a while.</p><h2>Active Record support for MariaDB</h2><p>Recently, <a href="https://github.com/iangilfillan">Ian Gilfillan</a> from MariaDBFoundation sent a <a href="https://github.com/rails/rails/pull/24454">Pull Request</a> toinclude MariaDB as part Rails Documentation.</p><p>Accepting that pull request means Rails is<a href="https://github.com/rails/rails/pull/24522">committing to</a> supporting MariaDBalong with MySQL, PostgreSQL and SQLite.</p><p>The tests revealed an <a href="https://travis-ci.org/rails/rails/jobs/122573447">issue</a>related to micro-precision support on time column.</p><p>If a column has time field and if we search on that column then the search wasfailing for MariaDB.</p><pre><code class="language-ruby">time = ::Time.utc(2000, 1, 1, 12, 30, 0, 999999)Task.create!(start: time)Task.find_by(start: time) # =&gt; nil</code></pre><p>In the above case we created a record. However query yielded no record.</p><p>Now let's see why the query did not work for MariaDB.</p><h2>MariaDB vs MySQL time column difference</h2><p>First let's examine the <code>tasks</code> table.</p><pre><code class="language-sql"> mysql&gt; desc tasks;+--------+---------+------+-----+---------+----------------+| Field  | Type    | Null | Key | Default | Extra          |+--------+---------+------+-----+---------+----------------+| id     | int(11) | NO   | PRI | NULL    | auto_increment || start  | time    | YES  |     | NULL    |                |+--------+---------+------+-----+---------+----------------+2 rows in set (0.00 sec)</code></pre><p>In the above case column <code>start</code> is of type <code>time</code>.</p><p>Let's insert a record in <code>tasks</code> table.</p><pre><code class="language-sql">mysql&gt; INSERT INTO `tasks` (`start`) VALUES ('2000-01-01 12:30:00');</code></pre><p>Now let's query the table.</p><pre><code class="language-sql">mysql&gt; SELECT  `tasks`.* FROM `tasks` WHERE `tasks`.`start` = '2000-01-01 12:30:00' LIMIT 1;Empty set (0.00 sec)</code></pre><p>In the above case query is passing date part(2000-01-01) along with the timepart(12:30:00) for column <code>start</code> and we did not get any result.</p><p>Now let's query again but this time we will pass only the time part to the<code>start</code> column.</p><pre><code class="language-sql">mysql&gt; SELECT  `tasks`.* FROM `tasks` WHERE `tasks`.`start` = '12:30:00' LIMIT 1;+----+----------+| id | start    |+----+----------+|  1 | 12:30:00 |+----+----------+1 row in set (0.00 sec)</code></pre><p>So in the query if we pass <code>2000-01-01 12:30:00</code> to a column which is of type<code>time</code> then MariaDB fails.</p><p>Passing <code>2000-01-01 12:30:00</code> to MySQL, PostgreSQL and SQLite will work fine.That's because the adapters for those databases will drop the date part if dateis passed in the query string.</p><p>For MariaDB similar action was needed and soon enough a<a href="https://github.com/rails/rails/pull/24542">Pull Request</a>, to take care of thisbehavior from Rails side, was landed. MariaDB is itself,<a href="https://jira.mariadb.org/browse/MDEV-9541">working</a> on supporting this behaviornow.</p><h2>Summary</h2><p>In summary Rails 5 officially supports MariaDB and MariaDB can now safely beused as an alternative to MySQL for Ruby on Rails Applications.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Changes to test controllers in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/changes-to-test-controllers-in-rails-5"/>
      <updated>2016-04-19T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/changes-to-test-controllers-in-rails-5</id>
      <content type="html"><![CDATA[<p>In Rails 5, controller tests have undergone some major changes. In this blogpost, we will walk through some of those changes.</p><h3>ActionController::TestCase is deprecated</h3><p>In Rails 5, controller tests are generated with superclass<code>ActionDispatch::IntegrationTest</code> instead of <code>ActionController::TestCase</code> whichis deprecated (Link is not available) . It will be moved into a separate gem inRails 5.1 .</p><p>Rails 5 will use <code>ActionDispatch::IntegrationTest</code> by default for generatingscaffolds as well<a href="https://github.com/rails/rails/pull/22569">controller tests stubs</a>.</p><h3>Use URL instead of action name with request methods in Rails 5</h3><p>In Rails 4.x, we pass controller action as shown below.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionController::TestCase  def test_index_response    get :index    assert_response :success  endend</code></pre><p>But in Rails 5, controller tests expect to receive URL instead of action (Linkis not available). Otherwise test will throw exception<code>URI::InvalidURIError: bad URI</code>.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionDispatch::IntegrationTest  def test_index    get products_url    assert_response :success  endend</code></pre><p>If we are upgrading an older Rails 4.x app to Rails 5, which have test caseswith superclass <code>ActionController::TestCase</code>, then they will continue to work asit is without requiring to change anything from above.</p><h2>Deprecation of assigns and assert_template in controller tests</h2><p>In Rails 4.x, we can test instance variables assigned in a controller action andwhich template a particular controller action renders using <code>assigns</code> and<code>assert_template</code> methods.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionController::TestCase  def test_index_template_rendered    get :index    assert_template :index    assert_equal Product.all, assigns(:products)  endend</code></pre><p>But in Rails 5, calling <code>assert_template</code> or <code>assigns</code> will throw an exception.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionDispatch::IntegrationTest  def test_index_template_rendered    get products_url    assert_template :index    assert_equal Product.all, assigns(:products)  endend# Throws exceptionNoMethodError: assert_template has been extracted to a gem. To continue using it,  add `gem 'rails-controller-testing'` to your Gemfile.</code></pre><p>These two methods have now been<a href="https://github.com/rails/rails/pull/20138">removed</a> from the core and moved toa separate gem<a href="https://github.com/rails/rails-controller-testing">rails-controller-testing</a>.If we still want to use <code>assert_template</code> and <code>assigns</code>, then we can do this byadding this gem in our applications.</p><h2>Reasons for removing assigns and assert_template</h2><p>The idea behind the removal of these methods is that instance variables andwhich template is rendered in a controller action are internals of a controller,and controller tests should not care about them.</p><p>According to Rails team, controller tests should be more concerned about what isthe result of that controller action like what cookies are set, or what HTTPcode is set rather than testing of the internals of the controller. So, thesemethods are removed from the core.</p><h2>Use of Keywords arguments in HTTP request methods in Rails 5</h2><p>In Rails 4.x, we pass various arguments like params, flash messages and sessionvariables to request method directly.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionController::TestCase  def test_show    get :show, { id: user.id }, { notice: 'Welcome' }, { admin: user.admin? }    assert_response :success  endend</code></pre><p>Where <code>{ id: user.id }</code> are params, <code>{ notice: 'Welcome' }</code> is flash and<code>{ admin: user.admin? }</code> is session.</p><p>This becomes confusing sometimes, as it is not clear which argument belongs towhich part.</p><p>Now in Rails 5, request methods accept only<a href="https://github.com/rails/rails/pull/18323/">keyword arguments</a>.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionDispatch::IntegrationTest  def test_create    post product_url, params: { product: { name: &quot;FIFA&quot; } }    assert_response :success  endend</code></pre><p>This makes it easier to understand what arguments are being passed.</p><p>When we pass arguments without keywords arguments, then Rails logs a deprecationwarning.</p><pre><code class="language-ruby">class ProductsControllerTest &lt; ActionDispatch::IntegrationTest  def test_create    post product_url, { product: { name: &quot;FIFA&quot; } }    assert_response :success  endendDEPRECATION WARNING: ActionDispatch::IntegrationTest HTTP request methods will acceptonly the following keyword arguments in future Rails versions:params, headers, env, xhr</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[accessed_fields to find active fields in application]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/accesssed-fields-to-find-actually-used-fileds-in-Rails-5"/>
      <updated>2016-04-18T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/accesssed-fields-to-find-actually-used-fileds-in-Rails-5</id>
      <content type="html"><![CDATA[<p>Rails makes it very easy to select all the fields of a table.</p><pre><code class="language-ruby">@users = User.all</code></pre><p>Above code is selecting all the columns of the table <code>users</code>. This might be okin most cases. However in some cases we might want to select only certaincolumns for performance reason. The difficult task is finding what all columnsare actually used in a request.</p><p>To help in this task, Rails 5 has added<a href="https://github.com/rails/rails/commit/be9b68038e83a617eb38c26147659162e4ac3d2c">accessed_fields</a>method which lists attributes that were actually used in the operation.</p><p>This is helpful in development mode in determining what all fields are reallybeing used by the application.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  def index    @users = User.all  endend</code></pre><pre><code class="language-erb"># app/views/users/index.html.erb&lt;table&gt;  &lt;tr&gt;    &lt;th&gt;Name&lt;/th&gt;    &lt;th&gt;Email&lt;/th&gt;  &lt;/tr&gt;  &lt;% @users.each do |user| %&gt;    &lt;tr&gt;      &lt;td&gt;&lt;%= user.name %&gt;&lt;/td&gt;      &lt;td&gt;&lt;%= user.email %&gt;&lt;/td&gt;    &lt;/tr&gt;  &lt;% end %&gt;&lt;/table&gt;</code></pre><p>Now, in order to find all the fields that were actually used, let's add<code>after_action</code> to the controller.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  after_action :print_accessed_fields  def index    @users = User.all  end  private  def print_accessed_fields    p @users.first.accessed_fields  endend</code></pre><p>Let's take a look at the log file.</p><pre><code class="language-plaintext">Processing by UsersController#index as HTML  User Load (0.1ms) SELECT &quot;users&quot;.* FROM &quot;users&quot;  Rendered users/index.html.erb within layouts/application (1.0ms)  [&quot;name&quot;, &quot;email&quot;]</code></pre><p>As we can see, it returns <code>[&quot;name&quot;, &quot;email&quot;]</code> as attributes which were actuallyused.</p><p>If <code>users</code> table has 20 columns then we do not need to load values all thoseother columns. We are using only two columns. So let's change code to reflectthat.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  def index    @users = User.select(:name, :email)  endend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Warning when fetching with Active Record]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-option-to-log-warning-when-fetching-big-result-sets"/>
      <updated>2016-04-13T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-option-to-log-warning-when-fetching-big-result-sets</id>
      <content type="html"><![CDATA[<p>With large data set we can run into memory issue. Here is an example.</p><pre><code class="language-ruby">&gt;&gt; Post.published.count=&gt; 25000&gt;&gt; Post.where(published: true).each do |post|     post.archive!   end# Loads 25000 posts in memory</code></pre><h2>Rails 5 adds warning when loading large data set</h2><p>To mitigate issue shown above Rails 5<a href="https://github.com/rails/rails/pull/18846">has added</a><code>config.active_record.warn_on_records_fetched_greater_than</code>.</p><p>When this configuration is set to an integer value, any query that returns thenumber of records greater than the set limit, logs a warning.</p><pre><code class="language-ruby">config.active_record.warn_on_records_fetched_greater_than = 1500&gt;&gt; Post.where(published: true).each do |post|     post.archive!   end=&gt; Query fetched 25000 Post records: SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;published&quot; = ? [[&quot;published&quot;, true]]   [#&lt;Post id: 1, title: 'Rails', user_id: 1, created_at: &quot;2016-02-11 11:32:32&quot;, updated_at: &quot;2016-02-11 11:32:32&quot;, published: true&gt;, #&lt;Post id: 2, title: 'Ruby', user_id: 2, created_at: &quot;2016-02-11 11:36:05&quot;, updated_at: &quot;2016-02-11 11:36:05&quot;, published: true&gt;,....]</code></pre><p>This helps us find areas where potential problems exist and then we can replaceinefficient queries with better ones.</p><pre><code class="language-ruby">config.active_record.warn_on_records_fetched_greater_than = 1500&gt;&gt; Post.where(published: true).find_each do |post|     post.archive!   end# No warning is logged</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 Sending STDOUT via environment variable]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-to-send-log-to-stdout-via-environment-variable"/>
      <updated>2016-04-12T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-to-send-log-to-stdout-via-environment-variable</id>
      <content type="html"><![CDATA[<p>By default, Rails creates <code>log</code> directory in a file that is named after theenvironment in which the application is running. So in production environment,logs are by default directed to <code>production.log</code> file.</p><p>We will have to define custom loggers if these logs are to be directed toanother file or to standard output. Presence of such custom logic is whatenables Rails to direct logs to <code>STDOUT</code> along with <code>development.log</code> file indevelopment environment.</p><p>Rails 5, however,<a href="https://github.com/rails/rails/pull/23734">supports logging to STDOUT</a> inproduction environment through introduction of new environment variable<code>RAILS_LOG_TO_STDOUT</code>.</p><p>In a brand new Rails app, we can see the following snippet in <code>production.rb</code>file.</p><pre><code class="language-ruby">if ENV[&quot;RAILS_LOG_TO_STDOUT&quot;].present?  config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))end</code></pre><p>By setting <code>RAILS_LOG_TO_STDOUT</code> to any value we should have the production logsdirected to <code>STDOUT</code>.</p><p>We can see in the snippet above <code>config.logger</code> is overwritten. Therefore nowthe logs will not be directed to <code>production.log</code> file.</p><p>To opt out of this and revert to the original functionality, we can eitherassign a blank value to this environment constant or remove<code>RAILS_LOG_TO_STDOUT</code> from the list of environment constants.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Validate multiple contexts together in Rails 5]]></title>
       <author><name>Vijay Kumar Agrawal</name></author>
      <link href="https://www.bigbinary.com/blog/validate-multiple-contexts-in-rails-5"/>
      <updated>2016-04-08T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/validate-multiple-contexts-in-rails-5</id>
      <content type="html"><![CDATA[<p>Active Record<a href="http://guides.rubyonrails.org/active_record_validations.html">validation</a> is awell-known and widely used functionality of Rails. Slightly lesser popular isRails's ability to validate on custom context.</p><p>If used properly, contextual validations can result in much cleaner code. Tounderstand validation context, we will take example of a form which is submittedin multiple steps:</p><pre><code class="language-ruby">class MultiStepForm &lt; ActiveRecord::Base  validate :personal_info  validate :education, on: :create  validate :work_experience, on: :update  validate :final_step, on: :submission  def personal_info    # validation logic goes here..  end  # Smiliary all the validation methods go here.end</code></pre><p>Let's go through all the four validations one-by-one.</p><p><em>1. personal_info</em> validation has no context defined (notice the absence of<code>on:</code>). Validations with no context are executed every time a model save istriggered. Please go through all the triggers<a href="http://guides.rubyonrails.org/active_record_validations.html">here</a>.</p><p><em>2. education</em> validation has context of <code>:create</code>. It is executed <em>only</em> when anew object is created.</p><p><em>3. work_experience</em> validation is in <code>:update</code> context and gets triggered forupdates <em>only</em>. <code>:create</code> and <code>:update</code> are the only two pre-defined contexts.</p><p><em>4. final_step</em> is validated using a custom context named <code>:submission</code>. Unlikeabove scenarios, it needs to be explicitly triggered like this:</p><pre><code class="language-ruby">form = MultiStepForm.new# Eitherform.valid?(:submission)# Orform.save(context: :submission)</code></pre><p><code>valid?</code> runs the validation in given context and populates <code>errors</code>. <code>save</code>would first call <code>valid?</code> in the given context and persist the changes ifvalidations pass. Otherwise populates <code>errors</code>.</p><p>One thing to note here is that when we validate using an explicit context, Railsbypasses all other <em>contexts</em> including <code>:create</code> and <code>:update</code>.</p><p>Now that we understand validation context, we can switch our focus to <em>validatemultiple context together</em><a href="https://github.com/rails/rails/pull/21535">enhancement</a> in Rails 5.</p><p>Let's change our contexts from above example to</p><pre><code class="language-ruby">class MultiStepForm &lt; ActiveRecord::Base  validate :personal_info, on: :personal_submission  validate :education, on: :education_submission  validate :work_experience, on: :work_ex_submission  validate :final_step, on: :final_submission  def personal_info    # code goes here..  end  # Smiliary all the validation methods go here.end</code></pre><p>For each step, we would want to validate the model with all previous steps andavoid all future steps. Prior to Rails 5, this can be achieved like this:</p><pre><code class="language-ruby">class MultiStepForm &lt; ActiveRecord::Base  #...  def save_personal_info    self.save if self.valid?(:personal_submission)  end  def save_education    self.save if self.valid?(:personal_submission)              &amp;&amp; self.valid?(:education_submission)  end  def save_work_experience    self.save if self.valid?(:personal_submission)              &amp;&amp; self.valid?(:education_submission)              &amp;&amp; self.valid?(:work_ex_submission)  end  # And so on...end</code></pre><p>Notice that <code>valid?</code> takes only one context at a time. So we have to repeatedlycall <code>valid?</code> for each context.</p><p>This gets simplified in Rails 5 by enhancing <code>valid?</code> and <code>invalid?</code> to acceptan array. Our code changes to:</p><pre><code class="language-ruby">class MultiStepForm &lt; ActiveRecord::Base  #...  def save_personal_info    self.save if self.valid?(:personal_submission)  end  def save_education    self.save if self.valid?([:personal_submission,                              :education_submission])  end  def save_work_experience    self.save if self.valid?([:personal_submission,                              :education_submission,                              :work_ex_submission])  endend</code></pre><p>A tad bit cleaner I would say.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 changes protect_from_forgery execution order]]></title>
       <author><name>Vijay Kumar Agrawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-default-protect-from-forgery-prepend-false"/>
      <updated>2016-04-06T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-default-protect-from-forgery-prepend-false</id>
      <content type="html"><![CDATA[<p>What makes Rails a great framework to work with is its sane<a href="http://rubyonrails.org/doctrine/#convention-over-configuration">conventions over configuration</a>.Rails community is always striving to keep these conventions relevant over time.In this blog, we will see why and what changed in execution order of<code>protect_from_forgery</code>.</p><p><code>protect_from_forgery</code> protects applications against <a href="csrf-and-rails">CSRF</a>.Follow that link to read up more about <code>CSRF</code>.</p><h3>What</h3><p>If we generate a brand new Rails application in Rails 4.x then<code>application_controller</code> will look like this.</p><pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base  protect_from_forgery with: :exceptionend</code></pre><p>Looking it at the code it does not look like <code>protect_from_forgery</code> is a<code>before_action</code> call but in reality that's what it is. Since<code>protect_from_forgery</code> is a <code>before_action</code> call it should follow the order ofhow other <code>before_action</code> are executed. But this one is special in the sensethat <code>protect_from_forgery</code> is executed first in the series of <code>before_action</code>no matter where <code>protect_from_forgery</code> is mentioned. Let's see an example.</p><pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base  before_action :load_user  protect_from_forgery with: :exceptionend</code></pre><p>In the above case even though <code>protect_from_forgery</code> call is made after<code>load_user</code>, the protection execution happens first. And we can't do anythingabout it. We can't pass any option to stop Rails from doing this.</p><p>Rails 5<a href="https://github.com/rails/rails/commit/39794037817703575c35a75f1961b01b83791191">changes</a>this behavior by introducing a <code>boolean</code> option called <code>prepend</code>. Default valueof this option is <code>false</code>. What it means is, now <code>protect_from_forgery</code> getsexecuted in order of call. Of course, this can be overridden by passing<code>prepend: true</code> as shown below and now protection call will happen first justlike Rails 4.x.</p><pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base  before_action :load_user  protect_from_forgery with: :exception, prepend: trueend</code></pre><h2>Why</h2><p>There isn't any real advantage in forcing <code>protect_from_forgery</code> to be the firstfilter in the chain of filters to be executed. On the flip side, there are caseswhere output of other <code>before_action</code> should decide the execution of<code>protect_from_forgery</code>. Let's see an example.</p><pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base  before_action :authenticate  protect_from_forgery unless: -&gt; { @authenticated_by.oauth? }  private    def authenticate      if oauth_request?        # authenticate with oauth        @authenticated_by = 'oauth'.inquiry      else        # authenticate with cookies        @authenticated_by = 'cookie'.inquiry      end    endend</code></pre><p>Above code would fail in Rails 4.x, as <code>protect_from_forgery</code>, though calledafter <code>:authenticate</code>, actually gets executed before it. Due to which we wouldnot have <code>@authenticated_by</code> set properly.</p><p>Whereas in Rails 5, <code>protect_from_forgery</code> gets executed after <code>:authenticate</code>and gets skipped if authentication is oauth.</p><h2>Upgrading to Rails 5</h2><p>Let's take an example to understand how this change might affect the upgrade ofapplications from Rails 4 to Rails 5.</p><pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base  before_action :set_access_time  protect_from_forgery  private    def set_access_time      current_user.access_time = Time.now      current_user.save    endend</code></pre><p>In Rails 4.x, <code>set_access_time</code> is <strong>not</strong> executed for <em>bad requests</em>. But itgets executed in Rails 5 because <code>protect_from_forgery</code> is called after<code>set_access_time</code>.</p><p>Saving data (<code>current_user.save</code>) in <code>before_action</code> is anyways a big enoughviolation of the best practices, but now those persistences would leave usvulnerable to CSRF if they are called before <code>protect_from_forgery</code> is called.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 provides config to use UUID as primary key]]></title>
       <author><name>Vijay Kumar Agrawal</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-provides-application-config-to-use-UUID-as-primary-key"/>
      <updated>2016-04-04T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-provides-application-config-to-use-UUID-as-primary-key</id>
      <content type="html"><![CDATA[<p>UUIDs are a popular alternative to auto-incremental integer primary keys.</p><pre><code class="language-ruby">create_table :users, id: :uuid do |t|  t.string :nameend</code></pre><p>Notice that <code>id: :uuid</code> is passed to create_table. This is all we need to do tohave UUID as primary key for <code>users</code>.</p><p>Now, if an application is designed to use UUID instead of Integer, then chancesare that new tables too would use UUID as primary key. And it can easily getrepetitive to add <code>id: :uuid</code> in <code>create_table</code> , every time a new model isgenerated.</p><p>Rails 5 comes up with <a href="https://github.com/rails/rails/pull/22033">a solution</a>.We need to set primary key as UUID in <code>config/application.rb</code>.</p><pre><code class="language-ruby">config.generators do |g|  g.orm :active_record, primary_key_type: :uuidend</code></pre><p>This automatically adds <code>id: :uuid</code> to <code>create_table</code> in all future migrations.</p><p>If we are using the latest version of PostgreSQL then we should enable<code>pgcrypto</code> extension as per<a href="https://guides.rubyonrails.org/active_record_postgresql.html#uuid">Rails guide</a>.</p><p>To enable <a href="https://www.postgresql.org/docs/8.3/pgcrypto.html">pgcrypto</a>extension we need a migration which does something like this.</p><pre><code class="language-ruby">class EnablePgcryptoExtension &lt; ActiveRecord::Migration  def change    enable_extension 'pgcrypto'  endend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 changed Active Job default adapter to Async]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-changed-default-active-job-adapter-to-async"/>
      <updated>2016-03-29T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-changed-default-active-job-adapter-to-async</id>
      <content type="html"><![CDATA[<p>Active Job has built-in adapters for multiple queuing backends among which twoare intended for development and testing. They are<a href="http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/InlineAdapter.html">Active Job Inline Adapter</a>and<a href="http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/AsyncAdapter.html">Active Job Async Adapter</a>.</p><p>These adapters can be configured as follows.</p><pre><code class="language-ruby"># for Active Job InlineRails.application.config.active_job.queue_adapter = :inline# for Active Job AsyncRails.application.config.active_job.queue_adapter = :async</code></pre><p>In Rails 4.x the default queue adapter is <code>:inline</code>. In Rails 5 it has<a href="https://github.com/rails/rails/commit/625baa69d14881ac49ba2e5c7d9cac4b222d7022">been changed to</a><code>:async</code> by DHH.</p><h2>Asynchronous Execution</h2><p>In case of <code>inline</code>, as the name suggests, execution of the job happens in thesame process that invokes the job. In case of Async adapter, the job is executedasynchronously using in-process thread pool.</p><p><code>AsyncJob</code> makes use of a<a href="https://github.com/ruby-concurrency/concurrent-ruby">concurrent-ruby</a> threadpool and the data is retained in memory. Since the data is stored in memory, ifthe application restarts, this data is lost. Hence, <code>AsyncJob</code> should not beused in production.</p><h2>Running in future</h2><p><code>AsyncJob</code> supports running the job at some time in future through<code>perform_later</code>. <code>Inline</code> executes the job immediately and does not supportrunning the job in future.</p><p>Both Active Job Async and Active Job Inline do not support configuringpriorities among queues, timeout in execution and retry intervals/counts.</p><h2>Advantage of having Async as default adapter</h2><p>In Rails 4.x where <code>Inline</code> is the default adapter, the test cases weremistakenly dependent on job's behavior that happens synchronously indevelopment/testing environment. Using <code>Async</code> adapter ,by default, will helpusers have tests not rely on such synchronous behavior.</p><p>It's a step closer to simulating your production environment where jobs areexecuted asynchronously with more persistent backends.</p><p>Consider an example, where in an e-commerce site upon every order placed anemail is sent.</p><pre><code class="language-ruby">test &quot;order is created successfully&quot; do  # Code to test record in orders table is createdendtest &quot;order email is sent&quot; do  # Code to test order email is sentend</code></pre><p>The process of sending email can be part of a job which is invoked from an<code>after_create</code> callback in <code>Order</code> model.</p><pre><code class="language-ruby">class Order &lt; ActiveRecord::Base  after_create :send_order_email  def send_order_email    # Invoke the job of sending an email asynchronously.  endend</code></pre><p>When <code>Inline</code> adapter is used, any wrongly configured email settings will causeboth the above tests to fail. This is because the process of sending the emailhappens within the process of order creation and any error in sending the emailwould kill the process if unhandled.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Support for left outer join in Rails 5]]></title>
       <author><name>Ratnadeep Deshmane</name></author>
      <link href="https://www.bigbinary.com/blog/support-for-left-outer-joins-in-rails-5"/>
      <updated>2016-03-24T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/support-for-left-outer-joins-in-rails-5</id>
      <content type="html"><![CDATA[<p>Suppose in a blog application there are authors and posts. A post belongs to anauthor, while author has many posts.</p><p>The app needs to show a list of all the authors along with a number of poststhat they have written.</p><p>For this, we need to join author and posts table with &quot;left outer join&quot;. Moreabout &quot;left outer join&quot;<a href="http://blog.codinghorror.com/a-visual-explanation-of-sql-joins">here</a>,<a href="http://www.dofactory.com/sql/left-outer-join">here</a> and<a href="http://stackoverflow.com/questions/406294/left-join-and-left-outer-join-in-sql-server">here</a>.</p><p>In Rails 4.x, we need to write the SQL for left outer join manually as ActiveRecord does not have support for outer joins.</p><pre><code class="language-ruby">authors = Author.join('LEFT OUTER JOIN &quot;posts&quot; ON &quot;posts&quot;.&quot;author_id&quot; = &quot;authors&quot;.&quot;id&quot;')                .uniq                .select(&quot;authors.*, COUNT(posts.*) as posts_count&quot;)                .group(&quot;authors.id&quot;)</code></pre><p>Rails 5 has <a href="https://github.com/rails/rails/pull/12071">added left_outer_joins</a>method.</p><pre><code class="language-ruby">authors = Author.left_outer_joins(:posts)                .uniq                .select(&quot;authors.*, COUNT(posts.*) as posts_count&quot;)                .group(&quot;authors.id&quot;)</code></pre><p>It also allows to perform the left join on multiple tables at the same time.</p><pre><code class="language-ruby">&gt;&gt; Author.left_joins :posts, :comments  Author Load (0.1ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; LEFT OUTER JOIN &quot;posts&quot; ON &quot;posts&quot;.&quot;author_id&quot; = &quot;authors&quot;.&quot;id&quot; LEFT OUTER JOIN &quot;comments&quot; ON &quot;comments&quot;.&quot;author_id&quot; = &quot;authors&quot;.&quot;id&quot;</code></pre><p>If you feel <code>left_outer_joins</code> is too long to type, then Rails 5 also has analias method <code>left_joins</code>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[has_secure_token for unique random token in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/has-secure-token-to-generate-unique-random-token-in-rails-5"/>
      <updated>2016-03-23T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/has-secure-token-to-generate-unique-random-token-in-rails-5</id>
      <content type="html"><![CDATA[<p>We sometimes need unique and random tokens in our web apps. Here is how wetypically build it.</p><pre><code class="language-ruby">class User &lt; ActiveRecord::Base  before_create :set_access_token  private  def set_access_token    self.access_token = generate_token  end  def generate_token    loop do      token = SecureRandom.hex(10)      break token unless User.where(access_token: token).exists?    end  endend</code></pre><h2>has_secure_token in Rails 5</h2><p>Rails 5<a href="https://github.com/rails/rails/pull/18217">has added has_secure_token method</a>to generate a random alphanumeric token for a given column.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  has_secure_tokenend</code></pre><p>By default, Rails assumes that the attribute name is <code>token</code>. We can provide adifferent name as a parameter to <code>has_secure_token</code> if the attribute name is not<code>token</code>.</p><pre><code class="language-ruby">class User &lt; ApplicationRecord  has_secure_token :password_reset_tokenend</code></pre><p>The above code assumes that we already have <code>password_reset_token</code> attribute inour model.</p><pre><code class="language-ruby">&gt;&gt; user = User.new&gt;&gt; user.save=&gt; true&gt;&gt; user.password_reset_token=&gt; 'qjCbex522DfVEVd5ysUWppWQ'</code></pre><p>The generated tokens are URL safe and are of fixed length strings.</p><h2>Migration helper for generating token</h2><p>We can also <a href="https://github.com/rails/rails/pull/18448">generate</a> migration fortoken similar to other data types.</p><pre><code class="language-paintext">$ rails g migration add_auth_token_to_user auth_token:token</code></pre><pre><code class="language-ruby">class AddAuthTokenToUser &lt; ActiveRecord::Migration[5.0]  def change    add_column :users, :auth_token, :string    add_index :users, :auth_token, unique: true  endend</code></pre><p>Notice that migration automatically adds index on the generated column withunique constraint.</p><p>We can also generate a model with the token attribute.</p><pre><code class="language-plaintext">$ rails g model Product access_token:token</code></pre><pre><code class="language-ruby">class CreateProducts &lt; ActiveRecord::Migration[5.0]  def change    create_table :products do |t|      t.string :access_token      t.timestamps    end    add_index :products, :access_token, unique: true  endend</code></pre><p>Model generator also adds <code>has_secure_token</code> method to the model.</p><pre><code class="language-ruby">class Product &lt; ApplicationRecord  has_secure_token :access_tokenend</code></pre><h2>Regenerating tokens</h2><p>Sometimes we need to regenerate the tokens based on some expiration criteria.</p><p>In order to do that, we can simply call <code>regenerate_#{token_attribute_name}</code>which would regenerate the token and save it to its respective attribute.</p><pre><code class="language-ruby">&gt;&gt; user = User.first=&gt; &lt;User id: 11, name: 'John', email: 'john@example.com',         token: &quot;jRMcN645BQyDr67yHR3qjsJF&quot;,         password_reset_token: &quot;qjCbex522DfVEVd5ysUWppWQ&quot;&gt;&gt;&gt; user.password_reset_token=&gt; &quot;qjCbex522DfVEVd5ysUWppWQ&quot;&gt;&gt; user.regenerate_password_reset_token=&gt; true&gt;&gt; user.password_reset_token=&gt; &quot;tYYVjnCEd1LAXvmLCyyQFzbm&quot;</code></pre><h2>Beware of race condition</h2><p>It is possible to generate a race condition in the database while generating thetokens. So it is advisable to add a unique index in the database to deal withthis unlikely scenario.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Suppress save events in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/suppress-save-events-in-rails-5"/>
      <updated>2016-03-11T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/suppress-save-events-in-rails-5</id>
      <content type="html"><![CDATA[<p>Rails 5 added <a href="https://github.com/rails/rails/pull/18910">suppress</a> method whichis used to prevent the receiver from being saved during the given block.</p><h2>Use case for suppress method</h2><p>Let's say, we have an E-commerce application, which has many products. Whenevernew product is launched then subscribed customers are notified about it.</p><pre><code class="language-ruby">class Product &lt; ApplicationRecord  has_many :notifications  belongs_to :seller  after_save :send_notification  def launch!    update_attributes!(launched: true)  end  private  def send_notification    notifications.create(message: 'New product Launched', seller: seller)  endendclass Notification &lt; ApplicationRecord  belongs_to :product  belongs_to :seller  after_create :send_notifications  private  def send_notifications    # Sends notification about product to customers.  endendclass Seller &lt; ApplicationRecord  has_many :productsend</code></pre><p>This creates a notification record every time we launch a product.</p><pre><code class="language-ruby">&gt;&gt; Notification.count=&gt; 0&gt;&gt; seller = Seller.last=&gt; &lt;Seller id: 6, name: &quot;John&quot;&gt;&gt;&gt; product = seller.products.create(name: 'baseball hat')=&gt; &lt;Product id: 4, name: &quot;baseball hat&quot;, seller_id: 6&gt;&gt;&gt; product.launch!&gt;&gt; Notification.count=&gt; 1</code></pre><p>Now, we have a situation where we need to launch a product but we don't want tosend notifications about it.</p><p>Before Rails 5, this was possible only by adding more conditions.</p><h2>ActiveRecord::Base.Suppress in Rails 5</h2><p>In Rails 5, we can use <code>ActiveRecord::Base.suppress</code> method to suppress creatingof notifications as shown below.</p><pre><code class="language-ruby">class Product &lt; ApplicationRecord  def launch_without_notifications    Notification.suppress do      launch!    end  endend&gt;&gt; Notification.count=&gt; 0&gt;&gt; product = Product.create!(name: 'tennis hat')=&gt; &lt;Event id: 1, name: &quot;tennis hat&quot;&gt;&gt;&gt; product.launch_without_notifications&gt;&gt; Notification.count=&gt; 0</code></pre><p>As we can see, no new notifications were created when product is launched inside<code>Notification.suppress</code> block.</p><p>Checkout <a href="https://github.com/rails/rails/pull/18910">the pull request</a> to gainbetter understanding of how <code>suppress</code> works.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 improves rendering partial from cache]]></title>
       <author><name>Ratnadeep Deshmane</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-makes-partial-redering-from-cache-substantially-faster"/>
      <updated>2016-03-09T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-makes-partial-redering-from-cache-substantially-faster</id>
      <content type="html"><![CDATA[<p>Let's have a look at Rails view code that renders partial using a collection.</p><pre><code class="language-erb"># index.html.erb&lt;%= render partial: 'todo', collection: @todos %&gt;# _todo.html.erb&lt;% cache todo do %&gt;  &lt;%= todo.name %&gt;&lt;% end %&gt;</code></pre><p>In the above case Rails will do one fetch from the cache for each todo.</p><p>Fetch is usually pretty fast with any caching solution, however, one fetch pertodo can make the app slow.</p><p>Gem <a href="https://github.com/n8/multi_fetch_fragments">multi_fetch_fragments</a> fixedthis issue by using<a href="http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-read_multi">read_multi</a>api provided by Rails.</p><p>In a single call to cache, this gem fetches all the cache fragments for acollection. The author of the gem saw<a href="http://ninjasandrobots.com/rails-faster-partial-rendering-and-caching">78% speed improvement</a>by using this gem.</p><p>The features of this gem<a href="https://github.com/rails/rails/pull/18948">have been folded into Rails 5</a>.</p><p>To get benefits of collection caching, just add <code>cached: true</code> as shown below.</p><pre><code class="language-erb"># index.html.erb&lt;%= render partial: 'todo', collection: @todos, cached: true %&gt;# _todo.html.erb&lt;% cache todo do %&gt;  &lt;%= todo.name %&gt;&lt;% end %&gt;</code></pre><p>With <code>cached: true</code> present, Rails will use <code>read_multi</code> to the cache storeinstead of reading from it every partial.</p><p>Rails will also log cache hits in the logs as below.</p><pre><code class="language-plaintext">  Rendered collection of todos/_todo.html.erb [100 / 100 cache hits] (339.5ms)</code></pre><p>Checkout <a href="https://github.com/rails/rails/pull/23695">the pull request</a> to gainbetter understanding about how collection caching works.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 switches from strong etags to weak etags]]></title>
       <author><name>Prajakta Tambe</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-switches-from-strong-etags-to-weak-tags"/>
      <updated>2016-03-08T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-switches-from-strong-etags-to-weak-tags</id>
      <content type="html"><![CDATA[<p><a href="https://en.wikipedia.org/wiki/HTTP_ETag">ETag</a>, short for entity tag, is a partof HTTP header and is used for web cache validation. ETag is a digest of theresource that uniquely identifies specific version of the resource. This helpsbrowser and web servers determine if resource in the browser's cache is exactlysame as the resource on the server.</p><h3>Strong v/s Weak ETags</h3><p>ETag supports<a href="https://tools.ietf.org/html/rfc2616#section-13.3.3">strong and weak validation</a>of the resource.</p><p>Strong ETag indicates that resource content is same for response body and theresponse headers.</p><p>Weak ETag indicates that the two representations are semantically equivalent. Itcompares only the response body.</p><p>Weak ETags are<a href="https://github.com/rails/rails/blob/a61bf5f5b63780a3e0b4c2d4339967df82b370de/actionpack/lib/action_dispatch/http/cache.rb#L91-L94">prefixed with</a><code>W\</code> and thus one can easily distinguish between Weak ETags and Strong ETags.</p><pre><code class="language-plaintext">&quot;543b39c23d8d34c232b457297d38ad99&quot;     Strong ETagW/&quot;543b39c23d8d34c232b457297d38ad99&quot;   Weak ETag</code></pre><p>W3 has<a href="https://www.w3.org/Protocols/HTTP/1.1/rfc2616bis/issues/#i71">an example</a> pageto illustrate how ETag matching works.</p><p>When server receives a request, it returns an ETag header as part of HTTPresponse. This ETag represents state of the resource. For the subsequent HTTPrequests, client sends this ETag via <code>If-None-Match</code> header to identify if theresource is changed or not. The server will compare the current ETag and the onesent by the client. If ETag matches, server responds with <code>304 Not modified</code>.This means resource content in the client's cache is up-to-date. If resource ischanged, server will send updated resource along with the new ETag.</p><p>Let's see it in action.</p><h2>ETags in Rails 4.x</h2><p>Rails 4.x generates strong ETags by default i.e without <code>W/</code> prefix.</p><pre><code class="language-ruby">class ItemsController &lt; ApplicationController  def show    @item = Item.find(params[:id])    fresh_when @item  endend</code></pre><p>We are making first request to the server.</p><pre><code class="language-plaintext">$ curl -i http://localhost:3000/items/1HTTP/1.1 200 OKX-Frame-Options: SAMEORIGINX-Xss-Protection: 1; mode=blockX-Content-Type-Options: nosniffEtag: &quot;618bbc92e2d35ea1945008b42799b0e7&quot;Last-Modified: Sat, 30 Jan 2016 08:02:12 GMTContent-Type: text/html; charset=utf-8Cache-Control: max-age=0, private, must-revalidateX-Request-Id: 98359119-14ae-4e4e-8174-708abbc3fd4bX-Runtime: 0.412232Server: WEBrick/1.3.1 (Ruby/2.2.2/2015-04-13)Date: Fri, 04 Mar 2016 10:50:38 GMTContent-Length: 1014Connection: Keep-Alive</code></pre><p>For the next request, we will send ETag that was sent by the sever. And noticethat server returns <code>304 Not Modified</code>.</p><pre><code class="language-plaintext">$ curl -i -H 'If-None-Match: &quot;618bbc92e2d35ea1945008b42799b0e7&quot;' http://localhost:3000/items/1HTTP/1.1 304 Not ModifiedX-Frame-Options: SAMEORIGINX-Xss-Protection: 1; mode=blockX-Content-Type-Options: nosniffEtag: &quot;618bbc92e2d35ea1945008b42799b0e7&quot;Last-Modified: Sat, 30 Jan 2016 08:02:12 GMTCache-Control: max-age=0, private, must-revalidateX-Request-Id: e4447f82-b96c-4482-a5ff-4f5003910c18X-Runtime: 0.012878Server: WEBrick/1.3.1 (Ruby/2.2.2/2015-04-13)Date: Fri, 04 Mar 2016 10:51:22 GMTConnection: Keep-Alive</code></pre><h2>Rails 5 sets Weak ETags by default</h2><p>In Rails 5, all ETags generated by Rails will be<a href="https://github.com/rails/rails/pull/17573">weak by default</a>.</p><pre><code class="language-plaintext">$ curl -i http://localhost:3000/items/1HTTP/1.1 200 OKX-Frame-Options: SAMEORIGINX-Xss-Protection: 1; mode=blockX-Content-Type-Options: nosniffEtag: W/&quot;b749c4dd1b20885128f9d9a1a8ba70b6&quot;Last-Modified: Sat, 05 Mar 2016 00:00:00 GMTContent-Type: text/html; charset=utf-8Cache-Control: max-age=0, private, must-revalidateX-Request-Id: a24b986c-74f0-4e23-9b1d-0b52cb3ef906X-Runtime: 0.038372Server: WEBrick/1.3.1 (Ruby/2.2.3/2015-08-18)Date: Fri, 04 Mar 2016 10:48:35 GMTContent-Length: 1906Connection: Keep-Alive</code></pre><p>Now for the second request, server will return <code>304 Not Modified</code> response asbefore, but the ETag is weak ETag.</p><pre><code class="language-plaintext">$ curl -i -H 'If-None-Match: W/&quot;b749c4dd1b20885128f9d9a1a8ba70b6&quot;' http://localhost:3000/items/1HTTP/1.1 304 Not ModifiedX-Frame-Options: SAMEORIGINX-Xss-Protection: 1; mode=blockX-Content-Type-Options: nosniffEtag: W/&quot;b749c4dd1b20885128f9d9a1a8ba70b6&quot;Last-Modified: Sat, 05 Mar 2016 00:00:00 GMTCache-Control: max-age=0, private, must-revalidateX-Request-Id: 7fc8a8b9-c7ff-4600-bf9b-c847201973ccX-Runtime: 0.005469Server: WEBrick/1.3.1 (Ruby/2.2.3/2015-08-18)Date: Fri, 04 Mar 2016 10:49:27 GMTConnection: Keep-Alive</code></pre><h2>Why this change?</h2><p>Rails does not perform strong validation of ETags as implied by strong ETagsspec. Rails just checks whether the incoming ETag from the request headersmatches with the ETag of the generated response. It does not do byte by bytecomparison of the response.</p><p>This was true even before Rails 5. So this change is more of a coursecorrection. Rack also<a href="https://github.com/rack/rack/issues/681">generates weak ETags</a> by defaultbecause of similar reasons.</p><p><a href="https://twitter.com/mnot">Mark Notthingham</a> is chair of<a href="http://httpwg.org">HTTP Working Group</a> and he<a href="https://www.mnot.net/blog/2007/08/07/etags">has written about etags</a> which hassome useful links to other ETag resources.</p><h3>How to use strong ETags in Rails 5</h3><p>If we want to bypass default Rails 5 behavior to use strong ETags then we can doby following way.</p><pre><code class="language-ruby">class ItemsController &lt; ApplicationController  def show    @item = Item.find(params[:id])    fresh_when strong_etag: @item  endend</code></pre><p>This will generate strong Etag i.e without <code>W/</code> prefix.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Parameter filtering enhancement in Rails 5]]></title>
       <author><name>Vijay Kumar Agrawal</name></author>
      <link href="https://www.bigbinary.com/blog/parameter-filtering-enhacement-rails-5"/>
      <updated>2016-03-07T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/parameter-filtering-enhacement-rails-5</id>
      <content type="html"><![CDATA[<p>For security reasons, we do not want sensitive data like passwords, credit cardinformation, auth keys etc to appear in log files.</p><p>Rails makes it very easy to filter such data. Just add following line in<code>application.rb</code> to filter sensitive information.</p><pre><code class="language-ruby">config.filter_parameters += [:password]</code></pre><p>Now the log file will show <code>[FILTERED]</code> instead of real password value.</p><p>This replacement of <code>password</code> with <code>[FILTERED]</code> is done recursively.</p><pre><code class="language-ruby">{user_name: &quot;john&quot;, password: &quot;123&quot;}{user: {name: &quot;john&quot;, password: &quot;123&quot;}}{user: {auth: {id: &quot;john&quot;, password: &quot;123&quot;}}}</code></pre><p>In all the above cases, &quot;123&quot; would be replaced by &quot;[FILTERED]&quot;.</p><p>Now think of a situation where we do not want to filter all the occurrence of akey. Here is an example.</p><pre><code class="language-ruby">{credit_card: {number: &quot;123456789&quot;, code: &quot;999&quot;}}{user_preference: {color: {name: &quot;Grey&quot;, code: &quot;999999&quot;}}}</code></pre><p>We definitely want to filter <code>[:credit_card][:code]</code> but we want<code>[:color][:code]</code> to show up in the log file.</p><p>This <a href="https://github.com/rails/rails/pull/13897">can be achieved in Rails 5</a>.</p><p>The application.rb changes from</p><pre><code class="language-ruby">config.filter_parameters += [&quot;code&quot;]</code></pre><p>to</p><pre><code class="language-ruby">config.filter_parameters += [&quot;credit_card.code&quot;]</code></pre><p>In this case so long as parent of <code>code</code> is <code>credit_card</code> Rails will filter thedata.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 adds http_cache_forever]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-adds-http-cache-forever"/>
      <updated>2016-03-04T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-adds-http-cache-forever</id>
      <content type="html"><![CDATA[<p>Rails 5 allows to<a href="https://github.com/rails/rails/pull/18394">cache HTTP responses forever</a> byintroducing <code>http_cache_forever</code> method.</p><p>Sometimes, we have static pages that never/rarely change.</p><pre><code class="language-ruby"># app/controllers/home_controller.rbclass HomeController &lt; ApplicationController  def index    render  endend# app/views/home/index.html.erb&lt;h1&gt;Welcome&lt;/h1&gt;</code></pre><p>Let's see log for the above action.</p><pre><code class="language-plaintext">Processing by HomeController#index as HTML  Rendered home/index.html.erb within layouts/application (1.3ms)Completed 200 OK in 224ms (Views: 212.4ms | ActiveRecord: 0.0ms) And so on for every request for this action.</code></pre><p>There is no change in the response and still we are rendering same thing againand again and again.</p><h2>Rails 5 introduces http_cache_forever</h2><p>When response does not change then we want browsers and proxies to cache it fora long time.</p><p>Method <code>http_cache_forever</code> allows us to set response headers to tell browsersand proxies that response has not modified.</p><pre><code class="language-ruby"># app/controllers/home_controller.rbclass HomeController &lt; ApplicationController  def index    http_cache_forever(public: true) {}  endend# ORclass HomeController &lt; ApplicationController  def index    http_cache_forever(public: true) do      render    end  endend# app/views/home/index.html.erb&lt;h1&gt;Welcome&lt;/h1&gt;</code></pre><p>Now let's look at the log for the modified code.</p><pre><code class="language-plaintext"># When request is made for the first time.Processing by HomeController#index as HTML  Rendered home/index.html.erb within layouts/application (1.3ms)Completed 200 OK in 224ms (Views: 212.4ms | ActiveRecord: 0.0ms)# For consecutive requests for the same pageProcessing by HomeController#index as HTMLCompleted 304 Not Modified in 2ms (ActiveRecord: 0.0ms)</code></pre><p>On first hit, we serve the request normally but, then on each subsequent requestcache is revalidated and a &quot;304 Not Modified&quot; response is sent to the browser.</p><h2>Options with http_cache_forever</h2><p>By default, HTTP responses are cached only on the user's web browser. To allowproxies to cache the response, we can set public to <code>true</code> to indicate that theycan serve the cached response.</p><h2>Use http_cache_forever with caution</h2><p>By using this method, <code>Cache-Control: max-age=3155760000</code> is set as responseheader and browser/proxy won't revalidate the resource back to the server unlessforce reload is done.</p><p>In case force reload is done, <code>Cache-Control: max-age=0</code> is set as requestheader.</p><p>In this case, browser will receive the changed resource whether ETag is changedor not.</p><p><code>http_cache_forever</code> is literally going to set the headers to cache it for 100years and developers would have to take extra steps to revalidate it. So, thisshould be used with extra care.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Better exception responses in Rails 5 API apps]]></title>
       <author><name>Akshay Mohite</name></author>
      <link href="https://www.bigbinary.com/blog/better-exception-responses-in-rails-5-api-apps"/>
      <updated>2016-03-03T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/better-exception-responses-in-rails-5-api-apps</id>
      <content type="html"><![CDATA[<p>Rails 4.x returns error information in HTML page whenever there is anyexception, in the development environment.</p><p>This is fine for normal HTML requests. But traditionally, Rails always returnedwith HTML response for exceptions for all requests, including JSON on XMLrequests in development.</p><p>We can now generate API only apps in Rails 5. In case of such apps, it's betterto have the error message in the format in which request was made. Having anHTML response for a JSON endpoint like <code>http://localhost:3000/posts.json</code> is notgoing to help in debugging why the exception happened.</p><h2>New config option debug_exception_response_format</h2><p>Rails 5 has introduced<a href="https://github.com/rails/rails/pull/20831">new configuration</a> to respond withproper format for exceptions.</p><pre><code class="language-ruby"># config/environments/development.rbconfig.debug_exception_response_format = :api</code></pre><p>Let's see an example of the response received with this configuration.</p><pre><code class="language-bash">$ curl localhost:3000/posts.json{&quot;status&quot;:404,&quot;error&quot;:&quot;Not Found&quot;,&quot;exception&quot;:&quot;#\u003cActionController::RoutingError: No route matches [GET] \&quot;/posts.json\&quot;\u003e&quot;,&quot;traces&quot;:{&quot;Application Trace&quot;:[...],&quot;Framework Trace&quot;:[...]}}</code></pre><p>The <code>status</code> key will represent HTTP status code and <code>error</code> key will representthe corresponding Rack HTTP status.</p><p><code>exception</code> will print the output of actual exception in <code>inspect</code> format.</p><p><code>traces</code> will contain application and framework traces similar to how they aredisplayed in HTML error page.</p><p>By default, <code>config.debug_exception_response_format</code> is set to <code>:api</code> so as torender responses in the same format as requests.</p><p>If you want the original behavior of rendering HTML pages, you can configurethis option as follows.</p><pre><code class="language-ruby"># config/environments/development.rbconfig.debug_exception_response_format = :default</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Use file_fixture to access test files in Rails 5]]></title>
       <author><name>Ershad Kunnakkadan</name></author>
      <link href="https://www.bigbinary.com/blog/use-file_fixture-to-access-test-files-rails-5"/>
      <updated>2016-03-02T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/use-file_fixture-to-access-test-files-rails-5</id>
      <content type="html"><![CDATA[<p>While writing tests sometimes we need to read files to compare the output. Forexample a test might want to compare the API response with pre determined datastored in a file.</p><p>Here is an example.</p><pre><code class="language-ruby"># In test helperdef file_data(name)  File.read(Rails.root.to_s + &quot;/tests/support/files/#{name}&quot;)end# In testclass PostsControllerTest &lt; ActionDispatch::IntegrationTest  setup do    @post = posts(:one)  end  test &quot;should get index&quot; do    get posts_url, format: :json    assert_equal file_data('posts.json'), response.body  endend</code></pre><h2>File Fixtures in Rails 5</h2><p>In Rails 5, we can now organize such test files as fixtures.</p><p>Newly generated Rails 5 applications, will have directory <code>test/fixtures/files</code>to store such test files.</p><p>These test files can be accessed using <code>file_fixture</code> helper method in tests.</p><pre><code class="language-ruby">require 'test_helper'class PostsControllerTest &lt; ActionDispatch::IntegrationTest  setup do    @post = posts(:one)  end  test &quot;should get index&quot; do    get posts_url, format: :json    assert_equal response.body, file_fixture('posts.json').read  endend</code></pre><p>The <code>file_fixture</code> method returns <code>Pathname</code> object, so it's easy to extractfile specific information.</p><pre><code class="language-ruby">file_fixture('posts.json').readfile_fixture('song.mp3').size</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Migrations are versioned in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/migrations-are-versioned-in-rails-5"/>
      <updated>2016-03-01T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/migrations-are-versioned-in-rails-5</id>
      <content type="html"><![CDATA[<p>We will see how migrations in Rails 5 differ by looking at different cases.</p><h2>Case I</h2><p>In Rails 4.x command</p><pre><code class="language-ruby">rails g model User name:string</code></pre><p>will generate migration as shown below.</p><pre><code class="language-ruby">class CreateUsers &lt; ActiveRecord::Migration  def change    create_table :users do |t|      t.string :name      t.timestamps null: false    end  endend</code></pre><p>In Rails 5 the same command will generate following migration.</p><pre><code class="language-ruby">class CreateUsers &lt; ActiveRecord::Migration[5.0]  def change    create_table :users do |t|      t.string :name      t.timestamps    end  endend</code></pre><p>Let's see the generated schema after running migration generated in Rails 5.</p><pre><code class="language-sql">sqlite&gt; .schema usersCREATE TABLE &quot;users&quot; (&quot;id&quot; INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, &quot;name&quot; varchar, &quot;created_at&quot; datetime NOT NULL, &quot;updated_at&quot; datetime NOT NULL);sqlite&gt;</code></pre><p>Rails 5 added the <code>NOT NULL</code> constraints on the timestamps columns even thoughnot null constraint was not specified in the migration.</p><h2>Case II</h2><p>Let's look at another example.</p><p>In Rails 4.x command</p><pre><code class="language-ruby">rails g model Task user:references</code></pre><p>would generate following migration.</p><pre><code class="language-ruby">class CreateTasks &lt; ActiveRecord::Migration  def change    create_table :tasks do |t|      t.references :user, index: true, foreign_key: true      t.timestamps null: false    end  endend</code></pre><p>In Rails 5.0, same command will generate following migration.</p><pre><code class="language-ruby">class CreateTasks &lt; ActiveRecord::Migration[5.0]  def change    create_table :tasks do |t|      t.references :user, foreign_key: true      t.timestamps    end  endend</code></pre><p>There is no mention of <code>index: true</code> in the above migration. Let's see thegenerated schema after running Rails 5 migration.</p><pre><code class="language-sql">sqlite&gt; .schema tasksCREATE TABLE &quot;tasks&quot; (&quot;id&quot; INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, &quot;user_id&quot; integer, &quot;created_at&quot; datetime NOT NULL, &quot;updated_at&quot; datetime NOT NULL);CREATE INDEX &quot;index_tasks_on_user_id&quot; ON &quot;tasks&quot; (&quot;user_id&quot;);</code></pre><p>As you can see, an index on <code>user_id</code> column is added even though it's notpresent in the migration.</p><h2>Migration API has changed in Rails 5</h2><p>Rails 5 has changed migration API because of which even though <code>null: false</code>options is not passed to timestamps when migrations are run then <code>not null</code> is<a href="https://github.com/rails/rails/commit/a939506f297b667291480f26fa32a373a18ae06a">automatically added</a>for timestamps.</p><p>Similarly, we want indexes for referenced columns in almost all cases. So Rails5 does not need references to have <code>index: true</code>. When migrations are run thenindex is <a href="https://github.com/rails/rails/pull/23179">automatically created</a>.</p><p>Now let's assume that an app was created in Rails 4.x. It has a bunch ofmigrations. Later the app was upgraded to Rails 5. Now when older migrations arerun then those migrations will behave differently and will create a differentschema file. This is a problem.</p><p>Solution is versioned migrations.</p><h3>Versioned migrations in Rails 5</h3><p>Let's look at the migration generated in Rails 5 closely.</p><pre><code class="language-ruby">class CreateTasks &lt; ActiveRecord::Migration[5.0]  def change    create_table :tasks do |t|      t.references :user, index: true, foreign_key: true      t.timestamps null: false    end  endend</code></pre><p>In this case <code>CreateUsers</code> class is now inheriting from<code>ActiveRecord::Migration[5.0]</code> instead of <code>ActiveRecord::Migration</code>.</p><p>Here [5.0] is Rails version that generated this migration.</p><h2>Solving the issue with older migrations</h2><p>Whenever Rails 5 runs migrations, it checks the class of the current migrationfile being run. If it's 5.0, it uses the new migration API which has changeslike automatically adding <code>null: false</code> to timestamps.</p><p>But whenever the class of migration file is other than<code>ActiveRecord::Migration[5.0]</code>, Rails will use a compatibility layer ofmigrations API. Currently this<a href="https://github.com/rails/rails/blob/434c8dc96759d4eca36ca05865b6321c54a2a90b/activerecord/lib/active_record/migration/compatibility.rb#L6-L93">compatibility layer</a>is present for Rails 4.2. What it means is that all migration generated prior tousage of Rails 5 will be treated as if they were generate in Rails 4.2.</p><p>You will also see a<a href="https://github.com/rails/rails/blob/434c8dc96759d4eca36ca05865b6321c54a2a90b/activerecord/lib/active_record/migration/compatibility.rb#L105-L112">deprecation warning</a>asking user to add the version of the migration to the class name for oldermigrations.</p><p>So if you are migrating a Rails 4.2 app, all of your migrations will have class<code>ActiveRecord::Migration</code>. If you run those migrations in Rails 5, you will seea warning asking to add version name to the class name so that class name lookslike <code>ActiveRecord::Migration[4.2]</code>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 improves redirect_to :back method]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-improves-redirect_to_back-with-redirect-back"/>
      <updated>2016-02-29T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-improves-redirect_to_back-with-redirect-back</id>
      <content type="html"><![CDATA[<p>In Rails 4.x, for going back to previous page we use <code>redirect_to :back</code>.</p><p>However sometimes we get <code>ActionController::RedirectBackError</code> exception when<code>HTTP_REFERER</code> is not present.</p><pre><code class="language-ruby">class PostsController &lt; ApplicationController  def publish    post = Post.find params[:id]    post.publish!    redirect_to :back  endend</code></pre><p>This works well when <code>HTTP_REFERER</code> is present and it redirects to previouspage.</p><p>Issue comes up when <code>HTTP_REFERER</code> is not present and which in turn throwsexception.</p><p>To avoid this exception we can use <code>rescue</code> and redirect to root url.</p><pre><code class="language-ruby">class PostsController &lt; ApplicationController  rescue_from ActionController::RedirectBackError, with: :redirect_to_default  def publish    post = Post.find params[:id]    post.publish!    redirect_to :back  end  private  def redirect_to_default    redirect_to root_path  endend</code></pre><h2>Improvement in Rails 5</h2><p>In Rails 5, <code>redirect_to :back</code> has been deprecated and instead<a href="https://github.com/rails/rails/pull/22506">a new method has been added</a> called<code>redirect_back</code>.</p><p>To deal with the situation when <code>HTTP_REFERER</code> is not present, it takes requiredoption <code>fallback_location</code>.</p><pre><code class="language-ruby">class PostsController &lt; ApplicationController  def publish    post = Post.find params[:id]    post.publish!    redirect_back(fallback_location: root_path)  endend</code></pre><p>This redirects to <code>HTTP_REFERER</code> when it is present and when <code>HTTP_REFERER</code> isnot present then redirects to whatever is passed as <code>fallback_location</code>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 allows configuring queue name for mailers]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-configuring-queue-name-for-mailers"/>
      <updated>2016-02-26T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-configuring-queue-name-for-mailers</id>
      <content type="html"><![CDATA[<p>In Rails 4.2, Active Job was integrated with Action Mailer to send emailsasynchronously.</p><p>Rails provides <code>deliver_later</code> method to enqueue mailer jobs.</p><pre><code class="language-ruby">class UserMailer &lt; ApplicationMailer  def send_notification(user)    @user = user    mail(to: user.email)  endend&gt; UserMailer.send_notification(user).deliver_later=&gt; &lt;ActionMailer::DeliveryJob:0x007ff602dd3128 @arguments=[&quot;UserMailer&quot;, &quot;send_notification&quot;, &quot;deliver_now&quot;, &lt;User id: 1, name: &quot;John&quot;, email: &quot;john@bigbinary.com&quot;&gt;], @job_id=&quot;d0171da0-86d3-49f4-ba03-37b37d4e8e2b&quot;, @queue_name=&quot;mailers&quot;, @priority=nil&gt;</code></pre><p>Note that the task of delivering email was put in queue called <code>mailers</code>.</p><p>In Rails 4.x, all background jobs are given queue named &quot;default&quot; except formailers. All outgoing mails are given the queue named &quot;mailers&quot; and we do nothave the option of changing this queue name from &quot;mailers&quot; to anything else.</p><p>Since Rails 4.x comes with minimum of two queues it makes difficult to usequeuing services like <a href="https://github.com/chanks/que">que</a> which relies onapplications having only one queue.</p><h2>Customizing queue name in Rails 5</h2><p>In Rails 5, we can now<a href="https://github.com/rails/rails/pull/18587">change queue name</a> for mailer jobsusing following configuration.</p><pre><code class="language-ruby">config.action_mailer.deliver_later_queue_name = 'default'class UserMailer &lt; ApplicationMailer  def send_notification(user)    @user = user    mail(to: user.email)  endend2.2.2 :003 &gt; user = User.last=&gt; &lt;User id: 6, name: &quot;John&quot;, email: &quot;john@bigbinary.com&quot;&gt;2.2.2 :004 &gt; UserMailer.send_notification(user).deliver_later=&gt; &lt;ActionMailer::DeliveryJob:0x007fea2182b2d0 @arguments=[&quot;UserMailer&quot;, &quot;send_notification&quot;, &quot;deliver_now&quot;, &lt;User id: 1, name: &quot;John&quot;, email: &quot;john@bigbinary.com&quot;&gt;], @job_id=&quot;316b00b2-64c8-4a2d-8153-4ce7abafb28d&quot;, @queue_name=&quot;default&quot;, @priority=nil&gt;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 handles DateTime with better precision]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-handles-datetime-with-better-precision"/>
      <updated>2016-02-23T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-handles-datetime-with-better-precision</id>
      <content type="html"><![CDATA[<p>MySQL 5.6.4 and up<a href="https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html">has added fractional seconds support</a>for TIME, DATETIME, and TIMESTAMP values, with up to microseconds (6 digits)precision.</p><h2>Adding precision to migration</h2><p>To add precision on <code>datetime</code> column we need to add <code>limit</code> option to it. Bydefault it is set to 0.</p><pre><code class="language-ruby">def change  add_column :users, :last_seen_at, :datetime, limit: 6end</code></pre><p>This adds precision(6) to <code>last_seen_at</code> column in <code>users</code> table.</p><h2>Rails 4.x behavior</h2><p>Let's look at the some of the examples with different precision values.</p><p>The task here is to set <code>end_of_day</code> value to <code>updated_at</code> column.</p><h3>With precision set to 6</h3><pre><code class="language-ruby">user = User.firstuser.updated_at=&gt; Mon, 18 Jan 2016 10:13:10 UTC +00:00user.updated_at = user.updated_at.end_of_day=&gt; Mon, 18 Jan 2016 23:59:59 UTC +00:00user.save'UPDATE `users` SET `updated_at` = '2016-01-18 23:59:59.999999' WHERE `users`.`id` = 1'user.updated_at=&gt; Mon, 18 Jan 2016 23:59:59 UTC +00:00user.reloaduser.updated_at=&gt; Mon, 18 Jan 2016 23:59:59 UTC +00:00</code></pre><p>Everything looks good here.</p><p>But let's look at what happens when precision is set to 0.</p><h3>With precision set to 0</h3><pre><code class="language-ruby">user = User.firstuser.updated_at=&gt; Mon, 18 Jan 2016 10:13:10 UTC +00:00user.updated_at = user.updated_at.end_of_day=&gt; Mon, 18 Jan 2016 23:59:59 UTC +00:00user.save'UPDATE `users` SET `updated_at` = '2016-01-18 23:59:59.999999' WHERE `users`.`id` = 1'user.updated_at=&gt; Mon, 18 Jan 2016 23:59:59 UTC +00:00</code></pre><p>So far everything looks good here too. Now let's see what happens when we reloadthis object.</p><pre><code class="language-ruby">user.reloaduser.updated_at=&gt; Tue, 19 Jan 2016 00:00:00 UTC +00:00</code></pre><p>As we can clearly see after the reload <code>updated_at</code> value has been rounded offfrom <code>2016-01-18 23:59:59.999999</code> to <code>2016-01-19 00:00:00</code>. It might seem like asmall issue but notice that date has changed from <code>01/18</code> to <code>01/19</code> because ofthis rounding.</p><h2>Improvement in Rails 5</h2><p>Rails team fixed this issue by removing fractional part if mysql adapter doesnot support precision.</p><p>Here are the two relevant commits to this change.</p><ul><li><p><a href="https://github.com/rails/rails/commit/e975d7cd1a6cb177f914024ffec8dd9a6cdc4ba1">Commit for support of precision with mysql</a></p></li><li><p><a href="https://github.com/rails/rails/commit/f1a0fa9e">Commit for checking precision on columns</a></p></li></ul><h3>With precision set to 0</h3><pre><code class="language-ruby">user.updated_at=&gt; Tue, 19 Jan 2016 00:00:00 UTC +00:00user.updated_at = user.updated_at.tomorrow.beginning_of_day - 1=&gt; Tue, 19 Jan 2016 23:59:59 UTC +00:00user.save'UPDATE `users` SET `updated_at` = '2016-01-19 23:59:59' WHERE `users`.`id` = 1'user.reloaduser.updated_at=&gt; Tue, 19 Jan 2016 23:59:59 UTC +00:00</code></pre><p>If precision is not set then fractional part gets stripped and date is notchanged.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Active Support Improvements in Rails 5]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/active-support-improvements-in-Rails-5"/>
      <updated>2016-02-17T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/active-support-improvements-in-Rails-5</id>
      <content type="html"><![CDATA[<p>Rails 5 has added some nice enhancements to Active Support. This blog will goover some of those changes.</p><h2>Improvements in Date, Time and Datetime</h2><h3>prev_day and next_day</h3><p>As the name of the methods suggests, <code>next_day</code><a href="https://github.com/rails/rails/pull/18335">returns next calendar date</a>.</p><p>Similarly, <code>prev_day</code> returns previous calendar date.</p><pre><code class="language-ruby">Time.current=&gt; Fri, 12 Feb 2016 08:53:31 UTC +00:00Time.current.next_day=&gt; Sat, 13 Feb 2016 08:53:31 UTC +00:00Time.current.prev_day=&gt; Thu, 11 Feb 2016 08:53:31 UTC +00:00</code></pre><h3>Support for same_time option to next_week and prev_week</h3><p>In Rails 4.x <code>next_week</code> returns beginning of next week and <code>prev_week</code> returnsbeginning of previous week.</p><p>In Rails 4.x these two methods also accept week day as a parameter.</p><pre><code class="language-ruby">Time.current=&gt; Fri, 12 Feb 2016 08:53:31 UTC +00:00Time.current.next_week=&gt; Mon, 15 Feb 2016 00:00:00 UTC +00:00Time.current.next_week(:tuesday)=&gt; Tue, 16 Feb 2016 00:00:00 UTC +00:00Time.current.prev_week(:tuesday)=&gt; Tue, 02 Feb 2016 00:00:00 UTC +00:00</code></pre><p>By using week day as parameter we can get the date one week from now but thereturned date is still the beginning of that date. How do we get one week fromthe current time.</p><p>Rails 5 add an additional option <code>same_time: true</code> to solve this problem.</p><p>Using this option, we can now get next week date from the current time.</p><pre><code class="language-ruby">Time.current=&gt; Fri, 12 Feb 2016 09:15:10 UTC +00:00Time.current.next_week=&gt; Mon, 15 Feb 2016 00:00:00 UTC +00:00Time.current.next_week(same_time: true)=&gt; Mon, 15 Feb 2016 09:15:20 UTC +00:00Time.current.prev_week=&gt; Mon, 01 Feb 2016 00:00:00 UTC +00:00Time.current.prev_week(same_time: true)=&gt; Mon, 01 Feb 2016 09:16:50 UTC +00:00</code></pre><h3>on_weekend?</h3><p>This method returns <code>true</code> if the receiving date/time is a Saturday or Sunday.</p><pre><code class="language-ruby">Time.current=&gt; Fri, 12 Feb 2016 09:47:40 UTC +00:00Time.current.on_weekend?=&gt; falseTime.current.tomorrow=&gt; Sat, 13 Feb 2016 09:48:47 UTC +00:00Time.current.tomorrow.on_weekend?=&gt; true</code></pre><h3>on_weekday?</h3><p>This method returns <code>true</code> if the receiving date/time is not a Saturday orSunday.</p><pre><code class="language-ruby">Time.current=&gt; Fri, 12 Feb 2016 09:47:40 UTC +00:00Time.current.on_weekday?=&gt; trueTime.current.tomorrow=&gt; Sat, 13 Feb 2016 09:48:47 UTC +00:00Time.current.tomorrow.on_weekday?=&gt; false</code></pre><h3>next_weekday and prev_weekday</h3><p><code>next_weekday</code> returns next day that is not a weekend.</p><p>Similarly, <code>prev_weekday</code> returns last day that is not a weekend.</p><pre><code class="language-ruby">Time.current=&gt; Fri, 12 Feb 2016 09:47:40 UTC +00:00Time.current.next_weekday=&gt; Mon, 15 Feb 2016 09:55:14 UTC +00:00Time.current.prev_weekday=&gt; Thu, 11 Feb 2016 09:55:33 UTC +00:00</code></pre><h3>Time.days_in_year</h3><pre><code class="language-ruby"># Gives number of days in current year, if year is not passed.Time.days_in_year=&gt; 366# Gives number of days in specified year, if year is passed.Time.days_in_year(2015)=&gt; 365</code></pre><h2>Improvements in Enumerable</h2><h3>pluck</h3><p><code>pluck</code> method is now <a href="https://github.com/rails/rails/pull/20350">added to</a>Enumerable objects.</p><pre><code class="language-ruby">users = [{id: 1, name: 'Max'}, {id: 2, name: 'Mark'}, {id: 3, name: 'George'}]users.pluck(:name)=&gt; [&quot;Max&quot;, &quot;Mark&quot;, &quot;George&quot;]# Takes multiple arguments as wellusers.pluck(:id, :name)=&gt; [[1, &quot;Max&quot;], [2, &quot;Mark&quot;], [3, &quot;George&quot;]]</code></pre><p>one great improvement in <code>ActiveRecord</code> due to this method addition is that whenrelation is already loaded then instead of firing query with pluck, it usesEnumerable#pluck to get data.</p><pre><code class="language-ruby"># In Rails 4.xusers = User.allSELECT `users`.* FROM `users`users.pluck(:id, :name)SELECT &quot;users&quot;.&quot;id&quot;, &quot;users&quot;.&quot;name&quot; FROM &quot;users&quot;=&gt; [[2, &quot;Max&quot;], [3, &quot;Mark&quot;], [4, &quot;George&quot;]]# In Rails 5users = User.allSELECT &quot;users&quot;.* FROM &quot;users&quot;# does not fire any queryusers.pluck(:id, :name)=&gt; [[1, &quot;Max&quot;], [2, &quot;Mark&quot;], [3, &quot;George&quot;]]</code></pre><h3>without</h3><p><a href="https://github.com/rails/rails/pull/19157">This method</a> returns a copy ofenumerable without the elements passed to the method.</p><pre><code class="language-ruby">vehicles = ['Car', 'Bike', 'Truck', 'Bus']vehicles.without(&quot;Car&quot;, &quot;Bike&quot;)=&gt; [&quot;Truck&quot;, &quot;Bus&quot;]vehicles = {car: 'Hyundai', bike: 'Honda', bus: 'Mercedes', truck: 'Tata'}vehicles.without(:bike, :bus)=&gt; {:car=&gt;&quot;Hyundai&quot;, :truck=&gt;&quot;Tata&quot;}</code></pre><h3>Array#second_to_last and Array#third_to_last</h3><pre><code class="language-ruby">['a', 'b', 'c', 'd', 'e'].second_to_last=&gt; &quot;d&quot;['a', 'b', 'c', 'd', 'e'].third_to_last=&gt; &quot;c&quot;</code></pre><p>PR for these methods can be found<a href="https://github.com/rails/rails/pull/23583">here</a>.</p><h3>Integer#positive? and Integer#negative?</h3><p><code>positive?</code> returns true if integer is positive.</p><p><code>negative?</code> returns true if integer is negative.</p><pre><code class="language-ruby">4.positive?=&gt; true4.negative?=&gt; false-4.0.positive?=&gt; false-4.0.negative?=&gt; true</code></pre><p>Commit for these methods can be found<a href="https://github.com/rails/rails/commit/e54277a4">here</a>.</p><p>These changes have now been<a href="https://github.com/ruby/ruby/blob/a837be87fdf580ac4fd58c4cb2f1ee16bab11b99/NEWS#L127">added to Ruby 2.3</a>also.</p><h3>Array#inquiry</h3><p>Rails team has<a href="https://github.com/georgeclaghorn/rails/commit/c64b99ecc98341d504aced72448bee758f3cfdaf">added</a><code>ArrayInquirer</code> to <code>ActiveSupport</code> which gives a friendlier way to check itscontents.</p><p><code>Array#inquiry</code> is a shortcut for wrapping the receiving array in an<code>ArrayInquirer</code></p><pre><code class="language-ruby">users = [:mark, :max, :david]array_inquirer1 = ActiveSupport::ArrayInquirer.new(users)# creates ArrayInquirer object which is same as array_inquirer1 abovearray_inquirer2 = users.inquiryarray_inquirer2.class=&gt; ActiveSupport::ArrayInquirer# provides methods like:array_inquirer2.mark?=&gt; truearray_inquirer2.john?=&gt; falsearray_inquirer2.any?(:john, :mark)=&gt; truearray_inquirer2.any?(:mark, :david)=&gt; truearray_inquirer2.any?(:john, :louis)=&gt; false</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 improves route search with advanced options]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-options-for-rake-routes"/>
      <updated>2016-02-16T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-options-for-rake-routes</id>
      <content type="html"><![CDATA[<p><code>rails routes</code> shows all the routes in the application.</p><pre><code class="language-bash">$ rake routesPrefix       Verb   URI Pattern                   Controller#Actionwishlist_user GET    /users/:id/wishlist(.:format) users#wishlist        users GET    /users(.:format)              users#index              POST   /users(.:format)              users#create     new_user GET    /users/new(.:format)          users#new    edit_user GET    /users/:id/edit(.:format)     users#edit         user GET    /users/:id(.:format)          users#show              PATCH  /users/:id(.:format)          users#update              PUT    /users/:id(.:format)          users#update              DELETE /users/:id(.:format)          users#destroy     products GET    /products(.:format)           products#index              POST   /products(.:format)           products#createand so on ......</code></pre><p>This list can be lengthy and it could be difficult to locate exactly what useris looking for.</p><h2>Ways to search specific routes prior to Rails 5</h2><p>To see only specific routes we can use commands like <code>grep</code>.</p><pre><code class="language-bash">$ rake routes | grep productsPrefix       Verb   URI Pattern                   Controller#Actionproducts      GET    /products(.:format)           products#index              POST   /products(.:format)           products#create</code></pre><h2>Options with Rails 5</h2><p>Rails 5 <a href="https://github.com/rails/rails/pull/23225">has added</a> options in<code>rails routes</code> to perform pattern matching on routes.</p><h4>Controller specific search</h4><p>Use option <code>-c</code> to search for routes related to controller. Also remember thatRails does case insensitive search. So <code>rails routes -c users</code> is same as<code>rails routes -c Users</code>.</p><pre><code class="language-bash"># Search for Controller name$ rails routes -c users       Prefix Verb   URI Pattern                   Controller#Actionwishlist_user GET    /users/:id/wishlist(.:format) users#wishlist        users GET    /users(.:format)              users#index              POST   /users(.:format)              users#create# Search for namespaced Controller name.$ rails routes -c admin/users         Prefix Verb   URI Pattern                     Controller#Action    admin_users GET    /admin/users(.:format)          admin/users#index                POST   /admin/users(.:format)          admin/users#create# Search for namespaced Controller name.$ rails routes -c Admin::UsersController         Prefix Verb   URI Pattern                     Controller#Action    admin_users GET    /admin/users(.:format)          admin/users#index                POST   /admin/users(.:format)          admin/users#create</code></pre><h4>Pattern specific search</h4><p>Use <code>-g</code> option to do<a href="https://github.com/rails/rails/pull/23611">general purpose</a> pattern matching.This results in any routes that partially matches Prefix, Controller#Action orthe URI pattern.</p><pre><code class="language-bash"># Search with pattern$ rails routes -g wishlist       Prefix Verb URI Pattern                   Controller#Actionwishlist_user GET  /users/:id/wishlist(.:format) users#wishlist# Search with HTTP Verb$ rails routes -g POST    Prefix Verb URI Pattern            Controller#Action           POST /users(.:format)       users#create           POST /admin/users(.:format) admin/users#create           POST /products(.:format)    products#create# Search with URI pattern$ rails routes -g admin       Prefix Verb   URI Pattern                     Controller#Action  admin_users GET    /admin/users(.:format)          admin/users#index              POST   /admin/users(.:format)          admin/users#create</code></pre><p>Note that using CONTROLLER=some_controller has now been deprecated. This had thesame effect as searching for a controller specific route.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 makes belongs_to association required by default]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-makes-belong-to-association-required-by-default"/>
      <updated>2016-02-15T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-makes-belong-to-association-required-by-default</id>
      <content type="html"><![CDATA[<p>In Rails 5, whenever we define a <code>belongs_to</code> association, it is required tohave the associated record present by default after<a href="https://github.com/rails/rails/pull/18937">this</a> change.</p><p>It triggers validation error if associated record is not present.</p><pre><code class="language-ruby">class User &lt; ApplicationRecordendclass Post &lt; ApplicationRecord  belongs_to :userendpost = Post.create(title: 'Hi')=&gt; &lt;Post id: nil, title: &quot;Hi&quot;, user_id: nil, created_at: nil, updated_at: nil&gt;post.errors.full_messages.to_sentence=&gt; &quot;User must exist&quot;</code></pre><p>As we can see, we can't create any <code>post</code> record without having an associated<code>user</code> record.</p><h2>How to achieve this behavior before Rails 5</h2><p>In Rails 4.x world To add validation on <code>belongs_to</code> association, we need to addoption <code>required: true</code> .</p><pre><code class="language-ruby">class User &lt; ApplicationRecordendclass Post &lt; ApplicationRecord  belongs_to :user, required: trueendpost = Post.create(title: 'Hi')=&gt; &lt;Post id: nil, title: &quot;Hi&quot;, user_id: nil, created_at: nil, updated_at: nil&gt;post.errors.full_messages.to_sentence=&gt; &quot;User must exist&quot;</code></pre><p>By default, <code>required</code> option is set to <code>false</code>.</p><h2>Opting out of this default behavior in Rails 5</h2><p>We can pass <code>optional: true</code> to the <code>belongs_to</code> association which would removethis validation check.</p><pre><code class="language-ruby">class Post &lt; ApplicationRecord  belongs_to :user, optional: trueendpost = Post.create(title: 'Hi')=&gt; &lt;Post id: 2, title: &quot;Hi&quot;, user_id: nil&gt;</code></pre><p>But, what if we do not need this behavior anywhere in our entire application andnot just a single model?</p><h2>Opting out of this default behavior for the entire application</h2><p>New Rails 5 application comes with an initializer named<code>new_framework_defaults.rb</code>.</p><p>When upgrading from older version of Rails to Rails 5, we can add thisinitializer by running <code>bin/rails app:update</code> task.</p><p>This initializer has config named<code>Rails.application.config.active_record.belongs_to_required_by_default = true</code></p><p>For new Rails 5 application the value is set to <code>true</code> but for old applications,this is set to <code>false</code> by default.</p><p>We can turn off this behavior by keeping the value to <code>false</code>.</p><pre><code class="language-ruby">Rails.application.config.active_record.belongs_to_required_by_default = falseclass Post &lt; ApplicationRecord  belongs_to :userendpost = Post.create(title: 'Hi')=&gt; &lt;Post id: 3, title: &quot;Hi&quot;, user_id: nil, created_at: &quot;2016-02-11 12:36:05&quot;, updated_at: &quot;2016-02-11 12:36:05&quot;&gt;</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 doesn't halt callback chain if false is returned]]></title>
       <author><name>Abhishek Jain</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-does-not-halt-callback-chain-when-false-is-returned"/>
      <updated>2016-02-13T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-does-not-halt-callback-chain-when-false-is-returned</id>
      <content type="html"><![CDATA[<p>Before Rails 5, returning <code>false</code> from any <code>before_</code> callback in <code>ActiveModel</code>or <code>ActiveModel::Validations</code>, <code>ActiveRecord</code> and <code>ActiveSupport</code> resulted inhalting of callback chain.</p><pre><code class="language-ruby">class Order &lt; ActiveRecord::Base  before_save :set_eligibility_for_rebate  before_save :ensure_credit_card_is_on_file  def set_eligibility_for_rebate    self.eligibility_for_rebate ||= false  end  def ensure_credit_card_is_on_file    puts &quot;check if credit card is on file&quot;  endendOrder.create!=&gt; ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved</code></pre><p>In this case the code is attempting to set the value of <code>eligibility_for_rebate</code>to false. However the side effect of the way Rails callbacks work is that thecallback chain will be halted simply because one of the callbacks returned<code>false</code>.</p><p>Right now, to fix this we need to return <code>true</code> from <code>before_</code> callbacks, sothat callbacks are not halted.</p><h2>Improvements in Rails 5</h2><p>Rails 5 fixed this issue <a href="https://github.com/rails/rails/pull/17227">by adding</a><code>throw(:abort)</code> to explicitly halt callbacks.</p><p>Now, if any <code>before_</code> callback returns <code>false</code> then callback chain is nothalted.</p><pre><code class="language-ruby">class Order &lt; ActiveRecord::Base  before_save :set_eligibility_for_rebate  before_save :ensure_credit_card_is_on_file  def set_eligibility_for_rebate    self.eligibility_for_rebate ||= false  end  def ensure_credit_card_is_on_file    puts &quot;check if credit card is on file&quot;  endendOrder.create!=&gt; check if credit card is on file=&gt; &lt;Order id: 4, eligibility_for_rebate: false&gt;</code></pre><p>To explicitly halt the callback chain, we need to use <code>throw(:abort)</code>.</p><pre><code class="language-ruby">class Order &lt; ActiveRecord::Base  before_save :set_eligibility_for_rebate  before_save :ensure_credit_card_is_on_file  def set_eligibility_for_rebate    self.eligibility_for_rebate ||= false    throw(:abort)  end  def ensure_credit_card_is_on_file    puts &quot;check if credit card is on file&quot;  endendOrder.create!=&gt; ActiveRecord::RecordNotSaved: Failed to save the record</code></pre><h2>Opting out of this behavior</h2><p>The new Rails 5 application comes up with initializer named<code>callback_terminator.rb</code>.</p><p><code>ActiveSupport.halt_callback_chains_on_return_false = false</code></p><p>By default the value is to set to <code>false</code>.</p><p>We can turn off this default behavior by changing this configuration to <code>true</code>.However then Rails shows deprecation warning when <code>false</code> is returned fromcallback.</p><pre><code class="language-ruby">ActiveSupport.halt_callback_chains_on_return_false = trueclass Order &lt; ApplicationRecord  before_save :set_eligibility_for_rebate  before_save :ensure_credit_card_is_on_file  def set_eligibility_for_rebate    self.eligibility_for_rebate ||= false  end  def ensure_credit_card_is_on_file    puts &quot;check if credit card is on file&quot;  endend=&gt; DEPRECATION WARNING: Returning `false` in Active Record and Active Model callbacks will not implicitly halt a callback chain in the next release of Rails. To explicitly halt the callback chain, please use `throw :abort` instead.ActiveRecord::RecordNotSaved: Failed to save the record</code></pre><h2>How older applications will work with this change?</h2><p>The initializer configuration will be present only in newly generated Rails 5apps.</p><p>If you are upgrading from an older version of Rails, you can add thisinitializer yourself to enable this change for entire application.</p><p>This is a welcome change in Rails 5 which will help prevent accidental haltingof the callbacks.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Caching result sets and collection in Rails 5]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/activerecord-relation-cache-key"/>
      <updated>2016-02-02T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/activerecord-relation-cache-key</id>
      <content type="html"><![CDATA[<p>Often while developing a Rails application you may look to have one of these<a href="http://guides.rubyonrails.org/caching_with_rails.html">caching techniques</a> toboost the performance. Along with these, Rails 5 now provides a way of caching acollection of records, thanks to the introduction of the following method:</p><pre><code class="language-plaintext">ActiveRecord::Relation#cache_key</code></pre><h3>What is collection caching?</h3><p>Consider the following example where we are fetching a collection of all usersbelonging to city of Miami.</p><pre><code class="language-ruby">@users = User.where(city: 'miami')</code></pre><p>Here <code>@users</code> is a collection of records and is an object of class<code>ActiveRecord::Relation</code>.</p><p>Whether the result of the above query would be same depends on followingconditions.</p><ul><li>The query statement doesn't change. If we change city name from &quot;Miami&quot; to&quot;Boston&quot; then result might change.</li><li>No record is deleted. The count of records in the collection should be same.</li><li>No record is added. The count of records in the collection should be same.</li></ul><p>Rails community<a href="https://github.com/rails/rails/pull/20884">implemented caching for a collection of records</a>. Method <code>cache_key</code> was added to <code>ActiveRecord::Relation</code> which takes intoaccount many factors including query statement, updated_at column value and thecount of the records in collection.</p><h3>Understanding ActiveRecord::Relation#cache_key</h3><p>We have object <code>@users</code> of class <code>ActiveRecord::Relation</code>. Now let's execute<code>cache_key</code> method on it.</p><pre><code class="language-ruby"> @users.cache_key =&gt; &quot;users/query-67ed32b36805c4b1ec1948b4eef8d58f-3-20160116111659084027&quot;</code></pre><p>Let's try to understand each piece of the output.</p><p><strong><code>users</code></strong> represents what kind of records we are holding. In this example wehave collection of records of class <code>User</code>. Hence <code>users</code> is to illustrate thatwe are holding <code>users</code> records.</p><p><strong><code>query-</code></strong> is hardcoded value and it will be same in all cases.</p><p><strong><code>67ed32b36805c4b1ec1948b4eef8d58f</code></strong> is a digest of the query statement thatwill be executed. In our example it is<code>MD5( &quot;SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;city&quot; = 'Miami'&quot;)</code></p><p><strong><code>3</code></strong> is the size of collection.</p><p><strong><code>20160116111659084027</code></strong> is timestamp of the most recently updated record inthe collection. By default, the timestamp column considered is <code>updated_at</code> andhence the value will be the most recent <code>updated_at</code> value in the collection.</p><h2>Using ActiveRecord::Relation#cache_key</h2><p>Let's see how to use <code>cache_key</code> to actually cache data.</p><p>In our Rails application, if we want to cache records of users belonging to&quot;Miami&quot; then we can take following approach.</p><pre><code class="language-ruby"># app/controllers/users_controller.rbclass UsersController &lt; ApplicationController  def index    @users = User.where(city: 'Miami')  endend# users/index.html.erb&lt;% cache(@users) do %&gt;  &lt;% @users.each do |user| %&gt;    &lt;p&gt; &lt;%= user.city %&gt; &lt;/p&gt;  &lt;% end %&gt;&lt;% end %&gt;# 1st HitProcessing by UsersController#index as HTML  Rendering users/index.html.erb within layouts/application   (0.2ms)  SELECT COUNT(*) AS &quot;size&quot;, MAX(&quot;users&quot;.&quot;updated_at&quot;) AS timestamp FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;city&quot; = ?  [[&quot;city&quot;, &quot;Miami&quot;]]Read fragment views/users/query-37a3d8c65b3f0f9ece7f66edcdcb10ab-4-20160704131424063322/30033e62b28c83f26351dc4ccd6c8451 (0.0ms)  User Load (0.1ms)  SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;city&quot; = ?  [[&quot;city&quot;, &quot;Miami&quot;]]Write fragment views/users/query-37a3d8c65b3f0f9ece7f66edcdcb10ab-4-20160704131424063322/30033e62b28c83f26351dc4ccd6c8451 (0.0ms)Rendered users/index.html.erb within layouts/application (3.7ms)# 2nd HitProcessing by UsersController#index as HTML  Rendering users/index.html.erb within layouts/application   (0.2ms)  SELECT COUNT(*) AS &quot;size&quot;, MAX(&quot;users&quot;.&quot;updated_at&quot;) AS timestamp FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;city&quot; = ?  [[&quot;city&quot;, &quot;Miami&quot;]]Read fragment views/users/query-37a3d8c65b3f0f9ece7f66edcdcb10ab-4-20160704131424063322/30033e62b28c83f26351dc4ccd6c8451 (0.0ms)  Rendered users/index.html.erb within layouts/application (3.0ms)</code></pre><p>From above, we can see that for the first hit, a <code>count</code> query is fired to getthe latest <code>updated_at</code> and <code>size</code> from the users collection.</p><p>Rails will write a new cache entry with a <code>cache_key</code> generated from above<code>count</code> query.</p><p>Now on second hit, it again fires <code>count</code> query and checks if cache_key for thisquery exists or not.</p><p>If cache_key is found, it loads data without firing <code>SQL query</code>.</p><h5>What if your table doesn't have updated_at column?</h5><p>Previously we mentioned that <code>cache_key</code> method uses <code>updated_at</code> column.<code>cache_key</code> also provides an option of passing custom column as a parameter andthen the highest value of that column among the records in the collection willbe considered.</p><p>For example if your business logic considers a column named <code>last_bought_at</code> in<code>products</code> table as a factor to decide caching, then you can use the followingcode.</p><pre><code class="language-ruby"> products = Product.where(category: 'cars') products.cache_key(:last_bought_at) =&gt; &quot;products/query-211ae6b96ec456b8d7a24ad5fa2f8ad4-4-20160118080134697603&quot;</code></pre><h3>Edge cases to watch out for</h3><p>Before you start using <code>cache_key</code> there are some edge cases to watch out for.</p><p>Consider you have an application where there are 5 entries in <code>users</code> table with<code>city</code> Miami.</p><p><em><strong>Using limit puts incorrect size in cache key if collection is not loaded.</strong></em></p><p>If you want to fetch three users belonging to city &quot;Miami&quot; then you wouldexecute following query.</p><pre><code class="language-ruby"> users = User.where(city: 'Miami').limit(3) users.cache_key =&gt; &quot;users/query-67ed32b36805c4b1ec1948b4eef8d58f-3-20160116144936949365&quot;</code></pre><p>Here users contains only three records and hence the <code>cache_key</code> has 3 for sizeof collection.</p><p>Now let's try to execute same query without fetching the records first.</p><pre><code class="language-ruby"> User.where(name: 'Sam').limit(3).cache_key =&gt; &quot;users/query-8dc512b1408302d7a51cf1177e478463-5-20160116144936949365&quot;</code></pre><p>You can see that the count in the cache is 5 this time even though we have set alimit to 3. This is because the implementation ofActiveRecord::Base#collection_cache_key<a href="https://github.com/rails/rails/blob/39f383bad01e52c217c9007b5e9d3b239fe6a808/activerecord/lib/active_record/collection_cache_key.rb#L16">executes query without limit</a>to fetch the size of the collection.</p><h4>Cache key doesn't change when an existing record from a collection is replaced</h4><p>I want 3 users in the descending order of ids.</p><pre><code class="language-ruby"> users1 = User.where(city: 'Miami').order('id desc').limit(3) users1.cache_key =&gt; &quot;users/query-57ee9977bb0b04c84711702600aaa24b-3-20160116144936949365&quot;</code></pre><p>Above statement will give us users with ids <code>[5, 4, 3]</code>.</p><p>Now let's remove the user with id = 3.</p><pre><code class="language-ruby"> User.find(3).destroy users2 = User.where(first_name: 'Sam').order('id desc').limit(3) users2.cache_key =&gt; &quot;users/query-57ee9977bb0b04c84711702600aaa24b-3-20160116144936949365&quot;</code></pre><p>Note that <code>cache_key</code> both <code>users1</code> and <code>users2</code> is exactly same. This isbecause none of the parameters that affect the cache key is changed i.e.,neither the number of records, nor the query statement, nor the timestamp of thelatest record.</p><p>There is <a href="https://github.com/rails/rails/pull/21503">a discussion undergoing</a>about adding ids of the collection records as part of the cache key. This mighthelp solve the problems discussed above.</p><h4>Using group query gives incorrect size in the cache key</h4><p>Just like <code>limit</code> case discussed above <code>cache_key</code> behaves differently when datais loaded and when data is not loaded in memory.</p><p>Let's say that we have two users with first_name &quot;Sam&quot;.</p><p>First let's see a case where collection is not loaded in memory.</p><pre><code class="language-ruby"> User.select(:first_name).group(:first_name).cache_key =&gt; &quot;users/query-92270644d1ec90f5962523ed8dd7a795-1-20160118080134697603&quot;</code></pre><p>In the above case, the size is 1 in <code>cache_key</code>. For the system mentioned above,the sizes that you will get shall either be 1 or 5. That is, it is size of anarbitrary group.</p><p>Now let's see when collection is first loaded.</p><pre><code class="language-ruby"> users = User.select(:first_name).group(:first_name) users.cache_key =&gt; &quot;users/query-92270644d1ec90f5962523ed8dd7a795-2-20160118080134697603&quot;</code></pre><p>In the above case, the size is 2 in <code>cache_key</code>. You can see that the count inthe cache key here is different compared to that where the collection wasunloaded even though the query output in both the cases will be exactly same.</p><p>In case where the collection is loaded, the size that you get is equal to thetotal number of groups. So irrespective of what the records in each group are,we may have possibility of having the same cache key value.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Caching in development environment in Rails 5]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/caching-in-development-environment-in-rails5"/>
      <updated>2016-01-25T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/caching-in-development-environment-in-rails5</id>
      <content type="html"><![CDATA[<p>In Rails 4 if I'm doing work related to caching then first I need to turncaching &quot;on&quot; by opening file <code>config/environments/development.rb</code> and changingfollowing line.</p><pre><code class="language-ruby">config.action_controller.perform_caching = false</code></pre><p>After changing the value from <code>false</code> to <code>true</code>, I need to restart the server.</p><p>This means that if I am testing caching behavior locally then every time I turncaching &quot;on&quot; or &quot;off&quot; I need to restart the server.</p><h2>New command to create development cache in Rails 5</h2><p>Rails 5 has introduced a new command to create development cache and help ustest how caching behaves in development mode. Here is the<a href="https://github.com/rails/rails/issues/18875">issue</a> and here is the<a href="https://github.com/rails/rails/pull/20961">pull request</a>.</p><pre><code class="language-plaintext">$ rails dev:cacheDevelopment mode is now being cached.</code></pre><p>Execution of the above command creates file <code>caching-dev.txt</code> in <code>tmp</code>directory.</p><h2>How does it work?</h2><p>In Rails 5 when a brand new Rails app is created then<code>config/environments/development.rb</code> file will have the following snippet ofcode.</p><pre><code class="language-ruby">if Rails.root.join('tmp/caching-dev.txt').exist?  config.action_controller.perform_caching = true  config.static_cache_control = &quot;public, max-age=172800&quot;  config.cache_store = :mem_cache_storeelse  config.action_controller.perform_caching = false  config.cache_store = :null_storeend</code></pre><p>In the above code we are checking if the file <code>tmp/caching-dev.txt</code> is presentand then use <code>:mem_cache_store</code> to enable caching only if the file is found.</p><p>Also, here is a snippet from the<a href="https://github.com/rails/rails/blob/master/railties/lib/rails/commands/dev/dev_command.rb">dev cache source code</a>.</p><pre><code class="language-ruby">def dev_cache  if File.exist? 'tmp/caching-dev.txt'    File.delete 'tmp/caching-dev.txt'    puts 'Development mode is no longer being cached.'  else    FileUtils.touch 'tmp/caching-dev.txt'    puts 'Development mode is now being cached.'  end  FileUtils.touch 'tmp/restart.txt'end</code></pre><h2>What is the advantage</h2><p>The advantage is that we do not need to restart the server manually if we wantto turn caching &quot;on&quot; or &quot;off&quot;. It is internally taken care by the <code>dev_cache</code>method that is executed when <code>rails dev:cache</code> is executed. You can see in thesource code that <code>tmp/restart.txt</code> is being <strong>touched</strong>.</p><p>Please note that <strong>this feature is not supported</strong> by unicorn, thin and webrick.My guess is that DHH wants this feature because his team uses pow and powrestarts when <code>tmp/restart.txt</code> is touched. He also created an issue for<a href="https://github.com/rails/rails/issues/18874">spring to watch tmp/restart.txt</a>long time back.</p><h2>Disabling development cache</h2><p>Execute the same command that was used to enable caching. If caching waspreviously enabled then it will be turned &quot;off&quot; now.</p><pre><code class="language-plaintext">$ rails dev:cacheDevelopment mode is no longer being cached.</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 wraps all rake commands using rails]]></title>
       <author><name>Mohit Natoo</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-supports-rake-commands-using-rails"/>
      <updated>2016-01-14T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-supports-rake-commands-using-rails</id>
      <content type="html"><![CDATA[<p>In Rails 4 some commands start with <code>rails</code> and some commands start with <code>rake</code>.This could be quite confusing for people new to Rails. Let's see an example.</p><p>Our task is to write a database migration and then to run that migration.</p><pre><code class="language-ruby">rails g migration create_users</code></pre><p>Above command creates a migration. Now we need to run that migration.</p><pre><code class="language-ruby">rake db:migrate</code></pre><p>As you can see first command starts with <code>rails</code> and second command starts with<code>rake</code>.</p><p>In order to consolidate them we can either use <code>rails</code> for everything or we canuse <code>rake</code> for everything.</p><h2>Choosing rails command over rake command</h2><p>Some favor using <code>rake</code> over <code>rails</code>. But an important feature missing in Rakeis the ability to pass arguments.</p><pre><code class="language-ruby">rails console development</code></pre><p>In order to execute the above command using <code>rake</code> we will have to pass<code>console</code> and <code>development</code> as arguments. We can pass these values usingenvironment variables. That would mean adding additional code in Rake task tofetch right values and then only we will be able to invoke command<code>rails console development</code>.</p><h2>Rails 5 enables executing rake commands with rails</h2><p>Rails core team <a href="https://github.com/rails/rails/pull/22288">decided</a> to haveconsistency by enabling <code>rails</code> command to support everything that <code>rake</code> does.</p><p>For example in Rails 5 commands like <code>db:migrate</code>, <code>setup</code>, <code>test</code> etc which arepart of <code>rake</code> command in Rails 4 are now being supported by <code>rails</code> command.However you can still choose to use <code>rake</code> to run those commands similar to howthey were run in Rails 4. This is because Rails community has<a href="https://github.com/rails/rails/blob/f718e52bcce02bc137263ead3a9d9f5df1c42c37/railties/lib/rails/commands/rake_proxy.rb">introduced Rake Proxy</a>instead of completely moving the command options from <code>rake</code> to <code>rails</code>.</p><p>What happens internally is that when <code>rails db:migrate</code> command is executed,Rails checks if <code>db:migrate</code> is something that <code>rails</code> natively supports or not.In this case <code>db:migrate</code> is not natively supported by <code>rails</code>, so Railsdelegates the execution to Rake via Rake Proxy.</p><p>If you want to see all the commands that is supported by <code>rails</code> in Rails 5 thenyou can get a long list of options by executing <code>rails --help</code>.</p><h3>Use app namespace for framework tasks in Rails 5</h3><p>As <code>rails</code> command is now preferred over <code>rake</code> command, few rails namespacedframework tasks started looking little odd.</p><pre><code class="language-bash">$ rails rails:update$ rails rails:template$ rails rails:templates:copy$ rails rails:update:configs$ rails rails:update:bin</code></pre><p>So, Rails team decided to change the namespace for these tasks from <code>rails</code> to<code>app</code>.</p><pre><code class="language-bash">$ rails app:update$ rails app:template$ rails app:templates:copy$ rails app:update:configs$ rails app:update:bin</code></pre><p>Using <code>rails rails:update</code> will now give deprecation warning like:<code>DEPRECATION WARNING: Running update with the rails: namespace is deprecated in favor of app: namespace. Run bin/rails app:update instead</code>.</p><h2>More improvements in pipeline</h2><p>In Rails 4, the routes are usually searched like this.</p><pre><code class="language-plaintext">$ rake routes | grep pattern</code></pre><p>There <a href="https://github.com/rails/rails/issues/18902">is an effort underway</a> tohave a Rails command which might work as shown below.</p><pre><code class="language-plaintext">$ rails routes -g pattern</code></pre><p>There is also<a href="https://github.com/rails/rails/pull/20420">an effort to enable lookup for controller</a>like this.</p><pre><code class="language-plaintext">$ rails routes -c some_controller</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Each form gets its own CSRF token in Rails 5]]></title>
       <author><name>Prajakta Tambe</name></author>
      <link href="https://www.bigbinary.com/blog/per-form-csrf-token-in-rails-5"/>
      <updated>2016-01-11T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/per-form-csrf-token-in-rails-5</id>
      <content type="html"><![CDATA[<p>We have <a href="csrf-and-rails">written an extensive blog</a> on what <strong>CSRF</strong> is and whatsteps Rails 4 takes to prevent CSRF. We encourage you to read that blog to fullyunderstand rest of this article.</p><h2>Nested form can get around CSRF protection offered by Rails 4</h2><p>A typical form generated in Rails 4 might look like this.</p><pre><code class="language-plaintext">&lt;form method= &quot;post&quot; action=&quot;/money_transfer&quot;&gt;  &lt;input type=&quot;hidden&quot; name=&quot;authenticity_token&quot; value=&quot;token_value&quot;&gt;&lt;/form&gt;</code></pre><p>Using code-injection, a Hacker can add another form tag above the form taggenerated by Rails using JavaScript. Now the markup looks like this.</p><pre><code class="language-plaintext">&lt;form method=&quot;post&quot; action=&quot;http://www.fraud.com/fraud&quot;&gt;  &lt;form method= &quot;post&quot; action=&quot;/money_transfer&quot;&gt;    &lt;input type=&quot;hidden&quot; name=&quot;authenticity_token&quot; value=&quot;token_value&quot;&gt;  &lt;/form&gt;&lt;/form&gt;</code></pre><p>HTML specification<a href="http://stackoverflow.com/questions/379610/can-you-nest-html-forms">does not allow nested forms</a>.</p><p>Since nested forms are not allowed browser will accept the top most level form.In this case that happens to be the form created by the hacker. When this formis submitted then &quot;authenticity_token&quot; is also submitted and Rails will do itscheck and will say everything is looking good and thus hacker will be able tohack the site.</p><h2>Rails 5 fixes the issue by generating a custom token for a form</h2><p>In Rails 5,<a href="https://github.com/rails/rails/pull/22275">CSRF token can be added for each form</a>.Each CSRF token will be valid only for the method/action of the form it wasincluded in.</p><p>You can add following line to your controller to add authenticity token specificto method and action in each form tag of the controller.</p><pre><code class="language-ruby">class UsersController &lt; ApplicationController  self.per_form_csrf_tokens = trueend</code></pre><p>Adding that code to each controller feels burdensome. In that case you canenable this behavior for all controllers in the application by adding followingline to an initializer.</p><pre><code class="language-ruby"># config/application.rbRails.configuration.action_controller.per_form_csrf_tokens = true</code></pre><p>This will add authenticity token specific to method and action in each form tagof the application. After adding that token the generated form might look likeas shown below.</p><pre><code class="language-plaintext">&lt;form method= &quot;post&quot; action=&quot;/money_transfer&quot;&gt;  &lt;input type=&quot;hidden&quot; name=&quot;authenticity_token&quot; value=&quot;money_transfer_post_action_token&quot;&gt;&lt;/form&gt;</code></pre><p>Authenticity token included here will be specific to action <code>money_transfer</code> andmethod <code>post</code>. Attacker can still grab authenticity_token here, but attack willbe limited to <code>money_transfer post</code> action.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Rendering views outside of controllers in Rails 5]]></title>
       <author><name>Prathamesh Sonpatki</name></author>
      <link href="https://www.bigbinary.com/blog/rendering-views-outside-of-controllers-in-rails-5"/>
      <updated>2016-01-08T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rendering-views-outside-of-controllers-in-rails-5</id>
      <content type="html"><![CDATA[<p>Rails request-response cycle is very easy to understand. A request hits the app,a route is matched to a controller action from <code>routes.rb</code>, and finallycontroller action processes the request and renders HTML or JSON based on thetype of the request.</p><p>But sometimes we want to render our HTML or JSON response outside of thisrequest-response cycle.</p><p>For example let's say user is allowed to download PDF version of a report onweb. This can be done using request-response cycle. We also need to send aweekly report to managers and the email should have the report as an attachment.Now we need to generate the same PDF but since emails are sent using backgroundjob the request-response cycle is missing.</p><p>Rails 5 has this feature baked in.</p><p>Let's say we have a <code>OrdersController</code> and we want to render individual orderoutside of controller.</p><p>Fire up <code>rails console</code> and execute following command.</p><pre><code class="language-ruby">OrdersController.render :show, assigns: { order: Order.last }</code></pre><p>This will render <code>app/views/orders/show.html.erb</code> with <code>@order</code> set to<code>Order.last</code>. Instance variables can be set using <code>assigns</code> in the same way weuse them in controller actions. Those instance variables will be passed to theview that is going to be rendered.</p><p>Rendering partials is also possible.</p><pre><code class="language-ruby">OrdersController.render :_form, locals: { order: Order.last }</code></pre><p>This will render <code>app/views/orders/_form.html.erb</code> and will pass <code>order</code> aslocal variable.</p><p>Say I want to render all orders, but in JSON format.</p><pre><code class="language-plaintext">OrdersController.render json: Order.all# =&gt; &quot;[{&quot;id&quot;:1, &quot;name&quot;:&quot;The Well-Grounded Rubyist&quot;, &quot;author&quot;:&quot;David A. Black&quot;},       {&quot;id&quot;:2, &quot;name&quot;:&quot;Remote: Office not required&quot;, &quot;author&quot;:&quot;David &amp; Jason&quot;}]</code></pre><p>Even rendering simple text is possible.</p><pre><code class="language-ruby">&gt;&gt; BooksController.render plain: 'this is awesome!'  Rendered text template (0.0ms)# =&gt; &quot;this is awesome!&quot;</code></pre><p>Similar to <code>text</code>, we can also use <code>render file</code> and <code>render template</code>.</p><h3>Request environment</h3><p>A typical web request carries its own environment with it. We usually handlethis environment using <code>request.env</code> in controllers. Certain gems like <code>devise</code>depends on <code>env</code> hash for information such as warden token.</p><p>So when we are rendering outside of controller, we need to make sure that therendering happens with correct environment.</p><p>Rails provides a default rack environment for this purpose. The default optionsused can be accessed through <code>renderer.defaults</code>.</p><pre><code class="language-ruby">&gt;&gt; OrdersController.renderer.defaults=&gt; {:http_host=&gt;&quot;example.org&quot;, :https=&gt;false, :method=&gt;&quot;get&quot;, :script_name=&gt;&quot;&quot;, :input=&gt;&quot;&quot;}</code></pre><p>Internally, Rails will build a new Rack environment based on these options.</p><h2>Customizing the environment</h2><p>We can customize environment using method <code>renderer</code>. Let's say that we need&quot;method as post&quot; and we want &quot;https to be true&quot; for our background jobprocessing.</p><pre><code class="language-ruby">renderer = ApplicationController.renderer.new(method: 'post', https: true)# =&gt; #&lt;ActionController::Renderer:0x007fdf34453f10 @controller=ApplicationController, @defaults={:http_host=&gt;&quot;example.org&quot;, :https=&gt;false, :method=&gt;&quot;get&quot;, :script_name=&gt;&quot;&quot;, :input=&gt;&quot;&quot;}, @env={&quot;HTTP_HOST&quot;=&gt;&quot;example.org&quot;, &quot;HTTPS&quot;=&gt;&quot;on&quot;, &quot;REQUEST_METHOD&quot;=&gt;&quot;POST&quot;, &quot;SCRIPT_NAME&quot;=&gt;&quot;&quot;, &quot;rack.input&quot;=&gt;&quot;&quot;}&gt;</code></pre><p>Now that we have our custom <code>renderer</code> we can use it to generate view.</p><pre><code class="language-ruby">renderer.render template: 'show', locals: { order: Order.last }</code></pre><p>Overall this is a nice feature which enables reuse of existing code.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Test runner in Rails 5]]></title>
       <author><name>Prathamesh Sonpatki</name></author>
      <link href="https://www.bigbinary.com/blog/test-runner-in-rails-5"/>
      <updated>2016-01-03T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/test-runner-in-rails-5</id>
      <content type="html"><![CDATA[<p>If you run <code>bin/rails -h</code> in a Rails 5 app, you will see a new command forrunning tests.</p><pre><code class="language-bash">$ bin/rails -hUsage: rails COMMAND [ARGS]The most common rails commands are: generate    Generate new code (short-cut alias: &quot;g&quot;) console     Start the Rails console (short-cut alias: &quot;c&quot;) server      Start the Rails server (short-cut alias: &quot;s&quot;) test        Run tests (short-cut alias: &quot;t&quot;)</code></pre><p>Before Rails 5, we had to use <code>bin/rake test</code> to run tests. But in Rails 5, wecan use <code>bin/rails test</code>. It is not just replacement of old rake task but it isbacked by a <code>test runner</code> inspired from RSpec, minitest-reporters, maxitest andothers.</p><p>Let's see what <code>bin/rails test</code> can do.</p><h2>Running a single test</h2><p>Now it is possible to run a single test out of the box using the line number ofthe test.</p><pre><code class="language-bash">$ bin/rails test test/models/user_test.rb:27</code></pre><p>Rails will intelligently run the test from user_test.rb having line number 27.Note that the line number 27 does not need to be first line of the test. Belowis an example.</p><pre><code class="language-ruby">22: def test_valid_user23:   hash = { email: 'bob@exmaple.com',24:            first_name: 'John',25:            last_name: 'Smith' }26:27:   user = User.new hash28:29:   assert user.valid?30: end</code></pre><p>In the above case, <code>test_valid_user</code> can be run as long as the line numberprovided is between 22 and 30.</p><h2>Running multiple tests</h2><p>You can also pass multiple test paths and Rails will run all of those tests.</p><pre><code class="language-bash">$ bin/rails test test/models/user_test.rb:27 test/models/post_test.rb:42</code></pre><p>It is also possible to run all tests from a directory.</p><pre><code class="language-bash">$ bin/rails test test/controllers test/integration</code></pre><h2>Improved failure messages</h2><p>When a test fails, Rails displays a command which can be used to just run thefailed test.</p><pre><code class="language-bash">$ bin/rails tRun options: --seed 51858# Running:.FFailure:PostsControllerTest#test_should_get_new:Expected response to be a &lt;success&gt;, but was a &lt;302&gt; redirect to &lt;http://test.host/posts&gt;bin/rails test test/controllers/posts_controller_test.rb:15</code></pre><p>I can simply copy <code>bin/rails test test/controllers/posts_controller_test.rb:15</code>and rerun the failing test.</p><h2>Failing fast</h2><p>By default when a test fails then rails reports about the test failures and thenmoves on to the next test. If you want to stop running the test when a testfails then use option <code>-f</code>.</p><pre><code class="language-bash">$ bin/rails t -fRun options: -f --seed 59599# Running:..FFailure:PostsControllerTest#test_should_get_new:Expected response to be a &lt;success&gt;, but was a &lt;302&gt; redirect to &lt;http://test.host/posts&gt;bin/rails test test/controllers/posts_controller_test.rb:15Interrupted. Exiting...Finished in 0.179125s, 16.7481 runs/s, 22.3308 assertions/s.3 runs, 4 assertions, 1 failures, 0 errors, 0 skips</code></pre><h2>Defer test output until the end of the full test run</h2><p>By default when a test fails then rails prints <code>F</code> and then details about thefailure like what assertion failed and how to re run the test etc.</p><p>If you want to have a clean output of <code>.</code> and <code>F</code> and would like all the testfailures report to come at the every end then use option <code>-d</code>.</p><pre><code class="language-plaintext">$ bin/rails t -dRun options: -d --seed 29906# Running:..F...FFinished in 0.201320s, 34.7704 runs/s, 49.6721 assertions/s.  1) Failure:PostsControllerTest#test_should_create_post [/Users/prathamesh/Projects/fun/rails-5-test-runner-app/test/controllers/posts_controller_test.rb:19]:&quot;Post.count&quot; didn't change by 1.Expected: 3  Actual: 2  2) Failure:PostsControllerTest#test_should_get_new [/Users/prathamesh/Projects/fun/rails-5-test-runner-app/test/controllers/posts_controller_test.rb:15]:Expected response to be a &lt;success&gt;, but was a &lt;302&gt; redirect to &lt;http://test.host/posts&gt;7 runs, 10 assertions, 2 failures, 0 errors, 0 skipsFailed tests:bin/rails test test/controllers/posts_controller_test.rb:19bin/rails test test/controllers/posts_controller_test.rb:15</code></pre><h2>Better backtrace output</h2><p>By default when an error is encountered while running the test then the outputdoes not contain full stacktrace. This makes debugging little bit difficult.</p><pre><code class="language-plaintext">Error:PostsControllerTest#test_should_create_post:NameError: undefined local variable or method `boom' for #&lt;PostsController:0x007f86bc62b728&gt;    app/controllers/posts_controller.rb:29:in `create'    test/controllers/posts_controller_test.rb:20:in `block (2 levels) in &lt;class:PostsControllerTest&gt;'    test/controllers/posts_controller_test.rb:19:in `block in &lt;class:PostsControllerTest</code></pre><p>Now we can use <code>-b</code> switch, which will display complete backtrace of errormessage.</p><pre><code class="language-plaintext">$ bin/rails t -bError:PostsControllerTest#test_should_create_post:NameError: undefined local variable or method `boom' for #&lt;PostsController:0x007fc53c4eb868&gt;    /rails-5-test-runner-app/app/controllers/posts_controller.rb:29:in `create'    /sources/rails/actionpack/lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'    /sources/rails/actionpack/lib/abstract_controller/base.rb:183:in `process_action'    /sources/rails/actionpack/lib/action_controller/metal/rendering.rb:30:in `process_action'    /sources/rails/actionpack/lib/abstract_controller/callbacks.rb:20:in `block in process_action'    /sources/rails/activesupport/lib/active_support/callbacks.rb:126:in `call'.....    /sources/rails/activesupport/lib/active_support/testing/assertions.rb:71:in `assert_difference'    /rails-5-test-runner-app/test/controllers/posts_controller_test.rb:19:in `block in &lt;class:PostsControllerTest&gt;'</code></pre><h2>Leveraging power of Minitest</h2><p>The test runner also leverages power of minitest by providing some handyoptions.</p><h5>Switch -s to provide your own seed</h5><p>Now we can also provide our own seed using <code>-s</code> switch.</p><pre><code class="language-bash">$ bin/rails t --s 42000</code></pre><h4>Switch -n to run matching tests</h4><p>Switch <code>-n</code> will run tests matching the given string or regular expressionpattern.</p><pre><code class="language-plaintext">$ bin/rails t -n &quot;/create/&quot;Run options: -n /create/ --seed 24558# Running:EError:PostsControllerTest#test_should_create_post:NameError: undefined local variable or method `boom' for #&lt;PostsController:0x007faa39c2df90&gt;    app/controllers/posts_controller.rb:29:in `create'    test/controllers/posts_controller_test.rb:20:in `block (2 levels) in &lt;class:PostsControllerTest&gt;'    test/controllers/posts_controller_test.rb:19:in `block in &lt;class:PostsControllerTest&gt;'bin/rails test test/controllers/posts_controller_test.rb:18Finished in 0.073857s, 13.5396 runs/s, 0.0000 assertions/s.1 runs, 0 assertions, 0 failures, 1 errors, 0 skips</code></pre><h4>Verbose output</h4><p>It is also possible to see the verbose output using <code>-v</code> switch. It shows timerequired to run each test. This would help in detecting slow running tests.</p><pre><code class="language-plaintext">$ bin/rails t -vRun options: -v --seed 30118# Running:PostsControllerTest#test_should_destroy_post = 0.07 s = .PostsControllerTest#test_should_update_post = 0.01 s = .PostsControllerTest#test_should_show_post = 0.10 s = .PostsControllerTest#test_should_create_post = 0.00 s = FFailure:PostsControllerTest#test_should_create_post:&quot;Post.count&quot; didn't change by 1.Expected: 3  Actual: 2bin/rails test test/controllers/posts_controller_test.rb:19PostsControllerTest#test_should_get_new = 0.02 s = .PostsControllerTest#test_should_get_index = 0.01 s = .PostsControllerTest#test_should_get_edit = 0.00 s = .Finished in 0.210071s, 33.3220 runs/s, 47.6028 assertions/s.7 runs, 10 assertions, 1 failures, 0 errors, 0 skips</code></pre><h3>Colored output</h3><p>Now by default we will get colored output. No need to add additional gem tocolored output.</p><p><img src="/blog_images/2016/test-runner-in-rails-5/rails_5_test_runner.png" alt="colored test output"></p><p>With all these awesome features, testing Rails 5 apps has definitely become abetter experience. Rails has shipped all these features within the frameworkitself so you don't have to use multiple gems and libraries to achieve all ofthese things.</p>]]></content>
    </entry><entry>
       <title><![CDATA[ApplicationRecord in Rails 5]]></title>
       <author><name>Prathamesh Sonpatki</name></author>
      <link href="https://www.bigbinary.com/blog/application-record-in-rails-5"/>
      <updated>2015-12-28T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/application-record-in-rails-5</id>
      <content type="html"><![CDATA[<p><a href="http://weblog.rubyonrails.org/2015/12/18/Rails-5-0-beta1/">Rails 5 beta-1</a> wasrecently released and one of the notable change was introduction of<a href="https://github.com/rails/rails/pull/22567">ApplicationRecord</a>.</p><p>Up to Rails 4.2, all models inherited from <code>ActiveRecord::Base</code>. But startingfrom Rails 5, all models will inherit from <code>ApplicationRecord</code>.</p><pre><code class="language-ruby">class Post &lt; ApplicationRecordend</code></pre><p>What happened to <code>ActiveRecord::Base</code> ?</p><p>Well not much changed in reality. Following file will be automatically added tomodels in Rails 5 applications.</p><pre><code class="language-ruby"># app/models/application_record.rbclass ApplicationRecord &lt; ActiveRecord::Base  self.abstract_class = trueend</code></pre><p>This behavior is similar to how controllers inherit from <code>ApplicationController</code>instead of inheriting from <code>ActionController::Base</code>.</p><p>Now <code>ApplicationRecord</code> will be a single point of entry for all thecustomizations and extensions needed for an application, instead of monkeypatching <code>ActiveRecord::Base</code>.</p><p>Say I want to add some extra functionality to Active Record. This is what Iwould do in Rails 4.2.</p><pre><code class="language-ruby">module MyAwesomeFeature  def do_something_great    puts &quot;Doing something complex stuff!!&quot;  endendActiveRecord::Base.include(MyAwesomeFeature)</code></pre><p>But now, <code>ActiveRecord::Base</code> forever includes <code>MyAwesomeFeature</code> and any classinheriting from it also includes <code>MyAwesomeFeature</code> even if they don't want it.</p><p>This is especially true if you are using plugins and engines where monkeypatching to <code>ActiveRecord::Base</code> can leak into engine or plugin code.</p><p>But with <code>ApplicationRecord</code>, they will be localized to only those models whichare inheriting from <code>ApplicationRecord</code>, effectively only to your application.</p><pre><code class="language-ruby">class ApplicationRecord &lt; ActiveRecord::Base  include MyAwesomeFeature  self.abstract_class = trueend</code></pre><h2>Migrating from Rails 4</h2><p>By default all new Rails 5 applications will have <code>application_record.rb</code>. Ifyou are migrating from Rails 4, then simply create<code>app/models/application_record.rb</code> as shown below and change all models toinherit from <code>ApplicationRecord</code> instead of <code>ActiveRecord::Base</code>.</p><pre><code class="language-ruby"># app/models/application_record.rbclass ApplicationRecord &lt; ActiveRecord::Base  self.abstract_class = trueend</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Rails 5 allows setting custom HTTP Headers for assets]]></title>
       <author><name>Vipul</name></author>
      <link href="https://www.bigbinary.com/blog/rails-5-allows-setting-custom-http-headers-for-assets"/>
      <updated>2015-10-31T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/rails-5-allows-setting-custom-http-headers-for-assets</id>
      <content type="html"><![CDATA[<p>Let's look at by default what kind of response headers we get when we start witha brand new Rails 4.2.4 application.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/header1.png" alt="header"></p><p>Now let's say that I want to set a custom response header. That's easy. All Ineed to do is add following line of code in the controller.</p><pre><code class="language-plaintext">response.headers['X-Tracking-ID'] = '123456'</code></pre><p>Now I see this custom response header.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/header2.png" alt="header"></p><h2>Setting custom response header for assets</h2><p>Let's say that I need that custom response header not only for standard webrequests but also for my assets. For example <code>application.js</code> file is served byRails in localhost. How would I set custom header to the asset being served byRails here.</p><p>Actually that's not possible in Rails 4. In Rails 4 we can set only one responseheader for assets that are served by Rails and that response header is<code>Cache-Control</code>.</p><p>Here is how I can configure <code>Cache-Control</code> for assets.</p><pre><code class="language-plaintext"># open config/environments/production.rb and add following lineconfig.static_cache_control = 'public, max-age=1000'</code></pre><p>Now we have modified 'Cache-Control` header for the assets.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/header3.png" alt="header"></p><p>Besides <code>Cache-Control</code> no other response header can be set for assets served byRails. That's a limitation.</p><h2>How Rails Apps lived with this limitation so far</h2><p>Rails is not the best server to serve static assets. Apace and NGINX are muchbetter at this job. Hence ,in reality, in production almost everyone puts eitherApache or NGINX in front of a Rails server and in this way Rails does not haveto serve static files.</p><p>Having said that, Rails applications hosted at Heroku is an exception. Assetsfor Rails applications running at Heroku are served by Rails application itself.</p><h3>Problem we ran into</h3><p>Our <a href="https://bigbinary.com">website</a> is hosted at heroku. When we ran<a href="https://developers.google.com/speed/pagespeed/insights/">Google page speed insights</a>for our website we were warned that we were not using <code>Expires</code> header for theassets.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/PageSpeedInsightsWarnings.png" alt="PageSpeed Insights Warning"></p><p>Here are how the header looked for <code>application.js</code>.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/bigbinary_before_expires.png" alt="PageSpeed Insights Warning"></p><p>Now you see the problem we are running into.</p><ul><li>Our application is hosted at Heroku.</li><li>Heroku lets Rails serve the assets.</li><li>Google page speed insights wants us to set <code>Expires</code> header to the assets.</li><li>Rails application allows only one header for the assets and that is'Cache-Control`.</li></ul><p>One easy solution is to host our website at<a href="https://www.digitalocean.com">Digital Ocean</a> and then use Apache or NGINX.</p><h2>Rails 5 saves the day</h2><p>Recently Rails<a href="https://github.com/rails/rails/pull/19135">merged basic support for access control headers</a>and added ability to define custom HTTP Headers on assets served by Rails.</p><p>Behind the scenes, Rails uses <code>ActionDispatch::Static</code> middleware to take careof serving assets. For example, a request to fetch an image, goes through<code>ActionDispatch::Static</code> in the request cycle. <code>ActionDispatch::Static</code> takescare of serving <code>Rack::File</code> object from server with appropriate headers set inthe response. The served image can have headers like <code>Content-Type</code>,<code>Cache-Control</code>.</p><h2>Start using Rails master</h2><p>To fix this, we first pointed the App to use Rails master.</p><pre><code class="language-ruby">gem 'rails', github: 'rails/rails'gem 'rack', github: 'rack/rack' # Rails depends on Rack 2gem 'arel', github: 'rails/arel' # Rails master works alongside of arel master.</code></pre><p>Next, we changed asset configuration to start providing and using missing headerfor <code>Expires</code>.</p><pre><code class="language-ruby"># production.rbconfig.public_file_server.headers = {  'Cache-Control' =&gt; 'public, s-maxage=31536000, max-age=15552000',  'Expires' =&gt; &quot;#{1.year.from_now.to_formatted_s(:rfc822)}&quot;}</code></pre><p>Here, we are first setting the <code>Cache-Control</code> header to use public(intermediate) caching, for a year (31536000 seconds) with <code>max-age</code> and<code>s-maxage</code>. Here <code>s-maxage</code> stands for <code>Surrogate</code> cache, which is used to cacheinternally by Fastly.</p><p>We then provide the missing <code>Expires</code> value with some future date in Internetformatted time value.</p><p>With this setup, we can see PageSpeed pickups the new headers on assets and doesnot warn us for the missing header.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/PageSpeedInsightsSolved.png" alt="PageSpeed Insights Warning"></p><p>Here is the changed response header for asset.</p><p><img src="/blog_images/2015/rails-5-allows-setting-custom-http-headers-for-assets/bigbinary_after_expires.png" alt="PageSpeed Insights Warning"></p><h2>Further Reading</h2><p>For better use and more details about different headers to use for the assets,please refer to<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html">RFC 2616</a>.</p>]]></content>
    </entry>
     </feed>