<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US">
  <title>BigBinary Blog: Rails 5.1</title>
  <subtitle>Deep technical writing on Ruby on Rails, performance, scaling, monitoring and engineering.</subtitle>
  <link rel="self" type="application/atom+xml" href="https://www.bigbinary.com/blog/categories/rails-5-1/feed.xml"/>
  <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/categories/rails-5-1"/>
  <id>https://www.bigbinary.com/blog/categories/rails-5-1</id>
  <updated>2017-11-14T00:00:00.000Z</updated>
  <author>
    <name>BigBinary</name>
    <uri>https://www.bigbinary.com/</uri>
  </author>
  <icon>https://www.bigbinary.com/favicon.ico</icon>
  <logo>https://www.bigbinary.com/images/bigbinary_square_big_logo.png</logo>
  <rights>Copyright 2017 Big Binary LLC</rights>
  <generator uri="https://nextjs.org">Next.js</generator>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 stops loading all records on Model.all#inspect]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/do-no-load-all-records-on-activerecord-relation-inspect"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/do-no-load-all-records-on-activerecord-relation-inspect.png"/>
      <id>https://www.bigbinary.com/blog/do-no-load-all-records-on-activerecord-relation-inspect</id>
      <published>2017-11-14T00:00:00.000Z</published>
      <updated>2017-11-14T00:00:00.000Z</updated>
      <author>
        <name>Mohit Natoo</name>
        <uri>https://www.bigbinary.com/blog/authors/mohit</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/do-no-load-all-records-on-activerecord-relation-inspect.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 limits number of records while calling inspect on ActiveRecord::Relation object.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/do-no-load-all-records-on-activerecord-relation-inspect"><![CDATA[<p>Let's take a project with hundreds of users. When we call inspect on <code>User.all</code>,
we see an array of 10 users followed by <code>...</code>. That means the output of
<code>#inspect</code> method shows data only for 10 records.</p>
<pre><code class="language-ruby">&gt; User.all.inspect
User Load (3.7ms)  SELECT  &quot;users&quot;.* FROM &quot;users&quot;
=&gt; &quot;#&lt;ActiveRecord::Relation [
#&lt;User id: 1, email: \&quot;dirbee@example.com\&quot; &gt;,
#&lt;User id: 2, email: \&quot;tee@example.com\&quot;&gt;,
#&lt;User id: 3, email: \&quot;scott@example.com\&quot;&gt;,
#&lt;User id: 4, email: \&quot;mark@example.com\&quot;&gt;,
#&lt;User id: 5, email: \&quot;ben@example.com\&quot;&gt;,
#&lt;User id: 6, email: \&quot;tina@example.com\&quot;&gt;,
#&lt;User id: 7, email: \&quot;tyler@example.com\&quot;&gt;,
#&lt;User id: 8, email: \&quot;peter@example.com\&quot;&gt;,
#&lt;User id: 9, email: \&quot;rutul@example.com\&quot;&gt;,
#&lt;User id: 10, email:\&quot;michael@example.com\&quot;&gt;,
...]&gt;&quot;
</code></pre>
<p>We can see that the query executed in the process is fetching all the records
even though the output doesn't need all of them.</p>
<p>In Rails 5.1,
<a href="https://github.com/rails/rails/pull/28592">only the needed records are loaded</a>
when <code>inspect</code> is called on ActiveRecord::Relation.</p>
<pre><code class="language-ruby">&gt; User.all.inspect
User Load (3.7ms)  SELECT  &quot;users&quot;.* FROM &quot;users&quot; LIMIT $1 /*application:Ace Invoice*/  [[&quot;LIMIT&quot;, 11]]

