Main Advantages of Ruby on Rails Usage

Main Advantages of Ruby on Rails Usage

Ruby on Rails (RoR) is a compact and effective way to build web applications. Each platform has advantages and disadvantages that make sense in light of each company’s target market. The main advantages of Ruby on Rails usage are:

1. High Speed of Development
For example, site development that would traditionally take about 2-3 months can commonly be launched much quicker with Ruby on Rails. This time savings results from a few factors: a leaner code-base (fewer lines of redundant code) and a modular design (re-using existing components rather than building everything from scratch). As such, after launching the site, modifications can be made more quickly as well.

2. Cost-Effectiveness
As Rails sites can be built and modified quickly, this is a really cost-effective way to create and maintain the website — without compromising the quality, performance, or scalability of your site.

3. Flexibility
There are lots of gems (already built components of specific functionality available); re-using them rather than building everything from scratch provides a lot of different bricks to build the application and extend its functionality.A variety of plugins are available to solve just about any functional challenge you may need for your project. Additionally, Rails is an ideal way to build custom database solutions at a fraction of the usual time and expense.

3. Flexibility
There are lots of gems (already built components of specific functionality available); re-using them rather than building everything from scratch provides a lot of different bricks to build the application and extend its functionality.A variety of plugins are available to solve just about any functional challenge you may need for your project. Additionally, Rails is an ideal way to build custom database solutions at a fraction of the usual time and expense.

4. High code quality
The Ruby language and Ruby on Rails framework are under active development and support. New features, ideas are introduced quite often. Security updates and fixes are released regularly. A large body of books, blog entries and experiences are also shared online to learn from.

5. Industry support
There are professional hosting support companies, (Heroku, EngineYard). experienced consulting companies, two primary cloud-based offerings, and help with development and deployment and more. Both provide an easy-to-scale, managed hosting environment. Both are built on Amazon EC2 and offer contrasting approaches and features that will appeal to different audiences.

Top 8 Ruby on Rails Websites

How Technology Company Make Money?

If you are curious to know which sites are built with Ruby on Rails, then this article is for you. In a previous blog we have mentioned that startups tend to choose Ruby on Rails for a variety of reason. Same reasons reflect here. These 8 following sites use the framework or at least these were built with Ruby on Rails initially.

TWITTER
Twitter is the most popular micro blogging platform in the world. It was envisioned by Dorsey as the sms of the internet. Twitter was first developed in 2006 with public release in 2007. It was developed in Ruby on Rails. Later it shifted its framework due to scalability. Like we said, startups have some special interest in Ruby on Rails.

How Technology Company Make Money?

SHOPIFY
Shopify is SaaS e-commerce platform. Basically, the merchants subscribes and uses Shopify for selling their product online or in store. Shopify was developed by Lütke in Ruby on Rails. He spent two months to develop the e-commerce platform for their snowboarding website. Interestingly, he did it because he was very dissatisfied with the existing platforms. In 2006, Shopify opened up to merchant and began enjoying significant growth.

How Technology Company Make Money?

GROUPON
Groupon is a deal of the day platform that issues discounted gift certificate a buy can use at variety of stores. Groupon was initially build with Ruby on Rails. It has enjoyed significant growth and now has 3 billion+ market capitalization. However, its business model has been heavily criticized since it inception. The criticism has been further bolstered by steady decline in sales and the ousting of the Founder-CEO Mr. Andrew D. Mason.

How Technology Company Make Money?

BLOOMBERG
Bloomberg is a private software, data and media company. It currently employs 15000 employees. Bloomberg provides analytical and stock trading platform, data and news services to companies through Bloomberg terminal.

How Technology Company Make Money?

SOUNDCLOUD
SoundCloud is a social platform for sound. It is like audio youtube where anybody can upload any sound or tunes and share them publicly or privately. Today, everyone is on multiple social platform. This has added a new dimension to SoundCloud. It is growing everyday and becoming a concern for other paid platform like iTunes and Google Play.

How Technology Company Make Money?

SQUARE
Square is making commerce easier for both enterprises and consumers. It was co-founded by twitter.com co-founder Dorsey. It makes credit card readers and stands that are attached with phones and tables. Users swap cards through these readers and make purchases.

