Ruby ‘Unless’ Goes Mainstream

I don’t like or not a fan of Ruby’s ‘unless’ keyword. I mean its nice but it take time to get used to.

Sample ‘unless’ statements like this:

1
puts product.name unless product.name.nil?

The code statement above is nice and easy. I’d say that in english “Print the product’s name unless the product doesn’t have a name”.

Why do we need unless? Let replace it with something else:

1
2
3
4
5
class Object
  def not_nil?
    !nil?
  end
end

Then we can code:

1
puts product.name if product.name.not_nil?

So far so good, that’s much better, ‘unless’ never made it into mainstream language.
OO scripting languages like Ruby can make new keyword. :)

Test Routes With RSpec in Ruby on Rails

Most Ruby on Rails developers don’t test their routes, they focus on Model testing, Controller testing, Features or View testing, Helper testing, and try to catch every possible scenarios.
I would like to show how to test route separately.

Sample routes.rb:

routes.rb
1
resources :products

Here is routes lists thats have been created:

1
2
3
4
5
6
7
8
     root        /                            products#index
    posts GET    /products(.:format)          products#index
          POST   /products(.:format)          products#create
 new_post GET    /products/new(.:format)      products#new
edit_post GET    /products/:id/edit(.:format) products#edit
     post GET    /products/:id(.:format)      products#show
          PUT    /products/:id(.:format)      products#update
          DELETE /products/:id(.:format)      products#destroy

Testing for each routes in routing/products_routing_spec.rb:

products_routing_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require 'spec_helper'

describe "routing to products" do
  it "routes /products to products#index" do
    expect(get: "/products").to route_to(
      controller: "products",
      action: "index"
    )
  end

  it "routes /products/1 to products#show" do
    expect(get: "/products/1").to route_to(
      controller: "products",
      action: "show",
      id: "1"
    )
  end

  it "routes /products/new to products#new" do
    expect(get: "/products/new").to route_to(
      controller: "products",
      action: "new"
    )
  end

  it "routes /products to products#create" do
    expect(post: "/products").to route_to(
      controller: "products",
      action: "create"
    )
  end

  it "routes /products/1/edit to products#edit" do
    expect(get: "/products/1/edit").to route_to(
      controller: "products",
      action: "edit",
      id: "1"
    )
  end

  it "routes /products/1 to products#update" do
    expect(put: "/products/1").to route_to(
      controller: "products",
      action: "update",
      id: "1"
    )
  end

  it "routes /products/1 to products#destroy" do
    expect(delete: "/products/1").to route_to(
      controller: "products",
      action: "destroy",
      id: "1"
    )
  end
end

Testing unroutable:

routes.rb
1
resources :products, except: [:show]
products_routing_spec.rb
1
2
3
it "does not routes /products/1 to products#show" do
  expect(:get => "posts/1").not_to be_routable
end

So far so good, Let enjoy the routes testing in your Ruby on Rails application. :)

RailsPanel

RailsPanel is a Chrome extension for Rails development that will end your tailing of development.log. Have all information about your Rails app requests in the browser - in the Developer Tools panel. Provides insight to db/rendering/total times, parameter list, rendered views and more.

Installation
To use this extension you need to add meta_request gem to your app’s Gemfile:

Gemfile
1
2
3
group :development do
  gem 'meta_request'
end

Install RailsPanel extension from the Chrome WebStore. This is recommended way of installing extension, since it will auto-update on every new version. Note that you still need to update meta_request gem yourself.

So far so good, Let play around with RailsPanel and enjoy your productivity. :)

Implement Decorator Design Pattern in Rails With Draper to Cleanup Views

Ruby on Rails is an awesome framework to build web application. Rails relies on the MVC pattern, and lots of conventions, code becomes complex to maintain, productivity start to decrease, etc.

We can find a lot of reasons to this(too much logic in controllers, fat models, lack of services layers, etc.), but I will just name one: logic in view, logic in view is bug prone, difficult to test, and can be a pain for front-end developers.

Sample problem

articles_controller.rb
1
2
3
4
5
class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
  end
end
show.html.haml
1
2
- if can? :update, @article
  = link_to "Edit", edit_article_path(@article)