=&gt; &quot;#&lt;ActiveRecord::Relation [
#&lt;User id: 1, email: \&quot;dirbee@example.com\&quot; &gt;,
#&lt;User id: 2, email: \&quot;tee@example.com\&quot;&gt;,
#&lt;User id: 3, email: \&quot;scott@example.com\&quot;&gt;,
#&lt;User id: 4, email: \&quot;mark@example.com\&quot;&gt;,
#&lt;User id: 5, email: \&quot;ben@example.com\&quot;&gt;,
#&lt;User id: 6, email: \&quot;tina@example.com\&quot;&gt;,
#&lt;User id: 7, email: \&quot;tyler@example.com\&quot;&gt;,
#&lt;User id: 8, email: \&quot;peter@example.com\&quot;&gt;,
#&lt;User id: 9, email: \&quot;rutul@example.com\&quot;&gt;,
#&lt;User id: 10, email:\&quot;michael@example.com\&quot;&gt;,
...]&gt;&quot;
</code></pre>
<p>We can see in the above case that query executed has limit constraint and hence
only the required number of records are loaded.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[New Syntax for HTML Tag helpers in Rails 5.1]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/new-syntax-for-tag-helpers-in-rails-5-1"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/new-syntax-for-tag-helpers-in-rails-5-1.png"/>
      <id>https://www.bigbinary.com/blog/new-syntax-for-tag-helpers-in-rails-5-1</id>
      <published>2017-08-23T00:00:00.000Z</published>
      <updated>2017-08-23T00:00:00.000Z</updated>
      <author>
        <name>Prathamesh Sonpatki</name>
        <uri>https://www.bigbinary.com/blog/authors/prathamesh</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/new-syntax-for-tag-helpers-in-rails-5-1.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 introduces new shorter syntax for HTML tag helpers]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/new-syntax-for-tag-helpers-in-rails-5-1"><![CDATA[<p>Rails is great at generating HTML using helpers such as
<a href="http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag">content_tag</a>
and
<a href="http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag">tag</a>.</p>
<pre><code class="language-erb">content_tag(:div, , class: &quot;home&quot;)

&lt;div class=&quot;home&quot;&gt;
&lt;/div&gt;
</code></pre>
<p>Rails 5.1 has <a href="https://github.com/rails/rails/issues/25195">introduced</a>
<a href="https://github.com/rails/rails/pull/25543">new syntax</a> for this in the form of
enhanced <code>tag</code> helper.</p>
<p>Now that same HTML div tag can be generated as follows.</p>
<pre><code class="language-erb">tag.div class: 'home'

&lt;div class=&quot;home&quot;&gt;
&lt;/div&gt;
</code></pre>
<p>Earlier, the tag type was decided by the positional argument to the
<code>content_tag</code> and <code>tag</code> methods but now we can just call the required tag type
on the <code>tag</code> method itself.</p>
<p>We can pass the tag body and attributes in the block format as well.</p>
<pre><code class="language-erb">&lt;%= tag.div class: 'home' do %&gt;
  Welcome to Home!
&lt;% end %&gt;


&lt;div class=&quot;home&quot;&gt;
  Welcome to Home!
&lt;/div&gt;
</code></pre>
<h3>HTML5 compliant by default</h3>
<p>The new <code>tag</code> helper is also HTML 5 compliant by default, such that it respects
HTML5 features such as
<a href="https://www.w3.org/TR/html5/syntax.html#void-elements">void elements</a>.</p>
<h3>Backward compatibility</h3>
<p>The old syntax of <code>content_tag</code> and <code>tag</code> methods is still supported but might
be deprecated and removed in future versions of Rails.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 enhances ActiveSupport::TimeZone.country_zones]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-returns-unmapped-timezones-from-activesupport-timezone-country_zones"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-returns-unmapped-timezones-from-activesupport-timezone-country_zones.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-returns-unmapped-timezones-from-activesupport-timezone-country_zones</id>
      <published>2017-07-18T00:00:00.000Z</published>
      <updated>2017-07-18T00:00:00.000Z</updated>
      <author>
        <name>Narendra Rajput</name>
        <uri>https://www.bigbinary.com/blog/authors/bknarendra</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-returns-unmapped-timezones-from-activesupport-timezone-country_zones.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 now returns unmapped timezones from ActiveSupport::TimeZone.country_zones with supplied TZInfo identifier instead of empty response]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-returns-unmapped-timezones-from-activesupport-timezone-country_zones"><![CDATA[<p>The