How Technology Company Make Money?

GITHUB
The hub is the social platform for programmers. Git works a repository where coders push codes and conduct review. It is a leading website for code share. If you are a programmer/ developer applying for a job, many times perhaps you have noticed employers asking for your Github username to see your work. Github significantly facilitates the development of web application.

How Technology Company Make Money?

SLIDESHARE
Another site built with Ruby on Rails is Slideshare. Slideshare is one of the most popular education and e-learning platform. It hosts different presentation slides and documents from users. Headed by CEO and Co-founder Ms. Rashmi Sinha, Slideshare is growing in popularity every day. It supports PowerPoint, PDF, Keynote and OpenDocument and also it hosts variety of documents from users.

How Technology Company Make Money?

The article merely introduces the sites, does not go into technicalities. The purpose was to show you that there are many strong web platform that use the Ruby on Rails. If you are interested to use Ruby on Rails for your next project, you can choose Ruby on Rails and for that

How Technology Company Make Money?

How Technology Company Make Money?

Have you ever wonder how the companies that offer free services make money? Such as Instagram, Evernote, Facebook, Twitter, LinkedIn, Google Maps, so on… or if it is even profitable to keep free users using their services. We would go through several revenue models and hopefully, it will throw you some light next time you decide to roll your own startup.

Revenues Models
Let’s start first giving some perspective what models are actually giving the most revenues. In 2013, App Store, reported that free apps brought the 71% of the revenue! Even more than paid apps… how’s that even possible?

Ok, let’s discuss some revenue models to understand this. There are 8 main models.

Freemium: apps are free to download and use. However, quite often some different features are sold separately (e.g. new levels, specialized functions, remove ads, more capacity, and so on). E.g. Pandora, Hulu, Google Docs.

Premium: users paid upfront a fixed price for the application. After you pay for it, you are able to download it. Usually new software updates are free. E.g. MS Office 365.

Subscription: users paid a fixed price which is automatically charged every certain time. Magazines in the iOS Newsstand are a good example of this subscription based model. Subscriptions have generally lower prices than premium accounts. E.g. Netfix.

Freemium is not as “free” as it might seem in the surface, there are indirect ways of getting revenues from it.

Advertising: the application/service is free to use, but it contains ads or interruption banners for an couple of minutes in order to raise revenue. This model is usually applied along with freemium apps and to remove the ads users have to pay a subscription. E.g. Spotify.

Selling data: user information and behavior inside the application is sell to interested 3rd-parties. Usually used with freemium apps and specified in the terms of used.

Transaction: the application is free to use generally and charges a percentage or fixed fee with every users’ transaction made. For example, it allows you to publish your item on their site for free but when you sell it, it charges you a fee. Or publish a project in a site and when it reaches certain goal a percentage fee is applied. E.g. eBay, Kickstarter.

Online lead generation: collects user’s information sometimes in an exchange of a product or service and then resell the information to companies interested indirectly. It’s different from the selling data model because the information is not sold to 3rd party directly, but indirectly. Influencing users desitions based on 3rd party companies affiliated and users’ interests, likes and behaviors. E.g. Mint, LinkedIn.

Donations: (it’s self-explanatory) Services/apps are free, but it encourages users to contribute throughout donations to support the development.

After reading these, you might have more clues why free apps are so much win nowadays. They helped to create those million-dollar-per-day games! (remembered FlappyBird, Candycrush, Farmville…) In a market where there is enough competition, having a free option will take you to large numbers of users quicker and broader, because of the low barrier to entry. For instance, Whatsapp had at certain point 10k of daily downloads, after moving it to $1 it download rate drops 10 times, they finally opted for yearly subscriptions.

Subscription-based revenue are also a model worth doing a special mention. It brings a steady flow of income to companies and usually comes in different tiers to fulfill users need. But, it has to be flexible enough, because it might limit hard core users which might be willing to pay more for taking the product to a new level.

How does Instagram make money?
Freemium: Before selling to Facebook they were not making money. They are trying to incorporate Ads.

