Freelance Mobile & Web Developer

A Ruby & Javascript hacker.

My Top Five Rails 4 Features

Rails 4 was released last June and version 4.0.1 at the beginning of this month. It should be noted that Rails 4 requires Ruby 1.9.3 with Ruby 2.0 being recommended.

Here I highlight my top five features:

Strong Parameters

Rails Mass assignment feature is quite handy but can be really dangerous. Last year Github was compromised by an attack based on it. Rails 4 has a new way of dealing with mass assignment each basically pushes the responsibility out of the model and into the controller where it belongs.

The new approach was already available as a plugin called strong_parameters and dhh as a blog post explaining it in detail.

Live Streaming

Rails 4 brings Lives Streaming as a major new feature. To enable streaming we need to mixin the ruby ActionController::Live to the controller class. One use case for this is to enable push notifications to the frontend without relying on plugins like Juggernaut or outside services such as Pusher.

You can read more about this feature here and here.

Russian Doll caching

Russian Doll caching describes the technique of using nested fragment caching. The idea is that a page can best divided multiple sections, each one being a fragment. These cached fragments are used independently and can be reused when the content changes. Changes to inner fragments caused a chain reaction which expires all outer fragment caches. Rails 4 uses caches digests to avoid the pain of maintaining cache version numbers for individual templates.

You can read more about Russian Doll caching here

Asynchronous Action Mailer

A new Queue framework was added to Rails 4 and Action Mailer are configured by default to use this new Queue interface. The interface remains very similar to Rails 3 developers with the added benefit that changing backend providers is as easy as changing a single line of code:

1
2
3
4
# production.rb
config.queue = ActiveSupport::Queue.new
# In this case to use Sidekiq as the Action Mailer backend
config.action_mailer.queue = Sidekiq::Client::Queue.new

You can read more about this feature here

Other smaller enhancements

Rails 4 is now thread-safe by default. You can read about this change on this helpful post by Aaron Patterson.

Another addition is Turbolinks which works similarly to pjax, fetching relevant content and updating the page to avoid a full reload. Read more about it here

There are many more features that I will not be able to cover here. You can read the releases notes to see the detailed changes.

Rails 4.0.1 brings some stability improvements to Rails 4. The complete set of changes are shown here

Using Pry With Rails

Pry is a IRB replacement with some very nice additional features. I’ll link to additional resources at the end of this post.

Some of the additional features pry offers us include:

  • Native syntax highlighting
  • Source and document browsing
  • Very flexible plugin architecture

Installation

You can install and run pry with:

1
2
$ gem install pry
$ pry

They are a few ways to integrate pry with Rails but the one I like it the most came from @fnando and originally from Luca Pette. Instead of patching of Rails initializer file, as described on the Pry Wiki, you can use the following method:

On IRB initialization file load Pry instead:

~/.irbrc
1
2
3
4
5
6
7
begin
  require 'pry'
  Pry.start
  exit
rescue LoadError => e
  warn "=> Unable to load pry"
end

This will load try to load Pry and if failed will print a message to stdout. The exit command after Pry’s invocation is to avoid going back to IRB after the Pry session has finished.

The other part of the configuration is done on .pryrc

~/.pryrc
1
2
3
4
5
6
7
8
9
if defined?(Rails)
  begin
    require "rails/console/app"
    require "rails/console/helpers"
  rescue LoadError => e
    require "console_app"
    require "console_with_helpers"
  end
end

This will allow you to continue using rails console but using pry instead of irb. I also like to use awesome_print so I added this to my config file:

~/.pryrc
1
2
3
4
5
6
begin
  require "awesome_print"
  Pry.config.print = proc {|output, value| Pry::Helpers::BaseHelpers.stagger_output("=> #{value.ai}", output)}
rescue LoadError => err
   warn "=> Unable to load awesome_print"
end

This will try to load awesome_print gem and failing to do that will print a message to stdout.

For more information on Pry see:

Routing a Wordpress Blog Inside a Rails App

This post describe how to host a subdomain route for a alien application inside a Ruby on Rails app. Wordpress is used here as an example but these instructions work with any outside url.

If you do have control over the web server you can use a url rewrite to accomplish this. See steps for doing this using Apache or nginx.

However what about when you have no control over the web server layer (such as when hosting the Rails application on Heroku)? The answer is to use the Rails routing engine do the routing.

config/routes.rb
1
 match "/blog" => redirect("http://yourwordpressblog.com"), :as => :blog

This will match any ‘/blog’ route and redirect to your chosen domain.

Full Text Search With MongoDB

Recently I had to implement full text search on a Ruby on Rails application I was developing and based on my needs the easiest way to do it was building a helper array with the keywords needed and search using those keywords.

To illustrate this I’ve implemented stock tickers search using the awesome rstat.us project. Have a look at my Github fork.

update.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Update
...
    # Adds stocks array mentions
    key: stocks, Array, :default => []

  # Parses update text and build stocks array for simpler search
  def parse_symbols
    stocks = []
    self.text.split(' ').each do |update|
      stocks << update if update[0] == '$'
    end
    return stocks
  end
end

and then the controller:

updates_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
class UpdatesController < ApplicationController
...
    def create
      ...
      u = Update.new(:text => params[:text],
          :referral_id => params[:referral_id],
          :author => current_user.author,
          :twitter => do_tweet)

      u.stocks = u.parse_symbols
      ...
    end
end

So it basically looks for words starting with $ and adds it to the stocks array. We can then search using

Perform search using MongoDB built in text search
1
Update.all(:conditions => {:stocks => '$goog'})

There are different solutions such as mongoid_search that could be used but for my needs this approach works the best.

MongoDB gives a lot of flexibility for the developer and speeds things up. Of course there are trade-offs to be made while using so YMMV.

Starting on the Blogging Path

After trying to blog and failing to continue writing I feel the need to start once more. Hopefully this time I’ll be able to sit down and write about technical subjects that interest me.

My intention with this blog is to share findings and document my learning process as I build and work on different applications.

More to come soon and thanks for stopping by.