<a href="http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html">ActiveSupport::TimeZone</a>
class serves as wrapper around
<a href="http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html">TZInfo::TimeZone</a>
class. It limits the set of zones provided by TZInfo to smaller meaningful
subset and returns zones with friendly names. For example, TZInfo gem returns
&quot;America/New_York&quot; whereas Active Support returns &quot;Eastern Time (US &amp; Canada)&quot;.</p>
<p><a href="http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-c-country_zones">ActiveSupport::TimeZone.country_zones</a>
method returns a set of TimeZone objects for timezones in a country specified as
2 character country code.</p>
<pre><code class="language-ruby"># Rails 5.0
&gt;&gt; ActiveSupport::TimeZone.country_zones('US')

=&gt; [#&lt;ActiveSupport::TimeZone:0x007fcc2b9b3198 @name=&quot;Hawaii&quot;, @utc_offset=nil, @tzinfo=#&lt;TZInfo::DataTimezone: Pacific/Honolulu&gt;&gt;, #&lt;ActiveSupport::TimeZone:0x007fcc2b9d9ac8 @name=&quot;Alaska&quot;, @utc_offset=nil, @tzinfo=#&lt;TZInfo::DataTimezone: America/Juneau&gt;&gt;, #&lt;ActiveSupport::TimeZone:0x007fcc2ba03a08 @name=&quot;Pacific Time (US &amp; Canada)&quot;, @utc_offset=nil, @tzinfo=#&lt;TZInfo::DataTimezone: America/Los_Angeles&gt;&gt;,...]
</code></pre>
<p>In Rails 5.0, the <code>country_zones</code> method returns empty for some countries. This
is because <code>ActiveSupport::TimeZone::MAPPING</code> supports only a limited number of
timezone names.</p>
<pre><code class="language-ruby">
&gt;&gt; ActiveSupport::TimeZone.country_zones('SV') // El Salvador

=&gt; []
</code></pre>
<p>Rails 5.1
<a href="https://github.com/rails/rails/commit/ec9b4d39108d4c22d00426fa95c61b8b37dfe4e3">fixed</a>
this <a href="https://github.com/rails/rails/issues/28431">issue</a>. So now if the country
is not found in the <code>MAPPING</code> hash then a new <code>ActiveSupport::TimeZone</code> instance
for the country is returned.</p>
<pre><code class="language-ruby">
&gt;&gt; ActiveSupport::TimeZone.country_zones('SV') // El Salvador

=&gt; [#&lt;ActiveSupport::TimeZone:0x007ff0dab83080 @name=&quot;America/El_Salvador&quot;, @utc_offset=nil, @tzinfo=#&lt;TZInfo::DataTimezone: America/El_Salvador&gt;&gt;]
</code></pre>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 dropped jQuery dependency in default stack]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack</id>
      <published>2017-06-20T00:00:00.000Z</published>
      <updated>2017-06-20T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[jQuery dropped as a dependency from Rails 5.1 onwards and replaced by a vanilla rails-ujs driver for the unobtrusive JavaScript helpers]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack"><![CDATA[<p>Rails has been dependent on jQuery for providing the unobtrusive JavaScript
helpers such as
<a href="http://guides.rubyonrails.org/working_with_javascript_in_rails.html#unobtrusive-javascript">data-remote, data-url and the Ajax interactions</a>.
Every Rails application before Rails 5.1 would have the <code>jquery-rails</code> gem
included by default.</p>
<p>The <code>jquery-rails</code> gem contains the jquery-ujs driver which provides all the
nice unobtrusive features.</p>
<p>But now JavaScript has progressed well such that we can write the unobtrusive
driver which Rails needs using just plain vanilla JavaScript.</p>
<p>That's what has happened for the 5.1 release. The <code>jquery-ujs</code> driver has been
rewritten using just plain JavaScript as part of a GSoC project by
<a href="https://github.com/liudangyi">Dangyui Liu</a>.</p>
<p>Now that the unobtrusive JavaScript driver does not depend on jQuery, new Rails
applications also need not depend on jQuery.</p>
<p>So, Rails 5.1 has <a href="https://github.com/rails/rails/issues/25208">dropped jQuery</a>
as a
<a href="https://github.com/rails/rails/pull/27113">dependency from the default stack</a>.</p>
<p>The current <a href="https://github.com/rails/jquery-rails">jquery-based</a> approach would
still be available. It's just that it's not part of the default stack. You will
need to manually add the <code>jquery-rails</code> gem to newly created 5.1 application and
<a href="https://github.com/rails/jquery-ujs#installation-using-the-jquery-rails-gem">update the application.js</a>
to include the <code>jquery-ujs</code> driver.</p>
<p>It's worth noting that <code>rails-ujs</code> only supports IE 11+. Visit the
<a href="https://basecamp.com/help/3/guides/account/browsers#desktop-browser-support">Desktop Browser Support</a>
section of Basecamp to see the full list of all the supported browsers.</p>
<h4>Browsers support without jQuery</h4>
<p>We saw some discussion about which all browsers are supported without jQuery. We
decided to test it ourselves on a plain vanilla CRUD Rails app. We tested
&quot;adding&quot;, &quot;editing&quot; and &quot;deleting&quot; of a resource.</p>
<p><strong>We found that all three operations (adding, editing and deleting) to be
working in following cases.</strong></p>
<ul>
<li>Win 7 - IE 9</li>
<li>Win 7 - IE 10</li>
<li>Win 7 - IE 11</li>
<li>Win 8 - IE 10</li>
<li>Win 8.1 - IE 11</li>
<li>Win 10 - IE 14 Edge</li>
<li>Win 10 - IE 15 Edge</li>
<li>Win 10 - Firefox 53</li>
<li>Win 10 - Chrome 58</li>
<li>Win 10 - Safari 5.1</li>
<li>Mac Sierra - Safari 10.1</li>
<li>Mac Sierra - Firefox 53</li>
<li>Mac Sierra - Chrome 58</li>
</ul>
<h4>API change for the event handlers</h4>
<p><code>rails-ujs</code> driver has changed the signature of the event handler functions to
just pass one <code>event</code> object instead of <code>event</code>, <code>data</code>, <code>status</code> and <code>xhr</code> as
in the case of <code>jquery-ujs</code> driver.</p>
<p>Check the
<a href="http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers">documentation for the rails-ujs event handlers</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 adds delegate_missing_to]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-adds-delegate-missing-to"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-adds-delegate-missing-to.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-adds-delegate-missing-to</id>
      <published>2017-05-30T00:00:00.000Z</published>
      <updated>2017-05-30T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-adds-delegate-missing-to.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 has introduced `Module#delegate_missing_to` to keep decorators more clearer]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-adds-delegate-missing-to"><![CDATA[<p>When we use <code>method_missing</code> then we should also use