How does Facebook make money?
Advertising & Freemium: Advertising is the main source of revenue but also some small percentage comes from payments, web apps and other sources.

How does Whatsapp make money?
Freemium & Subscribers: The company is based on Freemium model for firt year. Later, it has a subscription of $1 per year.

How does Twitter make money?
Advertising & Freemium: Mostly on corporate advertising and payments from ‘promoted’ tweets.

How does Kickstarter make money?
Transactions/Royalties: Charges a 5% for successfully funded projects.

How does Skype make money?
Freemium & Subscribers: Skype-to-skype calls are free, but users can buy additional features.

How does Groupon make money?
Freemium & Transactions/Royalties: Groupon takes charges a fee to seller for every deal sold. It’s one of the fastest growing company in the world. Going from $30.5 million in year one to $713.4 million in year two.

How does Mint make money?
Lead Gen: Mint get paid a small fee when user switch to a new bank or company.

How does Linkedin make money?
Advertising, Freemium, Subscribers & Selling Data: Sells user’s data to companies and recruiters.

How does Amazon Kindle make money?
Premium: Amazon loses money with Kindle but at the same time makes money selling digital content on it.

How does Microsoft Xbox Kindle make money?
Advertising, Freemium, Subscribers, Premium & Transactions/Royalties: Xbox console and games cost money (premium), charges $50 annually (subscribers) in addition to ads.

How does Stack Overflow make money?
Advertising: Ads, banners and sponsored results.

How does Netflix make money?
Subscribers: Just subscribers.

How does Pandora make money?
Advertising, Freemium & Subscribers: For free users presents adds, for subscribers does not.

How does Pandora make money?
Advertising, Freemium & Subscribers: For free users presents adds, for subscribers does not.

How does Spotify make money?
Advertising, Freemium & Subscribers: It has been reporting loses for a couple of years due to royalty payments.

How does Firefox make money?
Transactions/Royalties: Most of the income comes from royalties from the Firefox search box. Their search partners includes Google, Bing, Yahoo, Yandex, Amazon, eBay and others. Also donations and grants.

How does Craigslist make money?
Advertising, Freemium & Transactions/Royalties: Ads and charging users for posting in selected categories.

How does Dropbox make money?
Freemium, Subscribers & Transactions/Royalties: A fixed capacity for free, to increase it users have to subscribe.

How does Google make money?
Advertising: Ad products is their main source of revenue (AdSense and AdWords).

How does Shopify make money?
Subscribers & Transactions/Royalties: Ad products is their main source of revenue (AdSense and AdWords).

How does Airbnb make money?
Subscribers & Transactions/Royalties: Charge to travelers a fee of 6-12% and hosts pay a 3% for every booking on their site.

How does Zynga make money?
Advertising & Freemium: Zynga makes money through people purchasing credits for games and also throught partnerships.

How does World Of Warcraft make money?
Advertising & Subscribers: Charges $15 per month to users. They also sends expasions packs and discs.

How does Hulu make money?
Advertising & Subscribers: Free service has Ads, limitations and restrictions, which are removed for subscribed users.

So far so good, That it!!! See ya!!! :)

5 Tips to Scale Your Ruby on Rails Application

5 Tips to Scale Your Ruby on Rails Application

There are lots of resources on the web that explain how to scale web applications and how to scale Rails. Here’s a quick summary of just five of the basic strategies for a scalable Ruby on Rails web application. Some of them are specific to Ruby on Rails; others generalize to any shared-nothing application server architecture.

1. Cache, cache, cache and More Cache
Cache at the client and use Ajax libraries like JQuery to stream in data to the browser on demand. Use gateway /reverse proxy caches to cache HTTP responses at your website, and learn how to use expiration and etags. Take full advantage of Rails’ built-in action, page and fragment caching. Use memcache to cache results that you’d otherwise pull from your database.