Well, you got it, logic in view. And since rails don’t have view inheritance, this code will have to be copy-pasted over and over, I would rather have something like: = @article.link_to_edit

So, how can we remove logic from the view?

Decorator Design Pattern save the views
As usual, we can find a solution with a pattern. the decorator design pattern will help us remove logic from views in our Rails applications.
The idea is to insert an object between the model and the view, well there is a good ruby gem is Draper that work well.

Let create a decorator for the Article class

article_decorator.rb
1
2
3
4
5
6
7
class ArticleDecorator < Draper::Decorator
  def link_to_edit
    if h.can? :update, object
      h.link_to "Edit", h.edit_article_path(object)
    end
  end
end
articles_controller.rb
1
2
3
4
5
class ArticlesController < ApplicationController
  def show
    @article = ArticleDecorator.new(Article.find(params[:id]))
  end
end
show.html.haml
1
= @article.link_to_edit

A few things to notice here. From the controller, we call the decorate method on a instance of article, this will return a decorated version of the article object.

In the ArticleDecorator class, we have access to the decorated object with the object method and to all view helpers through the h object.
We can now call the link_to_edit method on the article object from our view, and the decorator will take care of the logic, and return a formatted link if the user has the right edit this resource, and nothing if he does not.

The code is easier to test, we just instantiate a new instance of the ArticleDecorator, and check the output of the link_to_edit method. No need to test whole renderd view, searching through the DOM object tree.

So far so good, we gain code readablility, code reuse, better testing, and in addition, we even lost a few lines of duplicated code. :)

Vim - the Best Programming Editor for UNIX

Vim is an advanced text editor that provide the power of Unix editor ‘Vi’, with a more complete feature set.

Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems.

Vim is often called a “programmer’s editor,” and so useful for programming that many consider it an entire IDE. It’s not just for programmers, Vim is perfect for all kinds of text editing, from composing email to editing configuration files.

Features
- highly configurable.
- syntax highlightning.
- windows split (both vertically as well as horrizontally).
- tabbing.
- folding.
- unicode support.
- flexible indenting.
- …

The Good
Vim is a professional text editor targeting mainly programmers, but it can be also used by any other type of user.
It received the best text editor award from readers of the Linux Journal magazine in 2001, 2002, 2003 , 2004 and 2005, which I think tells a lot about its efficiency.

The Bad
The bad and ugly part about Vim would be for most users the fact that they must do the learning first in order to be able to use it.

The Truth
Vim is a multi-platform text editor, Vim provides all the functionality of a regular text editor, such as spell checking, Unicode support, possibility of undo/redo the most recent actions, integrated help but it has also some features of its own which make it a powerful and reliable tool.

So far so good, To get a better idea on what Vim is, you can also check www.vim.org :)

Decorator Design Pattern

In the object-oriented world, simple applications usually require small classes with static behaviors. Adding, modifying, and sharing those behaviors can be achieved by mixing in modules or inheriting from other classes at compile time.

However, more complex applications might require a particular instance of a class to gain additional functionality at runtime. To modify the behavior of an object dynamically, we can utilize the decorator design pattern.

When to Decorate
Decoration can be used to add behavior to any individual object without affecting the behavior of other objects of the same class. Essentially the existing object is being wrapped with additional functionality.

Some practical problems that can be solved by decoration are
- applying one or more UI elements to a specific UI widget at runtime.
- saving an ActiveRecord model in various ways based on conditionals in a Rails controller.
- adding additional information to data streams by pre/appending with additional stream data.

Implementations of Decorators in Ruby
There are several ways to implement the decorator pattern in Ruby, but I cover my 4 favorite ways:
- Class + Method Missing decorator
- Module + Extend + Super decorator
- Plain Old Ruby Object decorator
- SimpleDelegator + Super + Getobj decorator

Class + Method Missing Decorator
The benefits of this implementation are:
- can be wrapped infinitely using Ruby instantiation.
- delegates through all decorators.
- can use the same decorator more than once on the same component.
- transparently uses component’s original interface.

The drawbacks of this implementation are:
- uses method_missing.
- the class of the decorated object is the decorator.

Sample example

sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
module Decorator
  def initialize(decorated)
    @decorated = decorated
  end

  def method_missing(meth, *args)
    if @decorated.respond_to?(meth)
      @decorated.send(meth, *args)
    else
      super
    end
  end

  def respond_to?(meth)
    @decorated.respond_to?(meth)
  end
end

class Coffee
  def cost
    2
  end
end

class Milk
  include Decorator

  def cost
    @decorated.cost + 0.4
  end
end

class Whip
  include Decorator

  def cost
    @decorated.cost + 0.2
  end
end

class Sprinkles
  include Decorator

  def cost
    @decorated.cost + 0.3
  end
end

Whip.new(Coffee.new).cost #=> 2.2
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost #=> 2.9

# Factory class
class CoffeeFactory
  def self.cappuccino
    Sprinkles.new(Cream.new(Milk.new(Coffee.new)))
  end
end

CoffeeFactory.cappucino.kind_of? Coffee #=> true

Module + Extend + Super Decorator
The benefits of this implementation are:
- it delegates through all decorators.
- has all of the original interface because it is the original object.

The drawbacks of this implementation are:
- can not use the same decorator more than once on the same object.
- difficult to tell which decorator added the functionality.

Sample example

sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Coffee
  def cost
    2
  end
end

module Milk
  def cost
    super + 0.4
  end
end

module Sugar
  def cost
    super + 0.2
  end
end

coffee = Coffee.new
coffee.extend(Milk)
coffee.cost   #=> 2.4
coffee.extend(Sugar)
coffee.cost   #=> 2.6

Plain Old Ruby Object Decorator
The benefits of this implementation are:
- can be wrapped infinitely using Ruby instantiation.
- delegates through all decorators.
- can use same decorator more than once on component.

The drawbacks of this implementation are:
- cannot transparently use component’s original interface.

Sample example

sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Coffee
  def cost
    2
  end

  def origin
    "Cambodia"
  end
end

class Sugar
  def initialize(component)
    @component = component
  end

  def cost
    @component.cost + 0.2
  end
end

class Milk
  def initialize(component)
    @component = component
  end

  def cost
    @component.cost + 0.4
  end
end

coffee = Coffee.new
Sugar.new(Milk.new(coffee)).cost  #=> 2.6
Sugar.new(Sugar.new(coffee)).cost #=> 2.4
Sugar.new(Milk.new(coffee)).class #=> Sugar
Milk.new(coffee).origin           #=> NoMethodError

SimpleDelegator + Super + Getobj
The benefits of this implementation are:
- can be wrapped infinitely using Ruby instantiation.
- delegates through all decorators.
- can use same decorator more than once on component.
- transparently uses component’s original interface.
- class if the component.

The drawbacks of this implementation are:
- it redefines class.

Sample example

sample.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Coffee
  def cost
    2
  end

  def origin
    'Cambodia'
  end
end

require 'delegate'

class Decorator < SimpleDelegator
  def class
    __getobj__.class
  end
end

class Milk < Decorator
  def cost
    super + 0.4
  end
end

So far so good, Let decorate your way with Decorator Design Pattern. :)

Deploy Ruby on Rails 4 to Heroku on Ubuntu

Ruby on Rails is a popular web framework written in Ruby. In this artical covers using Rails 4 on Heroku. The many step for deploying Rails 4 to Heroku below:

1. Installation heroku environment (www.toolbelt.heroku.com) – if you not yet have
Open your terminal and type command below:

1. wget -qO- https://toolbelt.heroku.com/install.sh | sh
2. gem install heroku foreman
3. heroku login

2. Installation git – if you not yet have
Open your terminal and type command below:

1. sudo apt-get install git-core
2. sudo apt-get install expat openssl zlib1g zlib1g-dev

3. Create Ruby on Rails project
Open your terminal and type command below:

rails new app_name -d postgresql

Go into you project, Open your terminal and type command below:

cd app_name

We will first create a controller called welcome for our home page to live, Open your terminal and type command below:

rails generate controller welcome

Next then add an index page in directory app/views/welcome/index.html.erb

index.html.rb
1
2
3
4
5
<h2>Hello World</h2>

<p>
  The time is now: <%= Time.now %>
</p>

We need to have Rails route to index action. We’ll edit config/routes.rb