<a href="http://blog.marc-andre.ca/2010/11/15/methodmissing-politely/">respond_to_missing?</a>.
Because of this code becomes verbose since both <code>method_missing</code> and
<code>respond_to_missing?</code> need to move in tandem.</p>
<p>DHH in <a href="https://github.com/rails/rails/issues/23824">the issue</a> itself provided
a good example of this verbosity.</p>
<pre><code class="language-ruby">
class Partition
  def initialize(first_event)
    @events = [ first_event ]
  end

  def people
    if @events.first.detail.people.any?
      @events.collect { |e| Array(e.detail.people) }.flatten.uniq
    else
      @events.collect(&amp;:creator).uniq
    end
  end

  private
    def respond_to_missing?(name, include_private = false)
      @events.respond_to?(name, include_private)
    end

    def method_missing(method, *args, &amp;block)
      @events.public_send(method, *args, &amp;block)
    end
end
</code></pre>
<p>He proposed to use a new method <code>delegate_missing_to</code>. Here is how it can be
used.</p>
<pre><code class="language-ruby">class Partition
  delegate_missing_to :@events

  def initialize(first_event)
    @events = [ first_event ]
  end

  def people
    if @events.first.detail.people.any?
      @events.collect { |e| Array(e.detail.people) }.flatten.uniq
    else
      @events.collect(&amp;:creator).uniq
    end
  end