2. Segregate Data and Data Serving
Don’t munge all your data storage into a single database “for convenience.” Datasets that are independent should go into separate databases. Serve static assets from a separate tier, or use Amazon S3 or a CDN like Akamai to serve those assets. It’s more expensive, but it simplifies scaling. Relational databases scale up, not out, so sit down and have a heart to heart talk with your DBA over whether you really need a relational data model for all your data stores. Maybe you can get away with a simpler key-value data store for some of your simpler data. There are ruby clients, so use Hadoop for scaling the storage and analysis of large amounts of unstructured data. Also know the scalability limitations of whatever file system you’re using. If you have heavy data reporting needs, do your reporting from a copy of your main database, not from your production database.

3. Minimize & Handle External Dependencies
Watch for dependencies on external services like ad serving networks or RSS feeds. If a service isn’t responding or can’t handle your growing request load, make sure that you have a fallback strategy.

4. Tend Your Database and Your Job Handlers
Any ORM, including Rails’ ActiveRecord can generate SQL queries that cause database performance issues. Make sure you’re looking at your slow query log after each major integration to make sure you don’t have “missing” database indices, and haven’t written inappropriate find-all’s in your Rails code. Scrub your database periodically for indices that are no longer being used. Similarly, watch the resource consumption of your background and scheduled jobs. As your user base grows jobs can start to overlap, and daily log processing can start to take more than 24 hrs! This kind of thing can sneak up on you easily. Ideally, segregate your jobs in a separate tier. And, as you grow, look at moving to a message based job handler.

5. Shard Your Unavoidably Relational Data
At high scaling levels, your MySQL database will have to be sharded. Sharding involves breaking up your datasets into independent pieces based on a key. For many consumer-oriented Rails sites, that can mean sharding based on userid’s, but other sharding schemes use data-age, or access-frequency (if that’s predictable).

IP Geolocation in Ruby on Rails Application

IP Geolocation in Ruby on Rails Application

Sometimes it can be useful to find a user’s physical location in our Rails application. For instance, maybe we want to send a special Happy Holidays to users of a particular country. IP address geolocation lets us do exactly that. With IP address geolocation you can get a pretty good idea of where the customer is accessing your site from as long as they aren’t using a proxy server or some other means of obscuring their IP address. In this article we will show you how to utilize the Maxmind GeoIP database to look up the location of just about any IP address. Let’s get started.

Setup Rails Application
To utilize the IP address geolocation functionality, we first need to add the geoip gem to our gemfile. Open up your gemfile and add in the code listed below:

Gemfile
1
gem 'geoip', '~> 1.4.0'

Great, now let’s run a bundle install to install the gem.

1
bundle install

Now we need to download the GeoIP database for use with the geoip gem. A free one can be downloaded at this link, or you can use the paid version if you have a subscription. Once downloaded, extract the compressed archive and place the .dat folder contained within in the root directory of your Rails app.

Great, now let’s create a controller so that we can play around with the GeoIP functionality. Run the commands below to create a controller called GeoIpRequest:

1
rails g controller geo_ip_request new create

Next, open up your routes file and modify it so that it looks like the code listed below:

config/routes.rb
1
2
3
4
5
Rails.application.routes.draw do
  resource :geo_ip_request, controller: :geo_ip_request

  root to: "geo_ip_request#new"
end

Great, now open up your GeoIpRequest controller and modify it so that it looks like the code listed below.

app/controllers/geo_ip_request_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class GeoIpRequestController < ApplicationController
  def new
  end

  def create
    require 'geoip'
    @info = GeoIP.new(Rails.root.join("GeoLiteCity.dat")).city(ip_request_params[:host])
  end

  private
  def ip_request_params
    params.require(:request).permit(:host)
  end
end

In the code above, we tell the geoip gem to load our database file and do a search for the host parameter.

Now let’s create our views. Open up the new view for the GeoIpRequest controller and modify it so that it looks like the code listed below:

app/views/geo_ip_request/new.html.erb
1
2
3
4
5
6
7
<h1>GeoIP Example</h1>
<p>Get the country for any ip address or hostname by typing it below and pressing the lookup button.</p>

<%= form_for :request, url: geo_ip_request_index_path do |f| %>
  <%= f.text_field :host %>
  <%= f.submit "Lookup" %>
<% end %>

