Pages

Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Friday, November 21, 2014

Simple, user-friendly cancel links for your Rails forms



The default Rails view generator includes back links on form-related view templates, so if users change their mind they can easily get out of the form and on to something else. However, these links are static. What do you do if you allow users to access the form from multiple views (say, an index and a show).
Here’s a simple but effective solution I came up with: Instead of passing a static URL, I pass the HTTP referrer environment variable as the location. That way users are taken back to the page from which they opened the form to begin with.
Here’s how it works. Most of the code resides in the application_helper.rb file:
  module ApplicationHelper
    include Rails.application.routes.url_helpers

    def cancel_link
      return link_to 'Cancel', request.env["HTTP_REFERER"], 
        :class => 'cancel', 
        :confirm => 'Are you sure? Any changes will be lost.'
    end
  end
You’ll need to include Rails.application.routes.url_helpers in order to access link_to from a helper method. Then you add the helper method itself, which does nothing more than return a cancel link. Mine uses an old-style :confirm message; you can spruce it up with some less obtrusive if you’d like.
If I need a cancel link in a view, I just add
  <%= cancel_link %>
The result: a flexible, reusable cancel option that’s much more user-friendly.

Friday, January 3, 2014

nil vs empty vs blank in Ruby on Rails

.nil?
.nil? can be used on any object and is true if the object is nil.
.empty?
.empty? can be used on strings, arrays and hashes and returns true if:
  • String length == 0
  • Array length == 0
  • Hash length == 0
Running .empty? on something that is nil will throw a NoMethodError.
.blank?
That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.
nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
.blank? also evaluates true on strings which are non-empty but contain only whitespace:
"  ".blank? == true
"  ".empty? == false
Rails also provides .present?, which returns the negation of .blank?.

Friday, December 27, 2013

ORM for Rails

ActiveRecord: Object-Relational Mapping(ORM) for Rails


  • Object Relational Mapping (ORM): simplify the use of databases in applications.
    • Use objects to hold database records
      • One class for each table in the database
      • Objects of the class correspond to rows in the table
      • Attributes of an object correspond to columns from the row
    • Manage the movement of information between objects and the back-end database.
    • Manage relationships between tables (joins), turn into linked data structures.

Thursday, December 26, 2013

Counter Cache in Rails - Performance Tuning

If you need to display the record count for a has_many association, you can improve performance by caching that number in a column.
Below we have an application that shows a list of projects along with the number of tasks that each project has.

Wednesday, December 25, 2013

Is Ruby on Rails is right choice for your new website?

Ruby on Rails (often referred to as just "Rails") is a framework for building websites that can make it more affordable to create and maintain your site, while simultaneously offering improved performance and faster development times.

Below are some guidelines for determining whether Ruby on Rails would be a good choice for your project.

The benefits of Ruby on Rails
Overall, as a business owner, the three largest benefits you can expect with Ruby on Rails are:
  • QUICKER LAUNCH. Sites that would traditionally take 12 weeks to build can commonly be launched inside of 6 weeks with Ruby on Rails. This time savings results from a few factors: a leaner code-base (fewer lines of redundant code), a modular design (re-using existing components rather than building everything from scratch), and the availability of existing plugins (again, reducing the need to build features from scratch).
  • EASIER CHANGES. After site launch, future modifications to your site (e.g., adding new features, making changes to the data model) can be made more quickly, for the same reasons noted above.
  • MORE COST-EFFECTIVE. Because of the speed with which Rails sites can be built and modified, you spend less money to create and maintain the website — without compromising the quality, performance, or scalability of your site.

Tuesday, December 24, 2013

Convention over Configuration in Rails

Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your BooksController class:
class BooksController < ApplicationController
end
And the following in your routes file:
resources :books

And you have a view file app/views/books/index.html.erb:
<h1>Books are coming soon!</h1>
Rails will automatically render app/views/books/index.html.erb when you navigate to /booksand you will see "Books are coming soon!" on your screen.

Monday, December 23, 2013

Best way to transfer db from one heroku app to another

It's quite common to migrate databases between staging, testing and production environments for Rails Apps. And heroku db:pull/push is painfully slow. The best way I have found so far is using Heroku PG Backups add-on and it's free. I followed following steps to migrate production database to staging server:
1) add pgbackups add-on to production and staging apps
heroku addons:add pgbackups:basic --app production-app
heroku addons:add pgbackups:basic --app staging-app
Since I am only using pgbackups for migration, basic plan is enough for this.

14 Bare Minimum Security Checks Before Releasing a Rails App

When you upload your latest app to a production Web server and open it up to the world, you're really throwing your app to the elements - good and bad. If you don't pay any attention to security whatsoever, you're likely to fall foul of some cracker's nefarious scheme and your users will be complaining when something doesn't work or they're being spammed by geriatric Nigerian clowns with pots of gold to share. But what to do?
Luckily, help is at hand in the shape of the official Ruby on Rails Security Guide, but Irish Rails developer Matthew Hutchinson has trawled through that guide as well as several illuminating blog posts relating to Rails security, and put together a 14 step checklist of "bare minimum" security checks to do before releasing your Rails app.
In summary:
  1. Don't trust logged in users. (Authentication is one thing, authorization to perform certain tasks is another.)
  2. Beware of mass assignments. (Use attr_accessible in your models!)

Sunday, December 22, 2013

How to Change Default Port i.e 3000 in Rails

Append these code lines in config/boot.rb:
require'rails/commands/server'
module Rails
  class Server
    alias:default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port=>3333)
    end
  end
end
Now default port is 3333.
Set this number to any number with 4 digits that you like!!!

Friday, December 20, 2013

How to Optimize Image Uploaded via Paperclip

Here is an another gem to reduce the size of the paperclip uploaded image.
    gem "paperclip-compression","~> 0.1.1"

Usage

    class User < ActiveRecord::Base
             has_attached_file :avatar,
              :styles     => { :medium => "300x300>", :thumb => "100x100>" },
              :processors => [:thumbnail, :compression]
    end
we can optimize this code as:

Boot your Rails development server and console faster than ever.... Use Zeus

How Zeus works?

Zeus preloads your Rails app so that your normal development tasks such as consoleserver,generate, and specs/tests take less than one second.

Install
Install the gem.
gem install zeus

Friday, May 3, 2013

How can you safeguard a rails application from SQL injection attack?

Rails already has the logic built into it to prevent SQL injection attacks if you follow the right syntax. 
Say you are trying to authenticate a user based on their login and password you might be tempted to use a syntax as below:
User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
If an attacker enters ’ OR ‘1’=‘1 as the name, and ’ OR ’2’>’1 as the password, the resulting SQL query will be:
 SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1 
This will simply find the first record in the database, and grants access to this user.
To prevent this type of SQL injection simply use the following format.
  User.where("login = ? AND password = ?", entered_user_name, entered_password).first
OR
User.where(:login => entered_user_name, :password => entered_password).first