end
</code></pre>
<h2>Why not SimpleDelegator</h2>
<p>We at BigBinary have used
<a href="https://ruby-doc.org/stdlib-2.2.1/libdoc/delegate/rdoc/SimpleDelegator.html">SimpleDelegator</a>.
However one issue with this is that statically we do not know to what object the
calls are getting delegated to since at run time the delegator could be
anything.</p>
<p>DHH had following to
<a href="https://github.com/rails/rails/issues/23824#issuecomment-221171899">say</a> about
this pattern.</p>
<blockquote>
<p>I prefer not having to hijack the inheritance tree for such a simple feature.</p>
</blockquote>
<h2>Why not delegate method</h2>
<p><a href="https://apidock.com/rails/Module/delegate">Delegate</a> method works. However here
we need to white list all the methods and in some cases the list can get really
long. Following is a real example from a real project.</p>
<pre><code class="language-ruby">delegate :browser_status, :browser_stats_present?,
         :browser_failed_count, :browser_passed_count,
         :sequential_id, :project, :initiation_info,
         :test_run, success?,
         to: :test_run_browser_stats
</code></pre>
<h2>Delegate everything</h2>
<p>Sometimes we just want to delegate all missing methods. In such cases method
<code>delegate_missing_to</code> does the job neatly. Note that the delegation happens to
only <code>public</code> methods of the object being delegated to.</p>
<p>Check out the <a href="https://github.com/rails/rails/pull/23930">pull request</a> for more
details on this.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 adds support for limit in batch processing]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-adds-support-for-limit-in-batch-processing"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-adds-support-for-limit-in-batch-processing.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-adds-support-for-limit-in-batch-processing</id>
      <published>2017-05-23T00:00:00.000Z</published>
      <updated>2017-05-23T00:00:00.000Z</updated>
      <author>
        <name>Mohit Natoo</name>
        <uri>https://www.bigbinary.com/blog/authors/mohit</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-adds-support-for-limit-in-batch-processing.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 can now limit the number of records fetched for batch processing.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-adds-support-for-limit-in-batch-processing"><![CDATA[<p>Before Rails 5.1, we were not able to limit the number of records fetched in
batch processing.</p>
<p>Let's take an example. Assume our system has 20 users.</p>
<pre><code class="language-ruby">
 User.find_each{ |user| puts user.id }

</code></pre>
<p>The above code will print ids of all the 20 users.</p>
<p>There was no way to limit the number of records. Active Record's <code>limit</code> method
didn't work for batches.</p>
<pre><code class="language-ruby">
 User.limit(10).find_each{ |user| puts user.id }

</code></pre>
<p>The above code still prints ids of all 20 users, even though the intention was
to limit the records fetched to 10.</p>
<p>Rails 5.1
<a href="https://github.com/rails/rails/commit/451437c6f57e66cc7586ec966e530493927098c7">has added support</a>
to limit the records in batch processing.</p>
<pre><code class="language-ruby">
 User.limit(10).find_each{ |user| puts user.id }

</code></pre>
<p>The above code will print only 10 ids in Rails 5.1.</p>
<p>We can make use of limit in <code>find_in_batches</code> and <code>in_batches</code> as well.</p>
<pre><code class="language-ruby">
 total_count = 0

 User.limit(10).find_in_batches(batch_size: 4) do |batch|
   total_count += batch.count
 end

 total_count
#=&gt; 10

</code></pre>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 doesn't share thread_mattr_accessor variable]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-does-not-share-thread-mattr-accessor-variable-with-sub-class"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-does-not-share-thread-mattr-accessor-variable-with-sub-class.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-does-not-share-thread-mattr-accessor-variable-with-sub-class</id>
      <published>2017-05-16T00:00:00.000Z</published>
      <updated>2017-05-16T00:00:00.000Z</updated>
      <author>
        <name>Mohit Natoo</name>
        <uri>https://www.bigbinary.com/blog/authors/mohit</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-does-not-share-thread-mattr-accessor-variable-with-sub-class.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 now does not share the variable defined by thread_mattr_accessor with subclass.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-does-not-share-thread-mattr-accessor-variable-with-sub-class"><![CDATA[<p>Rails 5.0 provides