routes.rb
1
root 'welcome#index'

Let run the rails app and visiting http://localhost:3000 in your browser, Open your terminal and type command below:

rails server

Then open Gemfile and add gems below at the end:

gem 'heroku'
gem 'thin'
gem 'rails_12factor', group: :production

Then open your terminal and type command below:

bundle install

Rails 4 requires Ruby 1.9.3 or above. Heroku has a recent version of Ruby installed, however you can specify an exact version by using the ruby DSL in your Gemfile by adding ruby “2.1.1” at the end of Gemfile.

ruby "2.1.1"

4. Deploy to heroku
Open your terminal and type command below:

1. cd project_name
2. git init
3. git add .
4. git commit -m “my first commit”
5. heroku create heroku_app_name
6. heroku git:remote -a heroku_app_name
7. git push heroku master

Each time you wish to deploy to Heroku
Open your terminal and type command below:

1. git add -A
2. git commit -m “commit for deploy to heroku”
3. git push -f heroku

So far so good, You now have your first application deployed to Heroku. The next step is to deploy your own application. :)

Useful Best Coding in Ruby on Rails Project

While a lot of techniques and libraries have come and gone as the community’s preferred way of doing something, there are some best practices that remain, and can lead to writing the clean code, most secure and maintainable Ruby on Rails code possible.

Listed here there are the most popular and useful best coding you can use as a Ruby on Rails developer:

Fat Model - Thin Controller
The most important ways to write clear and concise cod in Ruby on Rails is “Fat Model - Thin Controller”. Model and Controller are parts of MVC(Model - View - Controller), many logic should go in the Model, and Controller is a nice interface between the view and Model.

In priactice, We should move any logic that isn’t about the response(setting a flash message, redirect, render view) to the model instead of the controller, anyway we can reuse it where possible and make it possible for testing outside of the Controller.

Let look at sample example we have code in brands_controller.rb:

brands_controller.rb
1
2
3
def index
  @brands = Brand.joins(:products).where('products.category_uuid = ?', 'AA43D840-C70B-11E3-9C51-B888E33867FC').uniq
end

We can refactor it like this:

brands_controller.rb
1
2
3
def index
  @brands = Brand.find_brands_by_category('AA43D840-C70B-11E3-9C51-B888E33867FC')
end

Then we can move the logic into model brand.rb:

brand.rb
1
2
3
def self.find_brands_by_category(uuid)
  Brand.joins(:products).where('products.category_uuid = ?', uuid).uniq
end

With the methods Brand.find_brands_by_category, we’ve not only made it simpler to test our code, we’ve also made it possible to reuse that same set of conditions in another location. But as we’ll see shortly, even this is still not ideal.

Reusable Scopes and Relations
Ruby on Rails provides a better way – scopes to avoid duplication condition in another methods.

Let look at sample example we have code in brands.rb:

brand.rb
1
2
3
4
5
6
7
8
scope :under_portal, lambda{ |portal_uuid| where(portal_uuid: portal_uuid) unless portal_uuid.blank? }
scope :under_listing, lambda{ |alias_id| where(listing_alias_id: alias_id) unless alias_id.blank? }
scope :under_category, lambda{ |category_uuid| where(category_uuid: category_uuid) unless category_uuid.blank? }
scope :under_brand, lambda{ |brand_uuid| where(brand_uuid: brand_uuid) unless brand_uuid.blank? }

def self.set_scope(portal_uuid, listing_alias_id, category_uuid=nil, brand_uuid=nil)
  self.under_portal(portal_uuid).under_listing(listing_alias_id).under_category(category_uuid).under_brand(brand_uuid)
end

Virtual Attributes
If you find that you’re manipulating data before passing it to a model (for example, converting the type of an object), it’s likely time you started structuring your code to take advantage of virtual attributes.

Virtual attributes are a very simple idea—essentially, all you’re doing is defining your own getter and setter methods.

Let look at sample example we have code:

brand.rb
1
2
@user = User.new(params[:user])
@user.first_name, @user.last_name = params[:user][:full_name].split(" ", 2)

We could remove the second line, and instead add the following to our User model:

brand.rb
1
2
3
def full_name=(value)
  self.first_name, self.last_name = value.to_s.split(" ", 2)
