<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by chebyte on Medium]]></title>
        <description><![CDATA[Stories by chebyte on Medium]]></description>
        <link>https://medium.com/@chebyte?source=rss-54f6b3f1d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bHhGQzb4VNDYSsH4.</url>
            <title>Stories by chebyte on Medium</title>
            <link>https://medium.com/@chebyte?source=rss-54f6b3f1d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:19:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chebyte/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[New releases of dry-types and dry-validation]]></title>
            <link>https://medium.com/hashdog-blog/new-releases-of-dry-types-and-dry-validation-170a52f24fe4?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/170a52f24fe4</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 31 Mar 2016 00:00:00 GMT</pubDate>
            <atom:updated>2016-03-31T15:55:11.283Z</atom:updated>
            <content:encoded><![CDATA[<p>What a busy week! New versions of <a href="http://dry-rb.org/gems/dry-types">dry-types</a> and <a href="http://dry-rb.org/gems/dry-types">dry-validation</a> have been released and there are really exciting new features awaiting for you. We’re also very excited to see <a href="http://trailblazer.to/">Trailblazer</a> adopting some dry-rb libraries — Reform will soon support latest dry-validation, and Disposable has already replaced Virtus with dry-types for its coercion functionality.</p><h3>New dry-validation features</h3><p>The major highlight of the new 0.7.3 dry-validation release is improved integration with dry-types, a feature that we haven’t revealed until now. Both dry-validation and dry-types are based on the same foundational library called dry-logic. Validation rules and type constraints are handled by dry-logic, which means we can use constrained types to share common constraints between type definitions and validation schemas to reduce information duplication. This will DRY-up your code (see what I did there?).</p><p>Here’s what it means in practice:</p><pre>require &#39;dry-validation&#39; require &#39;dry-types&#39; module Types include Dry::Types.module Age = Strict::Int.constrained(gt: 18) end UserSchema = Dry::Validation.Form do key(:name).required key(:age).required(Types::Age) end UserSchema.(name: &#39;Jane&#39;, age: 17).messages # { age: [&quot;must be greater than 18&quot;] }</pre><p>This way you can encapsulate important constraints and completely avoid duplication.</p><p>We are not stopping here!</p><h3>Custom constructor types!</h3><p>Another fantastic improvement is support for custom constructor types in validation schemas. You can now define types that can encapsulate custom coercion logic and dry-validation will infer an input processor from it and apply it to the input data before validation.</p><p>Simple example:</p><pre>require &#39;dry-validation&#39; require &#39;dry-types&#39; module Types include Dry::Types.module module DataImport StrippedString = Strict::String.constructor { |value| value.to_s.strip } end end UserImport = Dry::Validation.Schema do configure { config.input_processor = :sanitizer } key(:name).required(Types::DataImport::StrippedString) key(:email).required(Types::DataImport::StrippedString) end UserSchema.(name: &#39; Jane &#39;, email: &#39;jane@doe.org &#39;).to_h # { name: &quot;Jane&quot;, email: &quot;jane@doe.org&quot; }</pre><p>This is a clean way of encapsulating custom coercion or sanitization logic. Notice that your type objects are small and reusable. You can also use them manually anywhere in your application, e.g. Types::DataImport::StrippedString[“ foo “] # =&gt; “foo”.</p><p>dry-validation infers both validation rules and value constructors from your types, notice that Types::DataImport::StrippedString is a strict string, which means a proper validation rule is set too:</p><pre>UserSchema.(name: &#39; Jane &#39;, email: nil).messages # { email: [&quot;must be filled&quot;, &quot;must be String&quot;] }</pre><h3>Applying external schemas conditionally</h3><p>When defining a high-level rule, you can now delegate validation to an external schema. Why would you want to do that? Let’s say you have a nested data structure, and parts of that structure should be validated using different schemas based on other values from that data structure. In example:</p><pre>CreateCommandSchema = Dry::Validation.Schema do key(:name).required key(:email).required end UpdateCommandSchema = Dry::Validation.Schema do key(:id).required(:int?) key(:data).schema(CreateCommandSchema) end CommandSchema = Dry::Validation.Schema do key(:command).maybe(:str?, :inclusion?: %w(Create Update)) key(:args).maybe(:hash?) rule(create_command: [:command, :args]) do |command, args| command.eql?(&#39;Create&#39;).then(args.schema(CreateCommandSchema)) end rule(update_command: [:command, :args]) do |command, args| command.eql?(&#39;Update&#39;).then(args.schema(UpdateCommandSchema)) end end CommandSchema.(command: &#39;Oops&#39;).messages.inspect # { command: [&quot;must be one of: Create, Update&quot;], args: [&quot;is missing&quot;] } CommandSchema.( command: &#39;Create&#39;, args: { name: &#39;Jane&#39;, email: nil } ).messages # { args: { email: [&quot;must be filled&quot;] } } CommandSchema.( command: &#39;Update&#39;, args: { id: 1, data: { name: nil, email: &#39;jane@doe.org&#39; } } ).messages # { data: { name: [&quot;must be filled&quot;] } }</pre><p>Notice that our high-level rules explicitly define which values they rely on. It means we don’t have to worry about validation rules from external schemas crashing due to invalid state. If args is nil, nothing will crash. Furthermore, if command is not one of the allowed values, we won’t even bother trying to apply external schemas.</p><h3>New predicate: :number?</h3><p>You can now specify that a value must be a number, in case of Form schemas a proper coercion is applied:</p><pre>UserSchema = Dry::Validation.Form do key(:age).required(:number?, :int?) end UserSchema.(age: &#39;1&#39;).to_h # { age: 1 } UserSchema.(age: &#39;one&#39;).messages # { age: [&quot;must be a number&quot;] } UserSchema.(age: &#39;1.5&#39;).messages # { age: [&quot;must be an integer&quot;] }</pre><h3>New dry-types features</h3><p>dry-types 0.7.0 focused on improving support for complex types and better exception messages. You can now specify complex types, like arrays or hashes, along with constraints.</p><p>Let’s say you want to specify Options type which is an array with either strings or string pairs inside nested arrays:</p><pre>require &#39;dry-types&#39; module Types include Dry::Types.module StringList = Strict::Array.member(Strict::String) StringPair = Strict::Array.member(Strict::String).constrained(size: 2) StringPairs = Strict::Array.member(StringPair) Options = StringList | StringPairs end Types::Options.call([&quot;one&quot;, &quot;two&quot;]) # [&quot;one&quot;, &quot;two&quot;] Types::Options.call([[&quot;a&quot;, &quot;one&quot;], [&quot;b&quot;, &quot;two&quot;]]) # [[&quot;a&quot;, &quot;one&quot;], [&quot;b&quot;, &quot;two&quot;]] Types::Options.call([&quot;one&quot;, nil]) # Dry::Types::ConstraintError Types::Options.call([[&quot;a&quot;, &quot;one&quot;], [&quot;b&quot;]]) # Dry::Types::ConstraintError</pre><p>Exception messages have been improved too; however, they’re still a work in progress, and complex types like in the previous example still need some work.</p><p>Here’s what you’d get if a simple constraint was violated:</p><pre>Password = Types::Strict::String.constrained(size: 10) Password[&quot;foo&quot;] # Dry::Types::ConstraintError: &quot;foo&quot; violates constraints (size?(10) failed)</pre><h3>Enjoy!</h3><p>We hope you’ll find new features useful. In case of any issues, please report them on GitHub or chat with us on <a href="https://gitter.im/dry-rb/chat">Gitter</a>.</p><p>If you want to use new features, just add latest versions to your Gemfile:</p><pre>gem &quot;dry-types&quot;, &quot;~&gt; 0.7.0&quot; gem &quot;dry-validation&quot;, &quot;~&gt; 0.7.3&quot;</pre><p>Detailed CHANGELOGs:</p><ul><li>dry-validation <a href="https://github.com/dry-rb/dry-validation/blob/master/CHANGELOG.md#v072-2016-03-28">v0.7.2</a> and quick follow-up <a href="https://github.com/dry-rb/dry-validation/blob/master/CHANGELOG.md#v073-2016-03-30">v0.7.3</a></li><li>dry-types <a href="https://github.com/dry-rb/dry-types/blob/master/CHANGELOG.md#v070-2016-03-30">v0.7.0</a></li></ul><p><em>Originally published at </em><a href="http://dry-rb.org/news/2016/03/31/new-releases-of-dry-types-and-dry-validation/"><em>dry-rb.org</em></a><em> on March 31, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=170a52f24fe4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/new-releases-of-dry-types-and-dry-validation-170a52f24fe4">New releases of dry-types and dry-validation</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Facts Why Developers Must Try Ruby on Rails]]></title>
            <link>https://medium.com/@chebyte/10-facts-why-developers-must-try-ruby-on-rails-c46bb6966b4c?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46bb6966b4c</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Tue, 29 Mar 2016 00:00:00 GMT</pubDate>
            <atom:updated>2016-03-31T15:55:51.201Z</atom:updated>
            <content:encoded><![CDATA[<p>The latest of the frameworks for designing any application is Ruby on Rails. The emerging Ruby on Rails has many interesting features that attract developers to try this framework for designing web applications. Many of the developers want to know if they should learn Ruby on Rails or not. Here is the ultimate guide featuring 10 interesting facts that will convince the developers to must try it. “Rails” has developed this written in the Ruby language that is the most flexible and can be used in effective manner.</p><ol><li><strong>Ruby on Rails is a Framework</strong></li></ol><p>It is written in Ruby that is the flexible and user friendly language and helps to build website application. This is the framework and not the language. It is really easy and simple to use framework in developing.</p><ol><li><strong>It is the beginners friendly</strong></li></ol><p>Ruby on Rails is the best framework for the beginners. It is very much easier than the other due to Ruby language that is friendly and forgiving. Beginners can enjoy developing web applications with Ruby on Rails. Beginners can avoid working hard when they have Ruby on Rails.</p><ol><li><strong>It saves you from writing complex code</strong></li></ol><p>The language used in this framework is really easy and friendly that you can avoid writing complicated codes. It saves you from writing complicated and complex codes while developing apps.</p><ol><li><strong>Save times and develop apps fast</strong></li></ol><p>You can build the apps in less time than other frameworks and techniques. It is possible due to less coding required and really being user friendly. Developers can build apps fast and in less time.</p><ol><li><strong>Startups are using Ruby on Rails</strong></li></ol><p>Ruby on rails is an emerging framework getting fame day by day and due to its friendly nature startups and ecommerce are specifically using this framework that will create opportunities for the learners of Ruby on Rails.</p><ol><li><strong>Hides the stuff you don’t need to know</strong></li></ol><p>Another benefit that Ruby on Rails learners can get is that it hides the extra stuff that you are not required. Developers will not need to know SQL in Ruby on Rails. This is best of the beginners when there is no need to give detailed attention to the customization. It also has free security stuff for you.</p><p>Ruby on rails covers both front end and back end while most of the languages do not have this feature. Another amazing thing is that as you finish learning ruby on rails you will have learnt a bit of HTML, CSS and JavaScript also.</p><ol><li><strong>It won’t let you bore while developing complex apps</strong></li></ol><p>If you are bored to learn and use complex languages and coding you must try ruby on rails. Now you can build complex websites and applications that involves database with ruby on rails.</p><ol><li><strong>You can build your personal website with Ruby on Rails</strong></li></ol><p>Ruby on rails is the most effective framework to build websites and apps fast. Beginners can easily build their personal website with this. It is the valuable tool to startup.</p><ol><li><strong>Some of the world’s biggest sites are build on Ruby on Rails</strong></li></ol><p>It will be surprising to know that some of the world’s biggest sites are built on ruby on rails. These includes Fab.com, Hulu.com, Kickstarter.com, Pitchfork, Basecamp, Scribd, Soundcloud, Shopify, Crunchbase, Slideshare, Funny or die and others.</p><p><em>Originally published at </em><a href="http://www.seaniea.com/10-facts-why-developers-must-try-ruby-on-rails/"><em>www.seaniea.com</em></a><em> on March 29, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46bb6966b4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 8 tools for Ruby on Rails code optimization and cleanup]]></title>
            <link>https://medium.com/hashdog-blog/top-8-tools-for-ruby-on-rails-code-optimization-and-cleanup-f926e15b77fb?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f926e15b77fb</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 10 Mar 2016 14:02:30 GMT</pubDate>
            <atom:updated>2016-03-10T14:02:30.198Z</atom:updated>
            <content:encoded><![CDATA[<p>For most people, <a href="http://en.wikipedia.org/wiki/Dead_code">dead</a>/inefficient code will build up over time. Others will find themselves in a similar predicament when they take over someone else’s project.</p><p>Actually, my own experience with code cleaning/polishing gems stems from having to optimize someone else’s Rails application. Considering its size and complexity, manual code refactoring was bound to be tedious and time consuming, so I decided to help myself as much I could with third-party tools.</p><p>If you want to keep your code maintainable, secure and optimized, take a look at some gems that have been doing the job for me:</p><h3>1. <a href="https://github.com/amatsuda/traceroute">traceroute</a></h3><p>Traceroute is a route cleaning tool for Rails applications. It provides a simple rake task for checking which routes are mapped to non existing controller actions, and finds out which controller actions are not reachable.</p><p>You will also be required to keep your controller helper methods and various before/after filters private, since they shouldn’t be a part of the public API. It sometimes has problems with showing false positives on mountable engines, but they can be easily overlooked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*Fhd1lTSepwsjrWJs." /></figure><h3>2. <a href="https://github.com/MiniProfiler/rack-mini-profiler">rack-mini-profiler</a></h3><p>This is a nice tool used for finding bottlenecks of your applications. It does a live speed analysis of how long it took for the request to be processed and how much of that time it was doing various renderings, database queries and DOM loading. Just plug it into your Gemfile and you’ll get a small window in the upper left corner of your page, showing you all of these information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*yZ3QW2689FD4qfEe." /></figure><h3>3. <a href="https://github.com/flyerhzm/bullet">Bullet</a></h3><p>This one particularly blew my mind. The bullet gem helps you kill all the N+1 queries, as well as unnecessarily eager loaded relations. Once you install it and start visiting various routes in development, alert boxes with warnings indicating database queries that need to be optimized will pop out. It works right out of the box and is extremely helpful for optimizing your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*n8cm-BtOd5R5aUqw." /></figure><h3>4. <a href="https://github.com/presidentbeef/brakeman">brakeman</a></h3><p>A security analysis tool for your Rails applications. It scans through your application and outputs a nicely formatted table of possible vulnerabilities. Security warnings are grouped according to their severity (High, Medium and Low). You can learn more about their meanings on <a href="http://brakemanscanner.org/docs/warning_types/">brakeman’s list of warnings</a>.</p><p>Note that even if you end up not having any warnings, it doesn’t mean that your app is secure, since brakeman sometimes overlooks some basic security pitfalls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PskYcsGs8nW_L3Sm." /></figure><p>Security-wise, there is also a gem called <a href="https://github.com/rubysec/bundler-audit#readme">bundler-audit</a>, used for checking vulnerable versions of gems in your Gemfile.lock.</p><h3>5. <a href="https://github.com/aanand/deadweight">deadweight</a></h3><p>Deadweight is used for cleaning unused CSS selectors. You have to hand out a set of your application’s style sheets and HTML pages, and it will report which CSS selectors are safe to remove.</p><p>The gem won’t work out of the box in Rails, since most pages have dynamic content, but Jason Morrison from Thoughtbot wrote a <a href="http://robots.thoughtbot.com/use-deadweight-and-your-integration-suite-to">blog post</a> on how to create a Rack Middleware and integrate it into your test suite to collect all the HTML content in one place.</p><p>If you’re using precompilers such as Sass or Less, you should compile all of your style sheets and hand them out as simple CSS files to the deadweight task. It is recommended that you remove all the vendor/third-party css files (such as Bootstrap files and similar) since they will end up clogging your output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*WWasi0qmOHDtKk8C." /></figure><h3>6. <a href="https://github.com/railsbp/rails_best_practices">rails best practices</a></h3><p>Static code analyzer for finding Rails specific <a href="http://en.wikipedia.org/wiki/Code_smell">code smells</a>. It offers a variety of suggestions; use scope access, restrict auto-generated routes, add database indexes, etc. For a full list of suggestions, check out the <a href="http://rails-bestpractices.com/posts?nav=vote_points&amp;order=desc">rails-best-pratices official page</a>. Unfortunately, sometimes it reports lots of false positives, such as unused methods. Nevertheless, it contains lots of nice suggestions that will give you a better perspective on how to refactor your code and learn some best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*lE0v_vANChR3bQzM." /></figure><p>If you like the suggestions that rails best practices gives, you also might find <a href="http://robots.thoughtbot.com/sandi-metz-rules-for-developers">Sandi Metz’s rules for developers</a> quite interesting. You can check if your code complies to Sandi’s standards with the <a href="https://github.com/makaroni4/sandi_meter">sandi_meter</a> gem.</p><h3>7. <a href="https://github.com/bbatsov/rubocop#cops">rubocop</a></h3><p>A Ruby static code analyzer which you can use to check if your code complies with the <a href="https://github.com/bbatsov/ruby-style-guide">Ruby community code guidelines</a>. The gem reports style violations through the command line, with lots of useful code refactoring goodies such as <em>useless variable assignment</em>, <em>redundant use of Object#to_s in interpolation</em> or even <em>unused method argument</em>.</p><p>A good thing is that it’s highly configurable, since the analyzer can be quite irritating if you’re not following the Ruby style guide 100% (i.e. you have lots of trailing whitespaces or you double quote your strings even when not interpolating, etc.).</p><p>It’s divided into 4 sub-analyzers (called cops): Style, Lint, Metrics and Rails. You can define which cops to use, as well as which files to exclude/include and tweak various other configuration options in a .rubocop.yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*O4zB8TU4LKWA-ISJ." /></figure><h3>8. <a href="https://github.com/whitesmith/rubycritic">rubycritic</a></h3><p>A relatively new gem that wraps around three static analysis gems — <a href="https://github.com/troessner/reek">Reek</a> (ruby code smells), <a href="https://github.com/seattlerb/flay">Flay</a> (code duplication detection) and <a href="https://github.com/seattlerb/flog">Flog</a> (ABC metrics). It creates nicely structured HTML files so you can browse through your smelly code and start refactoring. Out of all of the mentioned static code analysis tools, because of it’s nice output, it’s most convenient to overview and comment with your colleagues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*gyYYVFNrhtXKFqtK." /></figure><h3>Conclusion</h3><p>If you’re working on an open source project or can afford to automate the process of running all of these static code analyzers on every commit, I would suggest using the <a href="https://codeclimate.com/">code climate</a> service. In case you decide to go down this route, I suggest reading <a href="https://www.infinum.co/the-capsized-eight/articles/a-ruby-on-rails-continous-integration-process-using-semaphore-github-codeclimate-and-hipchat">“A Ruby on Rails Continuous Integration process using Github, Semaphore, CodeClimate and HipChat”</a>, a blog post written by my colleague, Jan Varljen.</p><p>Most of the functionalities that the listed static code analyzers can offer you is already wrapped inside it. Besides code quality reports, there is an optional code coverage report (basically what <a href="https://github.com/colszowka/simplecov">simplecov</a> does).</p><p>One thing to note is that you shouldn’t take each warning issued by these static code analyzers too seriously. Most of them will throw lots of stuff at you that you will probably never refactor because it will take you forever, and for some you just shouldn’t care (such as final newline missing or spruceing up your auto generated schema.rb). Sometimes they can generate lots of rubbish, but that can be prevented by doing code reviews on a regular basis and by tweaking their configuration options.</p><p><em>Originally published at </em><a href="https://infinum.co/the-capsized-eight/articles/top-8-tools-for-ruby-on-rails-code-optimization-and-cleanup"><em>infinum.co</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f926e15b77fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/top-8-tools-for-ruby-on-rails-code-optimization-and-cleanup-f926e15b77fb">Top 8 tools for Ruby on Rails code optimization and cleanup</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Onwards to Rails 5: Additions, Changes, and Deprecations]]></title>
            <link>https://medium.com/hashdog-blog/onwards-to-rails-5-additions-changes-and-deprecations-127804b4c19?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/127804b4c19</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[hashdog]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 10 Mar 2016 07:00:37 GMT</pubDate>
            <atom:updated>2016-03-15T13:36:01.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_78-GjI7in6FrgX3.jpg" /></figure><p>Rails 5, a new major release of the popular web framework, is <a href="http://weblog.rubyonrails.org/2015/12/18/Rails-5-0-beta1/">coming soon</a> and, of course, we are looking forward to it. Refer to <a href="http://www.sitepoint.com/whats-new-rails-5/">this article</a> if you want to read on overview of some new features that will be introduced. Today, however, we are going to dig into some technical details, discuss which methods were removed or deprecated, which settings have been changed, and how to migrate your existing Rails 4 application to version 5.</p><p>Don’t forget that after the release of Rails 5, all bug fixes will only be introduced for Rails 5.0.x, whereas regular security fixes will be applied to Rails 4.2.x, as stated in the <a href="http://guides.rubyonrails.org/maintenance_policy.html">official maintenance policy</a>.</p><p>The source code for this app is available at <a href="https://github.com/bodrovis/Sitepoint-source/tree/master/Rails5_Migration">GitHub</a>.</p><h3>Preparations</h3><p>The first thing to take into consideration before proceeding is that Rails 5 requires Ruby 2.2.2 or higher, so if you don’t have this version installed, go ahead and <a href="https://www.ruby-lang.org/en/downloads/">download it now</a>.</p><p>Before migrating your existing application to Rails 5, I really recommend you having a solid test suite, otherwise the migration process may become much more complex and painful. For this article I will be using a demo application, called MusicalShop, that was introduced in my screencast series <a href="https://www.sitepoint.com/premium/series/rspec">RSpec with Rails</a>. This is a very simple Rails 4 app, but it does have automated tests written in RSpec. You can clone the latest version of the app from <a href="https://github.com/learnable-content/RSpec-collection/tree/features">this branch</a>.</p><p>Also it is advised to migrate to the latest patch version of Rails 4 (which is currently 4.2.5.1). Additionally, you may check that the latest possible versions of gems are used in your project by running</p><pre>$ bundle outdated</pre><p>Be careful, though, not to introduce any conflicts by explicitly requiring the latest versions for all your gems (especially for dependencies).</p><p>Another thing to consider is some gems may not yet be compatible with Rails 5, so be prepared for that. Browse gem’s dependencies and skim through open issues on GitHub to find out whether other developers are facing problems while using the library with Rails 5. Some gems (like Devise, for example) may need to be included directly from the master branch.</p><p>Okay, so go ahead and check that the tests are running successfully:</p><pre>$ rspec .</pre><p>Don’t forget that, as Edsger Dijkstra said, “testing can never demonstrate the absence of errors in software, only their presence”. But we’ll hope for the best.</p><p>The last thing to do is to switch to another branch so that you can always return to an older version if things don’t go as planned:</p><pre>$ git checkout -b rails5</pre><h3>Migrating</h3><p>Take a deep breath and modify your <em>Gemfile</em>:</p><p><em>Gemfile</em></p><pre>[...] gem &#39;rails&#39;, &#39;&gt;= 5.0.0.beta3&#39;, &#39;&lt; 5.1&#39; [...]</pre><p>Currently Rails is in beta, but a release candidate should be published pretty soon.</p><p>Run</p><pre>$ bundle update</pre><p>You may also run</p><pre>$ rake rails:update</pre><p>which creates the new files introduced in Rails 5, as well as, modifies the old ones.</p><p>All in all, Rails 5 configuration files are very similar to Rails 4, so chances are that you’ll be able to boot your app right away while seeing some deprecation messages. Some of you may remember that the migration process from Rails 3 to 4 was much more painful.</p><p>Still, many deprecated methods <a href="https://github.com/rails/rails/pull/18325">were removed</a>, so if you were using any of them, you’ll have to modify the code base accordingly. Let’s discuss the major changes so that you understand which parts of the app will most require your attention.</p><h3>Controllers</h3><p>Okay, first of all, let’s observe changes that relate to controllers.</p><ul><li>The skip_action_callback method is <a href="https://github.com/rails/rails/pull/19060">removed completely</a>.</li><li>The :nothing option for the render method is <a href="https://github.com/vngrs/rails/commit/44781b6e9790d90b4f8b9a41d2b2c114b1a582ee">deprecated</a>.</li><li>The *_filter methods (before_filter, for example) are still supported, but <a href="https://github.com/rails/rails/commit/7644a99">deprecated</a> and will be removed in Rails 5.1. Use *_action instead.</li><li>A nice method redirect_back is being introduced in favor of redirect_to :back. It tries to redirect to an HTTP_REFERER or to the provided location, so you may use it inside your methods:</li></ul><pre>redirect_back root_path</pre><ul><li>render :text is deprecated, as it does not render a text/plain response. Use render :plain instead or render :html to display a text/html page:</li></ul><pre>render plain: &#39;My text&#39;</pre><h3>Views</h3><p>Every form now has its own CSRF token <a href="https://github.com/rails/rails/pull/22275">by default</a>. This is to prevent form hijacking when an attacker injects his own form on the page pointing to some malicious website.</p><p>Create an initializer file to control this behavior globally:</p><p><em>config/initializers/per_form_csrf_tokens.rb</em></p><pre>Rails.application.config.action_controller.per_form_csrf_tokens = true</pre><p>Or use the following setting inside individual controllers:</p><pre>self.per_form_csrf_tokens = true</pre><p>content_tag_for and div_for methods <a href="https://github.com/rails/rails/pull/18411">were removed</a> from ActionView and extracted to the <a href="https://github.com/rails/record_tag_helper">record<em>tag</em>helper gem</a>.</p><h3>Models</h3><p>Rails 5 introduces a new abstract class (meaning, that it cannot be instantiated) called ApplicationRecord and all models inherit from it by default rather than from ActiveRecord::Base. This is done to prevent monkey-patching ActiveRecord::Base directly. So, you can introduce all extensions inside ApplicationRecord. If you want to employ this functionality, create <strong>application_record.rb</strong> file inside your <strong>models</strong> directory:</p><p><em>models/application_record.rb</em></p><pre>class ApplicationRecord &lt; ActiveRecord::Base self.abstract_class = true end</pre><p>Next ensure that all models inherit from this new class, for example:</p><p><em>models/user.rb</em></p><pre>class User &lt; ApplicationRecord [...] end</pre><p>Another addition is related to belongs_to associations: in Rails 5, the associated record must be present by default. The required option is now <a href="https://github.com/rails/rails/pull/18937">deprecated</a> and a new optional parameter is being introduced. This means that, by default, Rails validates that the “parent” record is present before saving the object. If you do not wish to employ this behavior for some association, use</p><pre>belongs_to :some_parent, optional: true</pre><p>Rails 5 also comes with a <strong>active<em>record</em>belongs<em>to</em>required<em>by</em>default.rb</strong> initializer file that controls this behavior for the whole application. You may create it as well:</p><p><em>config/initializers/active_record_belongs_to_required_by_default.rb</em></p><pre>Rails.application.config.active_record.belongs_to_required_by_default = true</pre><p>before_* callbacks that return false inside your models do not halt the callback chain <a href="https://github.com/rails/rails/pull/17227">anymore</a>. If you wish to explicitly halt the callback chain, use throw(:abort) instead:</p><pre>def my_callback throw(:abort) if something_bad_happened end</pre><p>New Rails 5 apps comes with a <strong>callback_terminator.rb</strong> initializer file that controls this behavior:</p><p><em>config/inititalizers/callback_terminator.rb</em></p><pre>ActiveSupport.halt_callback_chains_on_return_false = false</pre><p>Another important thing to remember is that Rails 5 only works with <a href="https://github.com/rails/rails/pull/23434">PostgreSQL 9.1 and above</a>.</p><h3>Cache</h3><p>Caching management in development was made more convenient. In Rails 4, we used to have the config.action_controller.perform_caching setting that accepts either true or false. In Rails 5, however, the following code snippet is now present:</p><p><em>config/environments/development.rb</em></p><pre>[...] if Rails.root.join(&#39;tmp/caching-dev.txt&#39;).exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { &#39;Cache-Control&#39; =&gt; &#39;public, max-age=172800&#39; } else config.action_controller.perform_caching = false config.cache_store = :null_store end [...]</pre><p>To enable or disable caching, you <a href="https://github.com/rails/rails/issues/18875">can run</a> the rake dev:cache command that creates <strong>caching-dev.txt</strong> file inside the <strong>tmp</strong> directory.</p><h3>Routing</h3><p>Multiple root routes may exist in the same scope now (previously, an error was raised). You can provide constraints and choose which root to use:</p><pre>root &#39;blog#show&#39;, constraints: -&gt;(req) { some_condition } root &#39;pages#show&#39;</pre><p>The rails routes command <a href="https://github.com/rails/rails/pull/23225">now accepts</a> the following options to<br> search for specific routes:</p><ul><li>-c returns all routes for the specified controller</li><li>-g returns routes based on the specified pattern</li></ul><h3>Tests</h3><p>ActionController::TestCase HTTP request methods like get and post are deprecated. You should use process instead. For example, in my tests I have calls like:</p><p><em>spec/controllers/albums_controller_spec.rb</em></p><pre>[...] get :index [...] post :create, album: {title: &#39;&#39;} [...]</pre><p>These should be re-written as</p><p><em>spec/controllers/albums_controller_spec.rb</em></p><pre>[...] process :index, method: :get [...] process :create, method: :post, params: { album: {title: &#39;&#39;} } [...]</pre><p>The assigns and assert_template methods <a href="https://github.com/rspec/rspec-rails/issues/1393">have been extracted</a> to a separate <a href="https://github.com/rails/rails-controller-testing">rails-controller-testing gem</a>. Add it into your <strong>Gemfile</strong>:</p><p><em>Gemfile</em></p><pre>[...] group :test do gem &#39;rails-controller-testing&#39; end [...]</pre><p>If you are using RSpec like me, add the following lines into your <strong>rails_helper.rb</strong> file as a temporary fix (RSpec does not support Rails 5 officially yet):</p><p><em>spec/rails_helper.rb</em></p><pre>[...] RSpec.configure do |config| config.include Rails::Controller::Testing::TestProcess config.include Rails::Controller::Testing::TemplateAssertions config.include Rails::Controller::Testing::Integration [...] end</pre><h3>Some Other Stuff</h3><p>Another cool feature of Rails 5 is that all rake commands <a href="https://github.com/rails/rails/issues/18878">now live</a> in rails (for example, rake db:migrate becomes rails db:migrate).</p><p>ActiveRecord::Base.raise_in_transactional_callbacks setting is deprecated and has no effect. It will be removed without replacement, so you can safely delete it from <strong>config/application.rb</strong> file.</p><p>ActiveJob <a href="https://github.com/rails/rails/pull/19034">now inherits</a> from an intermediate ApplicationJob class. Create an <strong>application_job.rb</strong> file inside the <strong>jobs</strong> directory:</p><p><em>jobs/application_job.rb</em></p><pre>class ApplicationJob &lt; ActiveJob::Base end</pre><p>Make sure that your jobs inherit from ApplicationJob.</p><p>ActionDispatch::Static <a href="https://github.com/rails/rails/pull/19135">accepts</a> custom HTTP headers, so you may specify custom cache-control options.</p><p>The last thing to note is that ActionCable <a href="http://weblog.rubyonrails.org/2016/2/2/Rails-5-0-beta2/">does not require</a> Redis, EventMachine, and Celluloid to be present anymore.</p><h3>Conclusion</h3><p>So, Rails 5 promises a great set of new features and additions and I really encourage you to give it a try. Also, be sure to browse the <a href="http://weblog.rubyonrails.org/2015/12/18/Rails-5-0-beta1/#a-few-other-highlights">complete changelog</a>.</p><p>Are you planning to migrate to Rails 5 in the nearest future? How many of your apps are still running Rails 3 (or even Rails 2)? Share your opinion in the comments!</p><p><em>Originally published at </em><a href="http://www.sitepoint.com/onwards-to-rails-5-additions-changes-and-deprecations/"><em>www.sitepoint.com</em></a><em> on March 10, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127804b4c19" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/onwards-to-rails-5-additions-changes-and-deprecations-127804b4c19">Onwards to Rails 5: Additions, Changes, and Deprecations</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActiveRecord is reinventing Sequel]]></title>
            <link>https://medium.com/hashdog-blog/activerecord-is-reinventing-sequel-99985a5ebdb6?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/99985a5ebdb6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Mon, 07 Mar 2016 20:11:57 GMT</pubDate>
            <atom:updated>2016-03-07T20:13:42.459Z</atom:updated>
            <content:encoded><![CDATA[<p>For those who don’t know, <a href="http://github.com/jeremyevans/sequel">Sequel</a> is an ORM very similar to ActiveRecord, in a way that it also implements the <a href="http://www.martinfowler.com/eaaCatalog/activeRecord.html">Active Record pattern</a>. As of this writing it’s 9 years old. I’ve already written about why <a href="http://twin.github.io/ode-to-sequel/">Sequel is awesome</a>.</p><p>I’m using Sequel for over a year now, and am finding it to be consistently better than ActiveRecord. But that’s just my opinion, right? You can’t really say that one tool is objectively better than the other, each tool has its tradeoffs.</p><p>Well, sometimes you simply can. What I’ve noticed is that, whenever a new shiny ActiveRecord feature comes, Sequel has already had the same feature for quite some time. That would be ok if these were a few isolated incidents, but they’re really not. ActiveRecord appears to have been consistently reinventing Sequel.</p><p>Wait, that can’t be right. ActiveRecord is insanely popular and it’s part of Rails, the Rails team surely wouldn’t work so hard reimplementing something that already exists. Anyway, that is a huge accusation, how can I possibly prove my claims? Give me a chance, I really do have evidence. A <em>lot</em> of evidence.</p><p>What I will do is walk you through ActiveRecord’s most notable updates, and look for Sequel’s equivalents. I will also compare times when a feature landed on both ORMs. I will list the features roughly in reverse chronological order (from newest to oldest), so that we start from fresh memories.</p><h3>ActiveRecord 5</h3><h3>Or</h3><p>The ActiveRecord::Relation#or query method allows use of the OR operator (previously you’d have to write SQL strings):</p><pre>Post.where(id: 1).or(Post.where(id: 2)) # =&gt; SELECT * FROM posts WHERE (id = 1) OR (id = 2)</pre><p>Implementing this feature required a <a href="https://github.com/rails/rails/pull/9052">lot</a> <a href="https://github.com/rails/rails/pull/18706">of</a> <a href="https://github.com/rails/rails/pull/16052">discussion</a>. The feature finally landed in ActiveRecord (<a href="https://github.com/rails/rails/commit/9e42cf019f2417473e7dcbfcb885709fa2709f89">commit</a>), only <strong>8 years</strong> behind Sequel (<a href="https://github.com/jeremyevans/sequel/blob/305b965a2790675bc920f8d2d1a3bc194e366af4/lib/sequel/dataset/sql.rb#L235">code</a>).</p><h3>Left joins</h3><p>The ActiveRecord::Relation#left_joins query method generates a LEFT OUTER JOIN (previously kind of possible via #eager_load):</p><pre>User.left_joins(:posts) # =&gt; SELECT &quot;users&quot;.* FROM &quot;users&quot; LEFT OUTER JOIN &quot;posts&quot; ON &quot;posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;</pre><p>The feature landed in ActiveRecord in 2015 (<a href="https://github.com/rails/rails/pull/12071">PR</a>). On the other hand, Sequel has had support for all types of JOINs since <strong>2008</strong>, and added “association joins” in <strong>2014</strong> (<a href="https://github.com/jeremyevans/sequel/commit/8dbec2f404703a0b265763c94af901f6053c22fa">commit</a>).</p><h3>Attributes API</h3><p>The <a href="http://edgeapi.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute">attributes API</a> allows specifying/overriding types of columns/accessors in your models, as well as querying with instances of those types, and bunch of other things. It took Sean Griffin about 1 year to fully implement it.</p><p>It’s difficult to point out at a specific equivalent in Sequel since the area of ActiveRecord’s attributes API is so broad. In my opinion you can roughly achieve the same features with <a href="http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/Serialization.html">serialization</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/SerializationModificationDetection.html">serialization_modification_detection</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/Composition.html">composition</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/TypecastOnLoad.html">typecast_on_load</a>, and <a href="http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/DefaultsSetter.html">defaults_setter</a> plugins.</p><h3>Views</h3><p>The ActiveRecord::ConnectionAdapters::AbstractAdapter#views method defined on connection adapters returns an array of database view names:</p><pre>ActiveRecord::Base.connection.views #=&gt; [&quot;recent_posts&quot;, &quot;popular_posts&quot;, ...]</pre><p>Sequel implemented #views in 2011 (<a href="https://github.com/jeremyevans/sequel/commit/ed27c3856fde5a5e03c4940db50fa93f4d9fd99a">commit</a>), <strong>4 years</strong> before ActiveRecord (<a href="https://github.com/rails/rails/commit/dcd39949f8801cb4beddec37143a585259f09a2d">commit</a>).</p><h3>Indexing Concurrently</h3><p>This PostgreSQL feature is crucial for zero-downtime migrations on larger tables, ActiveRecord has had adding indices concurrently since 2013 (<a href="https://github.com/rails/rails/commit/e199dc1a570d4f0d9a07628268835bce5aab2732">commit</a>), and dropping concurrently since 2015 (<a href="https://github.com/rails/rails/commit/ce17e232a12861bce4bd950d7143df3fe0cd1991">commit</a>).</p><p>Sequel supported both adding and dropping indices concurrently since <strong>2012</strong> (<a href="https://github.com/jeremyevans/sequel/commit/61593033c05f5f52617f0c72bdc63d92a020bfff">commit</a>).</p><h3>In batches</h3><p>ActiveRecord::Relation#in_batches yields batches of relations, suitable for batched updates or deletes:</p><pre>Person.in_batches { |people| people.update_all(awesome: true) }</pre><p>Sequel doesn’t have an equivalent, because there is no one right way to do batched updates, it depends on the situation. For example, the following Sequel implementation in my benchmarks showed to be 2x faster than ActiveRecord’s:</p><pre>(Person.max(:id) / 1000).times do |i| Person.where(id: (i*1000 + 1)..((i+1) * 1000)).update(awesome: true) end</pre><h3>Aborting hooks</h3><p>Before Rails 5, returning false in any before_* callback resulted in halting of callback chain. The new version <a href="https://github.com/rails/rails/pull/17227">removes</a> this behaviour and requires you to be explicit about it:</p><pre>class Person &lt; ActiveRecord::Base before_save do throw(:abort) if some_condition end end</pre><p>This is actually one of the rare cases where Sequel <a href="https://github.com/jeremyevans/sequel/commit/2475df6223b92923dffe0bc4de4eb6bf21eda640">added the equivalent cancel_action method</a> being inspired by ActiveRecord’s change</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*R_DcLS-6-fMsFaLZ.png" /></figure><p>.</p><h3>ActiveRecord 4</h3><h3>Adequate Record</h3><p><a href="https://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html">Adequate Record</a> is a set of performance improvements in ActiveRecord that makes common find and find_by calls and some association queries up to 2x faster. Aaron Patterson worked on Adequate Record for about 3 years.</p><p>However, running the <a href="https://github.com/jeremyevans/simple_orm_benchmark">ORM benchmark</a> shows that Sequel is still much, much faster than ActiveRecord, even after the Adequate Record merge.</p><h3>Postgres JSON, array and hstore</h3><p>ActiveRecord 4 added support for Postgres JSON, array and hstore columns, along with automatic typecasting. From looking at the commits we can say that ActiveRecord received these features roughly at the same time as Sequel (<a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_json_rb.html">pg_json</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_array_rb.html">pg_array</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_hstore_rb.html">pg_hstore</a>), which is around the time these features got added to Postgres. Note that Sequel on top of this also has an API for <em>querying</em> these types of columns (<a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_json_ops_rb.html">pg_json_ops</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_array_ops_rb.html">pg_array_ops</a>, <a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_hstore_ops_rb.html">pg_hstore_ops</a>), which greatly improves readability.</p><h3>Mutation detection</h3><p>ActiveRecord 4.2+ automatically detects in-place changes to columns values, and marks the record as dirty. Sequel added this feature through <a href="https://github.com/jeremyevans/sequel/commit/a9c4e060f436a9084d533c054395746cd8ae6bf1">modification_detection</a> plugin after ActiveRecord. But note that in Sequel this is opt-in, so that users can decide whether they want the performance hit.</p><h3>Where not</h3><p>The where.not query construct allows negating a where clause, eliminating the need to write SQL strings:</p><pre>Person.where.not(name: &quot;John&quot;)</pre><p>It was added in 2012 (<a href="https://github.com/rails/rails/commit/de75af7acc5c05c708443de40e78965925165217">commit</a>), in which time Sequel’s equivalent exclude was existing already for <strong>5 years</strong> (<a href="https://github.com/jeremyevans/sequel/blob/305b965a2790675bc920f8d2d1a3bc194e366af4/lib/sequel/dataset/sql.rb#L263">code</a>).</p><h3>Rewhere</h3><p>In 2013 ActiveRecord::Relation#rewhere was <a href="https://github.com/rails/rails/commit/f950b2699f97749ef706c6939a84dfc85f0b05f2">added</a> allowing you to overwrite all existing WHERE conditions with new ones:</p><pre>Person.where(name: &quot;Mr. Anderson&quot;).rewhere(name: &quot;Neo&quot;)</pre><p>Sequel has had unfiltered, which removes existing WHERE and HAVING conditions, since 2008, <strong>5 years</strong> before this ActiveRecord update (<a href="https://github.com/jeremyevans/sequel/commit/691a5c31a0f64d764a975c4bc563eb8de8b38507">commit</a>).</p><h3>Enum</h3><p>ActiveRecord::Base#enum was added to ActiveRecord 4.1 (<a href="https://github.com/rails/rails/commit/db41eb8a6ea88b854bf5cd11070ea4245e1639c5">commit</a>), giving the ability to map names to integer columns:</p><pre>class Conversation &lt; ActiveRecord::Base enum status: [:active, :archived] end</pre><p>While Sequel doesn’t have this database-agnostic feature, it has the <a href="http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_enum_rb.html">pg_enum</a> plugin for Postgres’ enum type, although it was added only 1 year after ActiveRecord’s enum.</p><h3>Automatic inverse associations</h3><p>ActiveRecord 4.1 added a feature to automatically detect inverse associations, instead of having to always use :inverse_of (<a href="https://github.com/rails/rails/commit/ae6e6d953084d1966e52cc06ffe24131f0115cc1">commit</a>).</p><p>Sequel had this basically since it added associations in 2008, which was about <strong>5 years</strong> before ActiveRecord’s update.</p><h3>Contextual validations</h3><p><a href="https://github.com/rails/rails/commit/50d971710150533562240bef660f14237b70d939">Contextual validations</a> allow passing a symbol when validating, and doing validations depending on the existence or absence of the given symbol.</p><p>Sequel doesn’t have this feature, since it’s a code smell to have this in the model, but Sequel’s <a href="http://sequel.jeremyevans.net/rdoc/files/doc/validations_rdoc.html#label-validation_helpers">instance-level validations</a> allow you to validate records from service objects, which is a much better way of doing contextual validation.</p><h3>Reversibility improvements</h3><p>ActiveRecord 4.0 improved writing reversible migrations by allowing destructive methods like remove_column to be reversible, as well as adding a really handy ActiveRecord::Migration#reversible method allowing you to write everything in a change, not having to switch to up and down.</p><p>Sequel’s reversing capabilities are a bit lacking compared to ActiveRecord’s, they are currently about the same as ActiveRecord’s before this change.</p><h3>Null relation</h3><p>ActiveRecord 4.0 added a handy ActiveRecord::Relation#none which represents an empty relation, effectively implementing a null object pattern for relations.</p><p>Sequel <a href="https://github.com/jeremyevans/sequel/commit/e1e3207583c39ec69ea030e29b331868308c672c">added a null_dataset plugin</a> as an inspiration to ActiveRecord’s feature.</p><h3>ActiveRecord 3</h3><h3>EXPLAIN</h3><p>In 2011 ActiveRecord 3.2 added ActiveRecord::Relation#explain for EXPLAIN-ing queries (<a href="https://github.com/rails/rails/commit/e7b7b4412380e7ce2d8e6ae402cb7fe02d7666b8">commit</a>). Sequel has had EXPLAIN support for Postgres since 2007 (<a href="https://github.com/jeremyevans/sequel/blob/305b965a2790675bc920f8d2d1a3bc194e366af4/core/lib/sequel/adapters/postgres.rb#L365">code</a>), and for MySQL was added only later in 2012 (<a href="https://github.com/jeremyevans/sequel/commit/7708ec277572ddf36eee3999f20e67bedb07ac5b">commit</a>).</p><h3>Pluck</h3><p>ActiveRecord 3.2 added ActiveRecord::Relation#pluck in 2011 (<a href="https://github.com/rails/rails/commit/a382d60f6abc94b6a965525872f858e48abc00de">commit</a>), and added support for multiple columns in 2012 (<a href="https://github.com/rails/rails/commit/2e379c1e63b3646f9aff4d7e242ca37b4a57f529">commit</a>).</p><p>Sequel’s equivalent Sequel::Dataset#map existed since 2007 (<a href="https://github.com/jeremyevans/sequel/blob/305b965a2790675bc920f8d2d1a3bc194e366af4/core/lib/sequel/dataset/convenience.rb#L86">code</a>), and support for multiple columns was added in 2011 (<a href="https://github.com/jeremyevans/sequel/commit/3075880a2e0c4b42cc064cb5c342eb879bd809a1">commit</a>). To my initial surprise, Sequel’s map doesn’t automatically SELECT only the columns it needs. But then I’ve realized that it actually provides more flexibility, since it can be used with custom SELECTs and isn’t limited only to columns.</p><h3>Uniq</h3><p>ActiveRecord 3.2 added SELECT DISTINCT through ActiveRecord::Relation#uniq in 2011 (<a href="https://github.com/rails/rails/commit/562583c7667f508493ab8c5b1a4215087fafd22d">commit</a>). Sequel has had equivalent Sequel::Dataset#distinct since 2007 (<a href="https://github.com/jeremyevans/sequel/blob/a3c54c62a16b74218ba2311fb482b0b625972cd5/sequel_core/lib/sequel_core/dataset/sql.rb#L264">code</a>), <strong>4 years</strong> ahead of ActiveRecord.</p><h3>Update column</h3><p>ActiveRecord 3.1. added ActiveRecord::Base#update_column for updating attributes without executing validations or callbacks (<a href="https://github.com/rails/rails/commit/245542ea2994961731be105db6c076256a22a7a9">commit</a>). The equivalent behaviour in Sequel, user.this.update(…), at that moment already existed for <strong>4 years</strong>.</p><h3>Reversible migrations</h3><p>ActiveRecord 3.1 added support for reversible migrations via change (<a href="https://github.com/jeremyevans/sequel/commit/94450d775dfdc1b6cc0393944198bfa2ea0ecd71">commit</a>). Soon after that, and inspired by ActiveRecord, Sequel added its support for reversible migrations (<a href="https://github.com/jeremyevans/sequel/commit/94450d775dfdc1b6cc0393944198bfa2ea0ecd71">commit</a>).</p><h3>Arel</h3><p>Finally, we come probably to ActiveRecord’s biggest update: the chainable query interface and extraction of <a href="https://github.com/rails/arel">Arel</a>. For those who don’t know, ActiveRecord prior to 3.0 didn’t have a chainable query interface.</p><p>Sequel already had this chainable query interface, before Nick Kallen started working on Arel (<a href="http://sequel.jeremyevans.net/2010/02/06/arel-sequel-differences-part-1.html">source</a>), meaning he was obviously inspired by Sequel. Also, building queries with Arel looks very different than through models (it’s arguably more clunky), while Sequel’s low-level interface gives you the exact same API as you have through models.</p><p>Alternative to Arel for building complex queries is <a href="https://github.com/activerecord-hackery/squeel">Squeel</a>. Beside the obvious insipration indicated by the anagram in the name (even though there is no mention of it in the README), the interface obviously mimics Sequel’s <a href="http://sequel.jeremyevans.net/rdoc/files/doc/virtual_rows_rdoc.html">virtual row blocks</a>.</p><h3>Aftermath</h3><p>In this detailed overview, even though Sequel was ahead of ActiveRecord in vast majority of cases, there were a few cases where ActiveRecord was leading the way:</p><ul><li>Reversible migrations</li><li>Aborting hooks</li><li>Mutation detection</li><li>Enum (kind of)</li><li>Null relation</li></ul><p>We see that Sequel was closely keeping up with ActiveRecord, but ActiveRecord wasn’t keeping up with Sequel. Note that on GitHub Sequel maintains 0 open issues, while ActiveRecord circles around 300 open issues. It’s also worth mentioning that Sequel is maintained mainly by one developer, while ActiveRecord is developed by most of the Rails team.</p><h3>Conclusion</h3><p>I want that you think about this. ActiveRecord was mainly implementing features that Sequel already had. That could be justified if ActiveRecord had some other advantages over Sequel, but I’m failing to see them. I don’t classify integration with Rails as an advantage (you can just make a <a href="https://github.com/TalentBox/sequel-rails">sequel-rails</a> for that), I mean advantages that actually help interacting with databases.</p><p>I wished that I used Sequel from day one, instead of starting with ActiveRecord and slowly realizing that Sequel is better. The only reason ActiveRecord is so popular is because it’s part of Rails, not because it’s better. There is a reason why <a href="https://github.com/hanami/model">hanami-model</a> and <a href="https://github.com/rom-rb/rom-sql">ROM</a> use Sequel under-the-hood and not ActiveRecord. It hurts me that so many developer hours are put into ActiveRecord, and I don’t see for what purpose; a better tool already exists and is excellently maintainted. Let’s direct our energy towards these better tools.</p><p><em>Originally published at </em><a href="http://twin.github.io/activerecord-is-reinventing-sequel/"><em>twin.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99985a5ebdb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/activerecord-is-reinventing-sequel-99985a5ebdb6">ActiveRecord is reinventing Sequel</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[do you know our DOJO?]]></title>
            <link>https://medium.com/hashdog-blog/do-you-know-our-dojo-398c0d6a4b6f?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/398c0d6a4b6f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-factories]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 03 Mar 2016 19:20:06 GMT</pubDate>
            <atom:updated>2016-03-03T19:20:06.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NABXqX25N0y46N_gPahdNQ.jpeg" /></figure><p><a href="https://medium.com/://hashdog.ninja">take a look! https:://hashdog.ninja</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=398c0d6a4b6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/do-you-know-our-dojo-398c0d6a4b6f">do you know our DOJO?</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[{HashDog} why hire us? short animation!, dont missing it!]]></title>
            <link>https://medium.com/hashdog-blog/hashdog-short-animation-9f6e99051de?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f6e99051de</guid>
            <category><![CDATA[software-factories]]></category>
            <category><![CDATA[hashdog]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 03 Mar 2016 19:16:21 GMT</pubDate>
            <atom:updated>2016-03-03T19:28:01.924Z</atom:updated>
            <content:encoded><![CDATA[<p>{HashDog} why hire us? short animation!, dont missing it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*L6mqMopwgVNZyuKggfkJLw.jpeg" /><figcaption>dogger</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZt_CnXwuZQw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZt_CnXwuZQw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZt_CnXwuZQw%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f2871a906658a66e218728212c61ad1/href">https://medium.com/media/4f2871a906658a66e218728212c61ad1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f6e99051de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/hashdog-short-animation-9f6e99051de">{HashDog} why hire us? short animation!, dont missing it!</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[beerpay.io released — A way to monetize open source projects]]></title>
            <link>https://medium.com/hashdog-blog/beerpay-io-released-a-way-to-monetize-open-source-projects-75742b7a017f?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/75742b7a017f</guid>
            <category><![CDATA[monetize-opensource]]></category>
            <category><![CDATA[monetize-your-website]]></category>
            <category><![CDATA[beerpay]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 03 Mar 2016 18:51:47 GMT</pubDate>
            <atom:updated>2016-03-03T18:51:47.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZIuWl6UMpRUud1gJfzDLHg.png" /></figure><h3>The funding issue</h3><p>Open source is growing exponentially in the last years, that’s a fact to celebrate. However, until now, the big problem for developers has always been the funding issue: You need money to live and, most of the times, you get by working for proprietary software projects. Beerpay comes to fill that gap, between making open source and making a living.https://beerpay.io/projects</p><h3>The platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*hVF3JnjGSmtMQuJY.png" /></figure><h3>The funding issue</h3><p>Open source is growing exponentially in the last years, that’s a fact to celebrate. However, until now, the big problem for developers has always been the funding issue: You need money to live and, most of the times, you get by working for proprietary software projects. Beerpay comes to fill that gap, between making open source and making a living.https://beerpay.io/projects</p><h3>The platform</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FV12mdAg4-sM%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV12mdAg4-sM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FV12mdAg4-sM%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5f33bfe8c70282d82d1d41cfabfc270/href">https://medium.com/media/a5f33bfe8c70282d82d1d41cfabfc270/href</a></iframe><p>Beerpay.io is made by and for developers. The platform allows people to automatically import the projects they choose directly from their Github account, which is a must-have to use the platform. After importing the projects, they will appear on a list of projects, with the possibility to view them also by user, very similar to Github. The idea is to make open source projects visible and generate the support of other developers.</p><h3>Wishes and supporters</h3><p>People can view projects on Beerpay and decide to “make a wish”: a request for the project owner to change a functionality, parts of the design, customize something, or anything else that the project owner can do to make the project useful to the wish maker. Wishes include a monetary incentive, and other developers can join — or “support” — a wish by adding more money to the request. The project owner can accept or decline the wish. If declined, he/she can explain the reason of the rejection and give the wish maker the possibility to adapt his/her wish. If accepted, the project owner has a specific amount of time to deliver the changes and collect his/her money.</p><p><a href="https://beerpay.io/"><strong>Check beerpay out!</strong></a></p><h3>The people behind it</h3><p>Hashdog is an argentinean software factory who believes in the power of the open source. We’ve been around for 10 years making software, like a collaborative code editor for remote teams to work simultaneously on code, called<a href="http://scrapfy.io/"><strong>scrapfy.io</strong></a>, free to use, with no installation required; And a MEAN, fullstack, JavaScript framework called <a href="https://doggerjs.com/"><strong>DoggerJS</strong></a>for anyone to download.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75742b7a017f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/beerpay-io-released-a-way-to-monetize-open-source-projects-75742b7a017f">beerpay.io released — A way to monetize open source projects</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve the Smell of Your Code with Microrefactorings]]></title>
            <link>https://medium.com/hashdog-blog/improve-the-smell-of-your-code-with-microrefactorings-84e1cda6d296?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e1cda6d296</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[refacting]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 03 Mar 2016 07:00:39 GMT</pubDate>
            <atom:updated>2016-03-04T13:57:20.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*QjTiddk9VJZ6o23v.jpg" /></figure><p>You may believe that refactoring is about hideous complexity. Hours — no, days — spent trying to decipher thousand-line methods. A sprawling tangle of calls and callbacks that appear to produce working code only by accident.</p><p>Sometimes refactoring is all of these things, but more often than not, refactoring is about detecting familiar patterns and then responding to them methodically. From afar, large refactorings can seem daunting. Impossible. Close up, though, they’re made up of lots of tiny changes, and each change is rational. Explainable.</p><p>Refactoring is not so much about thousand-line methods. It’s about recognizing a tiny pattern within that thousand-line method and then applying a step-by-step recipe to change that small thing. It’s doing this over and over again.</p><p>Notice that there are two parts to this:</p><ul><li>Recognizing a snippet of code as exhibiting characteristics that are known to be problematic.</li><li>Applying a change that is known to fix this category of problem.</li></ul><p>This is not a rigid, infallible process. There’s some guess-work involved. Sometimes you recognize the problem, but it’s embedded in other problems that you have trouble articulating, and it can be hard to get at it. You might not be able to isolate it well enough to fix it. Or maybe you get a whiff of a problem but you can’t pinpoint what the issue actually is. Perhaps there are several known fixes for a problem, and you’re not sure which one will work and try two or three different approaches before you find one that fits comfortably.</p><p>Regardless, it all boils down to detecting a problematic pattern and then performing a systematic procedure to fix it.</p><p>Problematic patterns are known as “code smells”.</p><blockquote><em>[A] code smell is a surface indication that usually corresponds to a deeper problem in the system. — Martin Fowler</em></blockquote><p>A <em>deeper problem in the system</em> sounds kind of ominous. It feels like we’re right back to talking about the kind of thing that can take days to understand and weeks or months to fix. The thing is, the process is the same no matter how big — or small — the code smell is.</p><p>If you want to get better at refactoring, applying the process at the micro level can make it easier to start dealing with it in larger, more chaotic systems.</p><p>Look at the following code snippet:</p><pre>sum = 0 numbers.each do |number| sum += number end sum</pre><p>Make a snap judgement about it.</p><p>Good/bad. Clean/dirty. Simple/complex. Readable/cryptic.</p><p>You don’t need to be able to back up your gut feeling with logic or arguments. Just notice what you like or dislike about it.</p><p>Here’s another one:</p><pre>anagrams = [] candidates.each do |candidate| if anagram_of?(subject, candidate) anagrams &lt;&lt; candidate end end anagrams</pre><p>Check your gut feeling about it. Compare it to the previous example.</p><p>Better/worse. Same/different.</p><p>Here’s another one:</p><pre>mutations = 0 (0...strand1.length).each do |i| if strand1[i] != strand2[i] mutations += 1 end end mutations</pre><p>And one more:</p><pre>oldest = &quot;&quot; highest = 0 kids.each do |kid| if kid.age &gt; highest oldest = kid.name highest = age end end oldest</pre><p>Take a moment to notice similarities and differences between the examples.</p><p>The most obvious similarity is, perhaps, that these are all loops. Also, every loop is an each. More importantly, each of the above code examples exhibit one or two specific micro code smells.</p><ul><li><em>A loop with a temporary variable.</em></li><li><em>A loop with a nested conditional.</em></li></ul><p>The fix for both of these code smells is to choose a more appropriate enumerable method.</p><p>At first “choosing a more appropriate enumerable method” can seem like magic. How do you know? Well, you don’t. You basically go to the list of <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html">enumerable methods</a> and see if you can find one that makes sense. You try a few. You start getting a feel for them. You find that in some cases more than one enumerable method does an admirable job. Over time you start reaching for good enumerable methods instinctively.</p><p>Here are the micro refactorings to match the micro smells showcased in the examples above.</p><p>The first loop has only a temporary variable, no nested conditional. It can be fixed with inject, or its alias, reduce:</p><pre># before sum = 0 numbers.each do |number| sum += number end sum # after numbers.inject(:+)</pre><p>The second loop has both a temporary variable and a nested conditional. We’re filtering a list, and both select and reject tend to be good for this sort of thing. In this case, since we’re filtering to keep rather than discard, select or its alias keep_if is a good choice:</p><pre># before anagrams = [] candidates.each do |candidate| if anagram_of?(subject, candidate) anagrams &lt;&lt; candidate end end anagrams # after candidates.select do |candidate| anagram_of?(subject, candidate) end</pre><p>The third example also exhibits both micro smells. In this case we’re counting differences:</p><pre># before mutations = 0 (0...strand1.length).each do |i| if strand1[i] != strand2[i] mutations += 1 end end mutations # after (0...strand1.length).count {|i| strand1[i] != strand2[i]}</pre><p>The final code example has a triple whammy: two temporary variables and a nested conditional. Since we’re ranking on some attribute, perhaps sort_by would work:</p><pre># before oldest = &quot;&quot; highest = 0 kids.each do |kid| if kid.age &gt; highest oldest = kid.name highest = age end end oldest # after kids.sort_by {|kid| kid.age}.last.name</pre><p>It turns there’s an even better choice. If you want the first or last of some list of complex objects ordered by some arbitrary attribute, you can use min_by and max_by:</p><pre># even more after kids.max_by {|kid| kid.age}.name</pre><p>In the real world, the loop won’t always be an each. It won’t always be particularly verbose, either. Sometimes the conditional will be concise: a postfix if or unless, or a ternary statement.</p><p>Once you’ve identified a smell with this sort of precision, though, the problem is utterly straightforward to diagnose and fix in almost any context.</p><pre># before words.inject([]) do |censured, word| censured &lt;&lt; word if word.size == 4 censured end # after words.select {|word| word.size == 4}</pre><p>Sometimes you won’t be able to get rid of it — there might not be a perfect enumerable method. This is the nature of code smells. They’re <em>usually</em> an indication that there’s a better way to solve something, but not always.</p><p>Unlike the classic code smells described by Martin Fowler in his book <a href="http://www.amazon.com/Refactoring-Ruby-Addison-Wesley-Professional-ebook/dp/B002TIOYWG/">Refactoring</a>, micro code smells are unlikely to be a symptom of a deeper problem in the system. A micro code smell will only affect a few lines of code in its immediate vicinity.</p><p>It’s still worth doing, and not just because you start getting a feel for how little drama there is in a good refactoring.</p><p>The cumulative effect of reducing friction, removing boilerplate, and improving readability in tiny increments is that larger code smells rise to the surface and become easier to detect.</p><p>And if you can detect it, there’s a great chance that you can fix it.</p><p><em>Originally published at </em><a href="http://www.sitepoint.com/improve-the-smell-of-your-code-with-microrefactorings/"><em>www.sitepoint.com</em></a><em> on March 3, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e1cda6d296" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/improve-the-smell-of-your-code-with-microrefactorings-84e1cda6d296">Improve the Smell of Your Code with Microrefactorings</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Action Cable and WebSockets: An in-Depth Tutorial]]></title>
            <link>https://medium.com/hashdog-blog/action-cable-and-websockets-an-in-depth-tutorial-d9b738aaea5?source=rss-54f6b3f1d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9b738aaea5</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[chebyte]]></dc:creator>
            <pubDate>Thu, 04 Feb 2016 07:00:27 GMT</pubDate>
            <atom:updated>2016-03-04T13:57:57.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xG6Uutic-ITNavwQ.jpg" /></figure><p>One of the highly anticipated feature of Rails 5 is the official solution for integrating web socket communication with Rails, dubbed Action Cable. As a <a href="http://www.antlr-interactive.com/">Ruby on Rails agency</a>, we are very excited about this upcoming feature release.</p><p>According to their Github page, Action Cable:</p><blockquote><em>[…] seamlessly integrates WebSockets with the rest of your Rails application. It allows for real-time features to be written in Ruby in the same style and form as the rest of your Rails application, while still being performant and scalable.</em></blockquote><p>It sounds awesome and useful. Forget working directly with gems like Faye, Action Cable takes the mess out of web sockets and acts as an adapter to the functionality. It provides a clean interface for both client-side Javascript code as well as server-side Rails code.</p><p>To fully understand Action Cable in Rails 5, we need to take a look at a few things:</p><ul><li>The basics of WebSockets</li><li>The Action Cable API and an example</li><li>The pros and cons of Action Cable</li></ul><p>Let’s begin!</p><h3>What are WebSockets?</h3><p>HTTP has been around for quiet a while and, obviously, is the most ubiquitous protocol for communication between the browser and the server. In a typical browser HTTP request, the browser asks the server for a single HTML, Javascript, or CSS document. Afterwards, the connection is closed and if the browser needs additional resources, it is the job of the browser to initiate the conversation again.</p><p>Before WebSockets were even an idea, developers would mimic the WebSockets concept by consistently polling the server to check for updates every few seconds. You might already have alarms going off in your head. There isn’t great scalability in regards to polling. As a developer, you would be adding considerable load to your servers. That being said, polling is still very much used all over the Internet.</p><p>So what are WebSockets? Unlike HTTP requests, WebSockets are connections that are stateful. This means that the connection between a client and a server remains constant and connected. In this scenario. either party (the client or the server) has the ability to initiate a request or a message. The end result is direct interaction between browser and server.</p><h3>Enter Action Cable</h3><p>As part of his 2015 Rails Conf Keynote, David Heinemeier Hansson announced the addition of Action Cable to the Rails core. The reasoning behind this addition was based on the current landscape of application frameworks and the increasing need for such a feature. Action Cable was introduced as a new concept for extending Rails functionality with real-time messaging utilizing WebSockets.</p><h3>The Action Cable API</h3><p>To start playing around with Action Cable, first create a new project and install the actioncable gem. For ease of use, check out this project in this <a href="https://github.com/kylesziv/action-cable-house-example">example repository</a>.</p><p>In your terminal, change into the directory of the project run bundle install to install the project dependencies.</p><p>Since there is a need for a multi-threaded web server, we will be utilizing puma. The Action Cable service will run separately from our application server.</p><p>For this project, you will need to have Redis installed. Below are some quick directions on how to install Redis:</p><p>Linux:</p><pre>wget <a href="http://download.redis.io/redis-stable.tar.gz">http://download.redis.io/redis-stable.tar.gz</a> tar xvzf redis-stable.tar.gz cd redis-stable make make install</pre><p>Mac:</p><pre>brew install redis</pre><p>Once Redis is installed, go ahead and start your servers. In one terminal window run ./bin/cable to run your cable server.</p><p>In a new terminal window run ./bin/rails server to start the Rails server. Finally, and in yet another window, run redis-server to start the Redis server. Whew!</p><p>Once all these run successfully, you can navigate in your browser to localhost:3000. You’ll notice a map of Pittsburgh, PA, USA. Open up another browser to the same url. It could be a different browser or an incognito session of the same browser, so that the two sessions are not sharing the same cookies, etc.</p><h3>Action Cable in Action</h3><p>In the first browser window, click the create a house link that is below the houses tag on the home page. This will take you to a form with two fields. Fill out the address and zip code fields of a house or even a famous <a href="https://www.google.com/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=pittsburgh%20attractions">Pittsburgh attraction</a>. Once you click “Save”, you’ll notice on your other browser window, a pin drops down and a new house is listed on the map. This was all done via Action Cable and WebSockets.</p><h3>Diving into Action Cable</h3><h4>Creating Channels</h4><p>In Action Cable, channels are the meat and potatoes. Notice the following files in the <strong>channels</strong> folder:</p><ul><li><strong>app/channels/application_channel/connection.rb</strong></li><li><strong>app/channels/application_channel/channel.rb</strong></li><li><strong>app/channels/houses_channel.rb</strong></li></ul><p>ApplicationCable::Connection is used for general authorization. For example, we could use this module to query the database for a specific user that is making the connection and ensure that they are allowed to listen. For this project, we do not have any users and, thus, need no code here.</p><p>ApplicationCable::Channel is used much like ApplicationController in our normal stack. This class is the base of all other channels. Notice that all other channels in the project inherit from this class. You can use this class to perform shared logic that can be used between channels.</p><p>Lastly, there is the HouseChannel. When a client is trying to subscribe to a channel, the follow method on the channel gets called and anything that gets broadcast via the house stream will be sent to the client.</p><p>Keep in mind that there are two methods that can achieve similar results: stream_from and stream_for. The stream_from method is used to subscribe to a string that you define. For example, in our project, we subscribed to broadcasts that are associated with the string “houses”. When a new house is created, we want to know about it. In contrast, stream_for is used when there is a particular record (or record and association) we want updates about. Under the hood, Action Cable is generating a unique string for that record or that record and its association and then calls the stream_for method.</p><blockquote><em>NOTE: Another benefit of the stream_for method, is that it takes an optional callback method as the second parameter.</em></blockquote><h4>Broadcasting Changes</h4><p>For our example, a broadcast on the house channel happens after a house has been added. For this to work, we’ve created one <a href="http://www.sitepoint.com/new-rails-shiny-activejob/">ActiveJob</a> and a callback for the model.</p><p>The callback in our House model looks like the following:</p><pre>after_commit { HouseRelayJob.perform_later(self) }</pre><p>This creates a HouseRelayJob and schedules it to be performed in the near future.</p><p>The HouseRelayJob.perform method looks like:</p><pre>class HouseRelayJob &lt; ApplicationJob def perform(house) ActionCable.server.broadcast &quot;houses&quot;, house: house end end</pre><p>This tells the HouseChannel that a new house has been created, whicj sends the newly created house object to whomever is actively subscribing. For this example, it will be sending JSON to the client.</p><h4>Client Side Subscriptions</h4><p>The last portion of our houses channel is the client side code. There are two files that define this relationship. The first file is <strong>app/assets/javascripts/channels/application_channel.coffee</strong>. This file just defines the cable:</p><pre>#= require cable @App = {} App.cable = Cable.createConsumer &#39;ws://localhost:28080&#39;</pre><p>The second file is the <strong>app/assets/javascripts/channels/houses.coffee</strong> which establishes the subscription to the HousesChannel and then also creates the pin marker after a new house was been broadcast.</p><pre>App.houses = App.cable.subscriptions.create &#39;HousesChannel&#39;, dropMarker: (house) -&gt; new google.maps.Marker position: { lat: house.latitude, lng: house.longitude}, map: window.map, animation: google.maps.Animation.DROP title: &quot;#{house.address} #{house.zipcode}&quot; received: (data) -&gt; @dropMarker(data.house)</pre><h3>Pros and Cons of Action Cable/WebSockets</h3><p>Fully understanding a technology is important when deciding whether it will meet your needs. Implementing a new technology for technology sake can be an expensive mistake. Since Action Cable is a wrapper around WebSockets, we should really understand the Pros and Cons of using WebSockets.</p><h3>The Pros</h3><p>One of the largest benefits of WebSockets and Action Cable is that it is an open connection that is extremely lightweight compared to the normal HTTP request:</p><blockquote><em>HTML5 Web Sockets provides an enormous step forward in the scalability of the real-time web […] HTML5 Web Sockets can provide a 500:1 or — depending on the size of the HTTP headers — even a 1000:1 reduction in unnecessary HTTP header traffic and 3:1 reduction in latency. That is not just an incremental improvement; that is a revolutionary jump — a quantum leap!</em></blockquote><p><a href="http://www.websocket.org/quantum.html">HTML5 WebSocket: A Quantum Leap in Scalability for the Web<br> </a>.</p><p>Another benefit is that once a connection is made, it remains open. Both the server and the client can communicate through that open line without having to reestablish a new connection.</p><p>Lastly, a WebSocket connection is a full-duplex connection. The server and the client can use this connection to communicate to each other at the same exact time. This is very different compared to the normal half-duplex HTTP connection.</p><p>After reviewing the pros, it seems as if the addition of WebSockets into an application can greatly improve performance by reducing the data that needs to be sent across the wire.</p><h3>The Cons</h3><p>One of the biggest arguments against WebSockets is the inability to cache these requests. While researching Action Cable, I stumbled upon a really in-depth article about Action Cable written by Nate Berkopec called <a href="https://www.nateberkopec.com/2015/09/30/action-cable.html">Action Cable — Friend or Foe?</a>. He references many different alternatives to WebSockets and whether Action Cable is worth it.</p><p>When referencing Action Cable and WebSockets, he states:</p><blockquote><em>I’m not sure I buy into “WebSockets completely obviates the need for HTTP!” rhetoric. HTTP comes with a lot of goodies, and by moving away from HTTP we’ll lose it all. Caching, routing, multiplexing, gzipping and lot more. You could reimplement all of these things in Action Cable, but why?</em></blockquote><p>He continues by saying that it may be worth waiting a little bit. Both Action Cable and WebSockets are newer technologies and we may want to wait until the dust settles before adding it in just for technology sake.</p><p>Nate continues to say that there are some cases where Action Cable makes complete sense:</p><blockquote><em>[F]or high-throughput situations, where the client is communicating several times per second back to the server, I think Action Cable could be a great fit.</em></blockquote><p>Another con of WebSocket is the support among browsers. Currently, 70% of the browser market allows for WebSocket connections. This leaves 30% in need of a secondary solution.</p><p>Before reaching for Action Cable as the solution to your problem, make sure you’ve researched and know for sure that Action Cable will fit your needs.</p><h3>Wrapping Up</h3><p>Action Cable is a powerful addition to the Rails framework. Hopefully, this articles has given you the tools you need to decide if Action Cable and WebSockets are worth trying and researching further.</p><p>I’d love to hear more about how you’ve utilized Action Cable in either a live project or just for fun. Please feel free to leave a comment. Let’s have a conversation!</p><p><em>Originally published at </em><a href="http://www.sitepoint.com/action-cable-and-websockets-an-in-depth-tutorial/"><em>www.sitepoint.com</em></a><em> on February 4, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9b738aaea5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hashdog-blog/action-cable-and-websockets-an-in-depth-tutorial-d9b738aaea5">Action Cable and WebSockets: An in-Depth Tutorial</a> was originally published in <a href="https://medium.com/hashdog-blog">Hashdog Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>