<a href="https://www.bigbinary.com/blog/rails-5-adds-ability-to-create-module-and-class-level-variables-on-per-thread-basis">mattr_accessor</a>
to define class level variables on a per thread basis.</p>
<p>However, the variable was getting shared with child classes as well. That meant
when a child class changed value of the variable, then its effect was seen in
the parent class.</p>
<pre><code class="language-ruby">
class Player
  thread_mattr_accessor :alias
end

class PowerPlayer &lt; Player
end

Player.alias = 'Gunner'
PowerPlayer.alias = 'Bomber'

&gt; PowerPlayer.alias
#=&gt; &quot;Bomber&quot;

&gt; Player.alias
#=&gt; &quot;Bomber&quot;

</code></pre>
<p>This isn't the intended behavior as per OOPS norms.</p>
<p>In Rails 5.1
<a href="https://github.com/rails/rails/pull/25681">this problem was resolved</a>. Now a
change in value of <code>thread_mattr_accessor</code> in child class will not affect value
in its parent class.</p>
<pre><code class="language-ruby">
class Player
  thread_mattr_accessor :alias
end

class PowerPlayer &lt; Player
end

Player.alias = 'Gunner'
PowerPlayer.alias = 'Bomber'

&gt; PowerPlayer.alias
#=&gt; &quot;Bomber&quot;

&gt; Player.alias
#=&gt; &quot;Gunner&quot;

</code></pre>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 introduced assert_changes and assert_no_changes]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-introduced-assert_changes-and-assert_no_changes"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-introduced-assert_changes-and-assert_no_changes.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-introduced-assert_changes-and-assert_no_changes</id>
      <published>2017-05-09T00:00:00.000Z</published>
      <updated>2017-05-09T00:00:00.000Z</updated>
      <author>
        <name>Narendra Rajput</name>
        <uri>https://www.bigbinary.com/blog/authors/bknarendra</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-introduced-assert_changes-and-assert_no_changes.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[The BigBinary team's lesson on introduced assert_changes and assert_no_changes in Rails 5.1]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-introduced-assert_changes-and-assert_no_changes"><![CDATA[<p>Rails 5.1 has introduced
<a href="http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes">assert_changes</a>
and
<a href="http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes">assert_no_changes</a>.
It can be seen as a more generic version of
<a href="http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference">assert_difference</a>
and
<a href="http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference">assert_no_difference</a>.</p>
<h3>assert_changes</h3>
<p><code>assert_changes</code> asserts the value of an expression is changed before and after
invoking the block. The specified expression can be string like
<code>assert_difference</code>.</p>
<pre><code class="language-ruby">
@user = users(:john)
assert_changes 'users(:john).status' do
  post :update, params: {id: @user.id, user: {status: 'online'}}
end

</code></pre>
<p>We can also pass a lambda as an expression.</p>
<pre><code class="language-ruby">
@user = users(:john)
assert_changes -&gt; {users(:john).status} do
  post :update, params: {id: @user.id, user: {status: 'online'}}
end

</code></pre>
<p><code>assert_changes</code> also allows options <code>:from</code> and <code>:to</code> to specify initial and
final state of expression.</p>
<pre><code class="language-ruby">
@light = Light.new
assert_changes -&gt; { @light.status }, from: 'off', to: 'on' do
  @light.turn_on
end

</code></pre>
<p>We can also specify test failure message.</p>
<pre><code class="language-ruby">
@invoice = invoices(:bb_client)
assert_changes -&gt; { @invoice.status }, to: 'paid', 'Expected the invoice to be marked paid' do
  @invoice.make_payment
end