Great, now finally let’s do the create view. Open up the create view for the GeoIpRequest controller and modify it so that it looks like the code listed below.

app/views/geo_ip_request/create.html.erb
1
2
3
4
5
<h1>IP Address Info</h1>
<b>IP:&nbsp;&nbsp;</b><%= @info.request %><br />
<b>Country:&nbsp;&nbsp;</b><%= @info.country_name %><br />
<b>City:&nbsp;&nbsp;</b><%= @info.city_name %><br />
<b>Region:&nbsp;&nbsp;</b><%= @info.real_region_name %>

Excellent, now if you fire up your rails development server and and navigate to http://localhost:3000 you will see a form requesting your ip address or hostname. Entering any ip address or host name will show the country, city, and region that ip is from.

So far so good, that’s it!!! that’s all there is to it!!! :)

Code Concerns in Rails 4 Models

Code Concerns in Rails 4 Models

You may have noticed that Rails 4 creates a new folder called concerns. Concerns are pieces of code that allow you to better organize the code that you write. This feature has actually been around for a long time prior to Rails 4, Rails 4 merely creates the folders for you and sets up the environment. In this article, we focus primarily on Rails 4.0, but it should apply equally to 3.2.x or even 3.0.x and earlier.

Here is a simple example, lets say we have a model called user. In this model we would typically have something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
class User < ActiveRecord::Base
  has_secure_password

  def self.authenticate(email, password)
    user = find_by_email(email)
    user if !user.nil? && user.authenticate(password)
  end

  def create_password_reset_token
    logger.warn "Create password reset token code goes here."
    false
  end
end

We can create a a file in the app/models/concerns folder called authentication.rb (app/models/concerns/authentication.rb) and place the following code in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module Authentication
  extend ActiveSupport::Concern

  included do
    has_secure_password
  end

  module ClassMethods
    def authenticate(email, password)
      user = find_by_email(email)
      user if user && user.authenticate(password)
    end
  end

  def create_password_reset_token
    logger.warn "Create password reset token code goes here."
    false
  end
end

Now, lets refactor the User model to use the new code. Change the users model (app/models/user.rb) so that it looks like this:

1
2
3
class User < ActiveRecord::Base
  include Authentication
end

Now if you start the rails server and attempt to authenticate, you’ll notice that the functionality hasn’t changed at all. That’s the idea! You can use this method for organizing and DRYing up your code.

The extend ActiveSupport::Concern tells rails that we are creating a concern.

The code contained within the included block will be executed within the context of the class that is including the module. This is perfect for including functionality provided by 3rd party gems, etc.

Next you will notice the module ClassMethods block. The code contained within this block will be added to the Class itself. For example, the code above adds an authenticate function to the User class. This allows you to do User.authenticate(email, password) instead of User.find_by_email(email).authenticate(password).

Finally you will see the last bit of code, the create_password_reset_token function. Code not included in the ClassMethods block or the included block will be included as instance methods. For example, You could do @user = User.find(params[:id]) and then do @user.create_password_reset_token to create a password reset token for the specified user.

Now, all of this is great, but what benefit do you get from organizing your code in this fashion? Well, lets look at a good example of how utilizing this functionality of Rails can save you time and make your code much cleaner. Lets say we have a number of different models, BlogPosts, Articles, Comments, etc and we want to add tagging functionality that will allow the user to tag each object as something. Utilizing concerns we can quickly and easily do this:

1
2
3
4
5
6
7
8
9
10
11
12
module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, as: :taggable, dependent: :destroy
    has_many :tags, through: :taggings
  end

  def tag_names
    tags.map(&:name)
  end
end

In this simple example, you’ll see that simply including Taggable on your modules will (with the database structure in place of course) make your models taggable. This code can quickly and easily be spread upon as many models as needed. Well that’s it! Concerns are a great way to keep your code organized and DRY.

So far so good, That it!!! See ya!!! :)

Awesome jQuery Tricks

Awesome jQuery Tricks

As we all know, jQuery is an awesome library and has transformed the internet as we know it. In this article we will cover 5 extremely useful jQuery tricks that you can use in your sites. Let’s get started.