end

Use the Built-in Ruby Duck Typing Methods
Ruby uses several conventions that can make development easier like implementing a to_s instance method on an object will give you a standard way of getting a string representation of your object.

By implementing these standard type conversions—in addition to to_s, there’s also to_i for integers, let have a look at the following string interpolation:

brand.rb
1
"Hello there, #{user.name}"

Use Non-database-backed Models
Although models in Rails are mostly based on ActiveRecord::Base or some other type of object mapper for a database, it’s important to remember that in MVC, the M isn’t restricted to database-backed models.

Using non-database-backed models can help to organize logic which might otherwise become muddy. For example, there are libraries that give you anActiveRecord-like interface for contact form emails.

When it comes time to interact with these models in your controller code, your code will be that much cleaner, as you can use the exact same approach as with database-backed models.

Package Your Code into Gems
I you’ve used Ruby on Rails, you’ve noticed the wealth of rubygems available to Rails developers. When you write code you think is general enough—which usually just means you’ve written it more than once before in another application, let extract it into a gem suitable for a wider range of purposes.

So far so good, there are hundreds of coding practices or techniques that can make your life as a Ruby on Rails developer easier, but I’ve tried to pick out some. :)

Gems for Helping Speed Up Your Ruby on Rails Application

1. rails-footnotes
Description: This gem allows you to display footnotes in your application on pertinent information such as database queries, request parameters, etc. You can also create your own custom footnotes for objects in your application.
Helping: It’s helpful for debugging your application and showing you how long your database query took.
Source: https://github.com/josevalim/rails-footnotes

2. bullet
Description: This gem watches your database queries and alerts you when it thinks you should use eager loading, when you’re using eager loading unnecessarily, and when to consider using counter cache.
Helping: Unnecessary database queries slow down your application’s performance. Using eager loading and counter cache are two easy things you can implement for a performance boost. For high traffic websites, database queries can be the bottleneck for performance.
Source: https://github.com/flyerhzm/bullet

3. request-log-analyzer
Description: This gem outputs a performance report based on your application’s database request log file(s). It includes metrics such as average server time (the average time a server needs to respond to a user request) and cumulative server time (the sum of all the server time needed to handle all the requests for a given action on the server, i.e., the “load” on a server).
Helping: It uses your log files to tell you how your server is responding to database requests and points you in the direction of code to optimize in your application.
Source: https://github.com/wvanbergen/request-log-analyzer

4. ruby-prof
Description: This is a code profiling tool for MRI ruby implementations. It can generate graphical reports and gives information on call times, memory usage, and object allocation.
Helping: It can help you figure out where your “slow code” is in your rails application.
Source: https://github.com/ruby-prof/ruby-prof

5. rack-mini-profiler
Description: This is originally a .NET tool ported over to Ruby that displays a speed profile badge on each html page you navigate to.
Helping: If a page feels “slow”, MiniProfiler can give you a good idea of where the bottleneck is. It also lets you know which “sessions” you have not seen and displays them to you the next time you access your user interface. It allows you to easily see how much time you’re spending on database queries versus other non-SQL related bottlenecks.
Source: https://github.com/MiniProfiler/rack-mini-profiler

Using Strong Parameters With Fields for & Nested Forms in Rails 4

With strong_parameters becoming the standard way of handling security in Rails 4, I played around with it. It works great except the documentation isn’t clear on how to handle nested forms inside Rails, specifically with the accepts_nested_attributes_for in the model and fields_for in views.
So far so good, let take a look a short example below.

account.rb
1
2
3
4
class Account < ActiveRecord::Base
  has_many :people
  accepts_nested_attributes_for :people
end
person.rb
1
2
3
class Person < ActiveRecord::Base
  belongs_to :account
end
accounts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class AccountsController < ApplicationController
  def new
    @account = Account.new
    @account.people.build
  end

  def create
    @account = Account.new(new_account_params)
    if @account.save
      respond_to do |format|
        format.html {redirect_to root_path, notice: "Account created successfully."}
      end
    end
  end

  private
  def new_account_params
    params.require(:account).permit(:id, :name, people_attributes: [:id, :email, :password, :password_confirmation])
  end
end