</code></pre>
<h3>assert_no_changes</h3>
<p><code>assert_no_changes</code> has same options and asserts that the expression doesn't
change before and after invoking the block.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Forward ActiveRecord::Relation#count to Enumerable#count]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/forwarding-active-record-relation-count-to-enumerable-count"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/forwarding-active-record-relation-count-to-enumerable-count.png"/>
      <id>https://www.bigbinary.com/blog/forwarding-active-record-relation-count-to-enumerable-count</id>
      <published>2017-05-01T00:00:00.000Z</published>
      <updated>2017-05-01T00:00:00.000Z</updated>
      <author>
        <name>Rohit Arolkar</name>
        <uri>https://www.bigbinary.com/blog/authors/rohitakshar</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/forwarding-active-record-relation-count-to-enumerable-count.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Forward ActiveRecord::Relation#count to Enumerable#count if block given]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/forwarding-active-record-relation-count-to-enumerable-count"><![CDATA[<p>Let's say that we want to know all the deliveries in progress for an order.</p>
<p>The following code would do the job.</p>
<pre><code class="language-ruby">
class Order
  has_many :deliveries

  def num_deliveries_in_progress
    deliveries.select { |delivery| delivery.in_progress? }.size
  end

end

</code></pre>
<p>But usage of <code>count</code> should make more sense over a <code>select</code>, right?</p>
<pre><code class="language-ruby">
class Order
  has_many :deliveries

  def num_deliveries_in_progress
    deliveries.count { |delivery| delivery.in_progress? }
  end

end

</code></pre>
<p>However the changed code would return count for all the order deliveries, rather
than returning only the ones in progress.</p>
<p>That's because <code>ActiveRecord::Relation#count</code> silently discards the block
argument.</p>
<p>Rails 5.1
<a href="https://github.com/rails/rails/pull/24203/files#diff-e0e70620d0897d6819a6bcc2b5ee7a73">fixed this issue</a>.</p>
<pre><code class="language-ruby">
module ActiveRecord
  module Calculations

    def count(column_name = nil)
      if block_given?
        to_a.count { |*block_args| yield(*block_args) }
      else
        calculate(:count, column_name)
      end
    end

  end
end

</code></pre>
<p>So now, we can pass a block to <code>count</code> method.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 5.1 has introduced Date#all_day helper]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-5-1-has-introduced-date-all_day-helper"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-has-introduced-date-all_day-helper.png"/>
      <id>https://www.bigbinary.com/blog/rails-5-1-has-introduced-date-all_day-helper</id>
      <published>2017-04-24T00:00:00.000Z</published>
      <updated>2017-04-24T00:00:00.000Z</updated>
      <author>
        <name>Prathamesh Sonpatki</name>
        <uri>https://www.bigbinary.com/blog/authors/prathamesh</uri>
      </author>
      <category term="Rails 5.1"/>
      <category term="Rails"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-5-1-has-introduced-date-all_day-helper.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.1 has introduced a helper method for creating a range object covering the whole day for given date]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-5-1-has-introduced-date-all_day-helper"><![CDATA[<p>Sometimes, we want to query records over the whole day for a given date.</p>
<pre><code class="language-ruby">&gt;&gt; User.where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)

=&gt; SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE (&quot;users&quot;.&quot;created_at&quot; BETWEEN $1 AND $2) [[&quot;created_at&quot;, 2017-04-09 00:00:00 UTC], [&quot;created_at&quot;, 2017-04-09 23:59:59 UTC]]
</code></pre>
<p>Rails 5.1 has
<a href="https://github.com/rails/rails/pull/24930">introduced a helper method</a> for
creating this range object for a given date in the form of <code>Date#all_day</code>.</p>
<pre><code class="language-ruby">&gt;&gt; User.where(created_at: Date.today.all_day)

=&gt; SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE (&quot;users&quot;.&quot;created_at&quot; BETWEEN $1 AND $2) [[&quot;created_at&quot;, 2017-04-09 00:00:00 UTC], [&quot;created_at&quot;, 2017-04-09 23:59:59 UTC]]
</code></pre>
<p>We can confirm that the <code>Date#all_day</code> method returns the range object for a
given date.</p>
<pre><code class="language-ruby">&gt;&gt; Date.today.all_day

=&gt; Sun, 09 Apr 2017 00:00:00 UTC +00:00..Sun, 09 Apr 2017 23:59:59 UTC +00:00
</code></pre>
]]></content>
    </entry>
</feed>