Gracefully Degrade Broken Images
Broken images can be a pain to deal with. They degrade the user experience and can be difficult to find without scanning your site regularly with a 3rd party tool. Luckily it’s easy to substitute broken images with an image that you specify using jQuery. the error callback of an image gets fired any time an image can’t be successfully loaded by the browser. For example:

1
2
3
$('img').error(function(){
  $(this).attr('src', 'images/missing.png);
});

The code above would replace any broken images with an image in the images folder called missing.png. You could also do something like make an AJAX request to your server to log the location of the broken image.

Wait For an Image to Be Loaded
Sometimes you need to wait for an image to be loaded before continuing to process events. This is most often useful with libraries like the jQuery Masonry library, where images can affect the size of the overall content. Fortunately this is easy with the load callback. For example:

1
2
3
$('img').load(function() {
  // Do stuff here...
});

The above code would wait for the image to be loaded and then execute the code specified in the callback.

Zebra Stripe a Table
Sometimes we want our tables to alternating odd/even colors. While this is possible using CSS3, older browsers don’t support most CSS3 features. Using this script allows our tables to be striped across all browsers.

1
2
3
$('table tr:even').css('background', '#f7f7f7'); // Strip every even row
$('table tr:odd').css('background', '#f7f7f7'); // Stripe every odd row
$('table > tbody > tr:even').css('background', '#f7f7f7'); // Only stripe the table body

The above code will do striping as noted in the comments.

Preloading Images
If your page uses a lot of images that aren’t visible initially, it might be worth it to preload them. This simple script listed below does exactly that.

1
2
3
4
5
6
7
$.preloadImages = function() {
  for (var i = 0; i < arguments.length; i++) {
    $("<img />").attr("src", arguments[i]);
  }
}

$.preloadImages("images/myimage1.jpg","images/myimage2.jpg");

Detect Mobile Devices
Sometimes we need a ‘check all’ checkbox for our web pages that selects every checkbox in a fieldset. The code below lets you easily accomplish this.

1
2
3
$('.checkall').click(function () {
  $(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails With Bootstrap-Sass

Ruby on Rails with Bootstrap-Sass

Twitter Bootstrap is an insanely popular CSS framework that is used to quickly and easily throw together great looking websites. Many websites (including this one) are built on this framework, and with good reason; the power and ease of use rival that of most other frameworks.

In this tutorial we will show you how to add the framework using the bootstrap-sass gem. We will also show you how to override the bootstrap styles using the various scss variables provided by the bootstrap framework. Finally we will show you how to use the will_paginate-bootstrap gem to style your pagination using bootstrap’s pagination styles.

Setup Project
In an existing or new project, add the following line to Gemfile:

Gemfile
1
gem 'bootstrap-sass', '~> 2.3'

Run a bundle install and start your rails server. Now that the gem is installed you are ready to to start using bootstrap.

The first thing we will need to do is create a new SCSS file to store our bootstrap configuration. Create a file called bootstrap_config.scss in the app/assets/stylesheets folder. This file will be used to store bootstrap specific configuration. Next, we will need to tell Rails to actually include bootstrap in this file. Open app/assets/stylesheets/bootstrap_config.scss and add the following line:

app/assets/stylesheets/bootstrap_config.scss
1
@import "bootstrap";

If you want a responsive layout, also add the following line:

app/assets/stylesheets/bootstrap_config.scss
1
@import "bootstrap-responsive";

This will include bootstrap in your application. Now, any views you create will automatically include bootstrap as long as they use the main application layout. We aren’t quite done yet though, if you are on Rails 4 (Rails 3.2 users don’t need to do this) you will need to perform one more step. Open up the config/application.rb file and add the following line to your application’s configuration:

config/application.rb
1
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)

This is due to rails no longer compiling images in vendor assets by default.

Now go ahead and create a controller and try it out. If you aren’t familiar with the framework itself, the absolute best place to learn about it is at The Official Twitter Boostrap Site. That’s all there is to setting it up!

Bootstrap Variables
The bootstrap-sass gem, much like it’s official LESS-based cousin, has a number of variables that you can override to change the look and feel of various styles. Lets try it out. Suppose we want to change the background color of our website. To do this we just need to open up app/assets/stylesheets/bootstrap_config.scss and add the following line to the very top of the file:

app/assets/stylesheets/bootstrap_config.scss
1
$bodyBackground: #e0e0e0;

Now, if you refresh the page you will notice that the body background has changed to a light gray color.

Will Paginate
One pitfall that rails users often run into is utilizing will_paginate in a twitter bootstrap project. Luckily the will_paginate-bootstrap gem makes this very easy. Add the following line to your gemfile and then run a bundle install and restart your rails server:

Gemfile
1
gem 'will_paginate-bootstrap'

Now, open up the view where you are using will_paginate, find any will_paginate lines and add :renderer => BootstrapPagination::Rails to the end of them so they look like this:

1
<%= will_paginate @products, :renderer => BootstrapPagination::Rails %>

Now if you refresh the page, you’ll see that that will_paginate is now styled using bootstrap.

So far so good, That’s it!!! See ya!!! :)

Enable Compression for Nginx

Enable Compression for Nginx

Using Nginx for your Rails app? Use this trick to speed up your site. If you are using Nginx, you can quickly and easily speed up your site by enabling gzip compression for your application. Gzip compression compresses files and assets before they are sent to the client, resulting in a nice little speed boost. A sample of how to do this is listed below:

nginx.conf
1
2
3
4
5
6
7
8
9
10
11
server {
  listen 80;
  server_name mysite.com www.mysite.com;
  root /opt/mysite.com/current/public;
  passenger_enabled on;
  gzip on;
  gzip_http_version 1.1;
  gzip_vary on;
  gzip_comp_level 6;
  gzip_proxied any;
  gzip_types text/plain text/html text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml;

The gzip types specifies the mime types that will be compressed using the gzip protocol. You can exclude and include other mime types using this particular list. It’s best not to include things such as images and/or media files.

So far so good, That’s it!!! See ya!!! :)

Rails 4 FriendlyId

Rails 4 FriendlyId

In this article we will go over using FriendlyId in Rails 4. It is important to note that the current version of FriendlyId (4.0) does not work with Rails 4. Therefore we will need to use FriendlyId 5.x, which is currently in release candidate status.

First, let’s include the FriendlyId gem in our gemfile.

Gemfile
1
gem "friendly_id", "~> 5.0.1"

FriendlyId no longer overrides finder code by default. Because of this we will need to change the way our controller code works. FriendlyId now exposes it’s functionality via .friendly. For example, to find a post by it’s friendly id, we use something like Post.friendly.find(params[:id]). To get FriendlyId working, you need to modify your controllers to use this behavior. An example is shown below.

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.friendly.find(params[:id])
  end
end

If you have a large site making extensive use of FriendlyId, you can also restore the old finder override behavior. This isn’t recommended though. An example of how to do this is listed below.

app/models/post.rb
1
2
3
4
class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: [:slugged, :finders]
end

Once you’ve added this, finder override functionality should now be restored. For example, the code listed below will now work as before.

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end
end

FriendlyId 5 introduces a new slug candidates feature. This feature allows you to tell friendly id what to do in the case of duplicate slugs. See the code listed below for an example of how to utilize this functionality.

app/models/post.rb
1
2
3
4
5
6
7
8
9
10
11
class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: [:slugged, :finders]

  def slug_candidates
    [
      :title,
      [:title, :id]
    ]
  end
end

The code listed above tells FriendlyId you want to use the slug_candidates method to make the slug unique. It will try the list beginning to last, so in the example above, it will try to generate the slug first using title, and then if a post by that title already exists, it will try again by appending the id.

Some other quick things to note when upgrading to FriendlyId 5:
- The default sequence separator has been changed from two dashes (–) to one dash (-). If you have a url scheme in place using the old way of doing things, you might want to find a workaround.
- FriendlyId no longer uses a numeric sequence to differentiate a conflicting slug. Instead it uses a UUID (example: 2bc08962-b3dd-4f29-b2e6-244710c86106). If you dislike this functionality, you can utilize the new slug candidates feature explained above.