×

Get the Blog Updates

Your information will not be shared with any 3rd parties under any circumstances.
Cancel
Image Image Image Image Image
Scroll to Top

To Top

Scroll to Top

To Top

Search Results for: label/Rails Development

25

Apr
2014

No Comments

In Ruby on rail

By Srikant M.

Top 5 reasons why web development is faster with “Ruby on Rails”?

On 25, Apr 2014 | No Comments | In Ruby on rail | By Srikant M.

Ruby-on-Rails-150x150Ruby on Rails aka “RoR” is an open-source MVC framework built using the Ruby programming language.

It is considered as the epitome of the latest generation of high-productivity, open source web development tool. The growing demand for Ruby on Rails has been driven by successful RoR development companies like Andolasoft, who benefit from the speed and agility of building applications in Rails, which results in increased productivity and company growth.

1. Framework built on Agile methodology

RoR is faster because the framework was built based on Agile development methodology, best practices are emulated so web development is done with high quality and speed.

RoR framework includes support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together the different components to enable development of a project or solution.

Sites that would traditionally take 12 weeks to build can commonly be launched inside of 6 weeks with Ruby on Rails, saving you cost close to 50%.

2. Less code writing

It has all the code libraries pre-loaded while creating a rails structure. So you need to write some command, which would execute and generate a skeleton of the application and modules. This is what makes the process of web development faster.

Rails is easier because it allows migrations which makes deployment of database changes easier than any open or commercial solution available.

  • Adopting principle of DRY
    It also adopts the principle of “Don’t Repeat Yourself” so all information can be retrieved from a single unambiguous database which tends to easier development.
  • Easy configuration
    A key principle of Ruby on Rails development is convention over configuration. This means that the programmer does not have to spend a lot of time configuring files in order to get setup, Rails comes with a set of conventions which help speeding up development.
  • Modular design
    Ruby code is very readable and mostly self-documenting. This increases productivity, as there is little need to write out separate documentation, making it easier for other developers to pick up existing projects.
  • Designer Friendly Templates
    HTML templates is a core feature of Rails. It allow templates to be composed of a base template that defines the overall layout of the page,the base template is called a “layout” while the individual page templates are “views”. The Rails application retrieves the list of tags from the database and makes it available to the view.The section of the view that renders these category is:
    <%= render :partial => 'category' %>

    This refers to a Ruby partial, a fragment of a page, which is contained in _category.html.erb. That file’s content is:

<h3>categories</h3>
<p class="categorylist">
<%= render :partial => 'categorylist', :collection => @category %>
</p>
  • This generates the heading then refers to another partial, which will be used once for each object in the collection named “categorylist”.

3. Third Party Plugin/Gem Support

Mature plugin architecture, well used by the growing community. Rails plugins allows developer to extend or override nearly any part of the Rails framework, and share these modifications with others in an encapsulated and reusable manner.

Rails community provides a wealth of plugins as Ruby Gems that you simply add to your project Gem-file and install. This significantly accelerates development and maintenance time as you’re not trying to integrate disparate libraries, it’s already done for you.

 

4. Automated Testing

Rails has developed a strong focus on testing, and has good testing suit in-built within the frameworks.

Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.

Rails ships with a built-in test suite. There are many tools available in the market for testing Rails application as mentioned below with other web apps from many different aspects.

  • Rspec
  • Cucumber
  • Test Unit
  • Shoulda
  • Selenium (not really a ruby thing but more of a web thing)

But if you are new to testing we highly recommend you start with learning Rails own testing suite before start using other tools

5. Easier Maintenance

Once site launches, 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.
New features can be added quickly and maintaining applications over time can also be more cost-effective.

If you like this one, you might also like Why Rails framework popular among Ruby developers and The Best practices for Rails App Development .

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

 

 

Tags | , , , ,

11

Apr
2014

No Comments

In Ruby on rail

By Srikant M.

Asynchronous processing with Sidekiq gem in Rails

On 11, Apr 2014 | No Comments | In Ruby on rail | By Srikant M.

Introduction to Sidekiq

Sidekiq gem is used to move long running jobs to background for asynchronous processing.

It is more efficient, with respect to memory usage, than delayed_job and Resque as it uses threads instead of forks.

Need of background process

For example, in a mailing application you need to send emails to a large list of recipients. It will take large time to process with the large list of recipients, which is too long for a User to wait for a response after clicking a link. So, it’s better to move the long running task as the background process by using Sidekiq gem.

Integration of Sidekiq in a Rails application

Steps to integrate Sidekiq gem in a Rails Application :

Step#1 – Add the gem to the Gemfile to use Sidekiq with Active Record

gem 'sidekiq'

You can also view the web interface to manage the background jobs. It isn’t included by default with Sidekiq. To use the web interface we need to add couple of gems to the Gemfile like ‘sinatra‘ and ‘slim

 gem 'sidekiq', '2.9.0'
 gem 'sinatra', '1.3.6', require: false
 
 gem 'slim', '1.3.6'

Run “bundle install” to install the sidekiq gem

Step#2 – Install Redis Server to manage its job queue

Redis is an open-source, advanced key-value pair store. It is often referred to as a data structure server.
Sidekiq uses Redis to manage its job queue.

If you’re running OS X follow the steps as below:
Logged in as a Admin user or add sudo prefix on terminal

$ brew install redis

After installation completed starts the Redis server up with the following command

$ redis-server /usr/local/etc/redis.conf

if you’re running CentOS 5.6 follow the steps as below:

yum install make gcc wget telnet
 wget http://redis.googlecode.com/files/redis-2.2.12.tar.gz
 tar -xf redis-2.2.12.tar.gz
 cd redis-2.2.12
 make && make install

Change the default redis.conf file to daemonize it.

mkdir /etc/redis /var/lib/redis
sed -e "s/^daemonize no$/daemonize yes/" -e "s/^dir \.\//dir \/var\/lib\/redis\//" -e     "s/^loglevel debug$/loglevel notice/" -e "s/^logfile stdout$/logfile     \/var\/log\/redis.log/" redis.conf > /etc/redis/redis.conf

To make management easy, use an init script by using sed to update it.

 Wget https://raw.github.com/gist/257849/9f1e627e0b7dbe68882fa2b7bdb1b2b263522004/redis-server
 sed -i "s/usr\/local\/sbin\/redis/usr\/local\/bin\/redis/" redis-server
 
 chmod u+x redis-server
 
 mv redis-server /etc/init.d
 
 /sbin/chkconfig --add redis-server
 
 /sbin/chkconfig --level 345 redis-server on
 
 /sbin/service redis-server start

Step#3 – Start up the jobs process

There are couple of ways to do this,

  • If application is in development mode, we should use the below rake task file instead.
bundle exec sidekiq

If application is in production mode, then it is preferred to daemonizes the job process and allows multiple background processes to be spawned. To use this, follow the following step:
1. Add gem “daemon-spawn”, “0.4.2” to your Gemfile
2. Run bundle install
3. Run the below command to run it in background

bundle exec sidekiq -d -L log/delayed_job.log

4. You have to pass path of log file while using above command.

Step#4 – Add task to run in background

We need to add the background work in a separate class and store it in a new directory, let’s say app/background_jobs and ensures that it’s auto-loaded by the application.

We need to include the Sidekiq::Worker module.

class NotifyUsers
   include Sidekiq::Worker
   def perform
     User.find_each(is_subscribed: true) do |user|
       NewsMailer.newsletter_mail(user).deliver
     end
   end
end

This class must have a perform method. Add the code that need be to run in the background. Then call NotifyUsers.perform_async method inside the controller which will add the job to Redis and then it will call function perform asynchronously.

For Example:
Before background job in UsersController

class UsersController < ApplicationController
  def send_email
    User.find_each(is_subscribed: true) do |user|
      NewsMailer.newsletter_mail(user).deliver
      flash[:notice] = "Mail delivered"
      redirect_to root_path
    end
  end
end

After implementation of UsersController after adding to background job

class UsersController < ApplicationController
   def send_email
      NotifyUsers.perform_async
         flash[:notice] = "Mail is being delivered"
         redirect_to root_path
      end
   end
end

Conclusion

  • No need to wait for a response after clicking a link to do a big stuff
  • Sidekiq has client-side middleware which runs before a job is inserted into Redis
  • It has server-side middleware which runs before the job is being processed. This middleware retry jobs, log them and handle exceptions

SEE ALSO: How to Install and Configure Redis-Server on Centos/Fedora Server

Sidekiq handles the processing of the jobs after they’re pulled from Redis and multithreaded behavior.

It is also providing a web interface there are a couple of gems that we need to add to the gem file too. To visit the web interface just go to the /sidekiq path

It tells us how many jobs have been processed, the number of failures, the currently-active workers and the number of jobs in queues.

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

Tags | , , ,

22

Sep
2010

No Comments

In Ruby on rail

By Jay Dee

The Era of Ruby on Rails Development

On 22, Sep 2010 | No Comments | In Ruby on rail | By Jay Dee

rails_image1With the advent of Ruby on Rails around 2006, it has revolutionized the sphere of web development. Built on MVC (Model-View-Controller) architecture, this relatively new technology in the field of web development, has appealed to numerous developers. Programmers, who were accustomed to writing thousands of lines codes in technologies like PHP and JAVA, were spellbound by this frameworks agility and features to create a full-fledged database backed application within a few hundred lines of code.
Application which normally would have taken months or even years to complete, can now not only be wrapped up within days and months but also with considerably less number of developers.Rails is backed up by the powerful object oriented language Ruby, on which it is based. It also leverages the extensive patronage of Ruby for meta programming. It makes optimum use of code generation features, which eases out to complete applications and promote agile programming techniques.

Rails development is also unique in the field of web application because it makes use of two key design features which are DRY or “Don’t Repeat Yourself” and CoC or “Convention over Configuration”. Agile Development Methodology, combined with DRY and CoC, not only helps ruby on rails engineer’s to develop dynamic web application economically, in less time & code but also facilitates code reusability in the development process.

Andolasoft Inc offers fast and high class Ruby on Rails development to startup and established businesses, groups, etc.

Tags | , ,

11

Jul
2013

No Comments

In Ruby on rail

By Jay Dee

The Best practices for Rails App Development

On 11, Jul 2013 | No Comments | In Ruby on rail | By Jay Dee

Rails_development_new_0912

Introduction:

“Rails” is an amazing framework to develop web applications quickly through its inbuilt helper libraries. However, there are certain best practices that you should follow to get your rails app perform better.

Conventional programming methods:

Most developers love to place the logic inside the controller and use the model for the “Active Record” operation only. This leads to a “Fat controller and skinny model” interface which eventually kills an app’s performance and looses the maintainability of the code. This way, application stops responding when the load is high.

What should be the best practices?

Below, I have mentioned some of the most essential and useful practices that should be followed by every Ruby on Rails developer.

Fat Model, Skinny Controller

Write all the non-response-related logics inside the model with nice and testable methods; and don’t forget to use comments. You should follow the Ruby on Rails motto i.e. “Fat Model, Skinny Controller”. Because the “skinny” controller offers a nice interface between the view and model.

By moving any logic that isn’t about the response (for example, setting a flash message, or choosing whether to redirect or render a view) to the model instead of the controller, not only you can reuse the codes where

possible but you’ve also made it possible to test your code.

Reusable Scopes

A scope is a set of constraints on database interactions (such as a condition, limit, or offset) that are chainable and reusable.

Let’s see a simple example:

def index
@paid_users= User.where(“is_active=? AND is_paid=?”,true, true).order(“name”)
@unpaid_users= User.where(“is_active=? AND is_paid=?”, true, false).order(“name”)

You can change it to this:

def index
@paid_users= User.paid.all
@unpaid_users= User.unpaid.all
end

Then, you can move the logic to your User model, where it might look like this:

scope :paid, lambda { where(“is_active=? AND is_paid=?”,true, true).order(“name”) }
scope :unpaid, lambda { where(“is_active=? AND is_paid=?”,true, false).order(“name”) }

Using the methods User.paid.all and User.unpaid.all, we’ve not only made it simpler to test our code, but also made it possible to reuse that same set of conditions in another location.

You should avoid the use of default_scope because:

  1. You can’t override default scope
  2. default_scope will affect your model initialization

Package Your Code into Gems and Plugins

Writing a particular set code more than once for different applications is exhausting as well as redundant, hence, it is advisable to create a plugin or gem to use it further. It will save your development time and effort.

Manage Your Attribute Access

While creating or updating an object, Rails usually assigns every attribute without checking the data. Validation only prevents the bad data but doesn’t exactly prevent it from overwriting an attribute that we don’t want to change.

To solve this issue, ActiveRecord is implemented which uses two methods: attr_protected and attr_accessibile.

Using attr_protected, you can declare a blacklist of variables you don’t want to be assigned and using attr_accessible, you can declare a list of variables that can be assigned.

By implementing above steps, you could prevent any mass assignment that could occur via your application’s forms; because if the form does not have the field for a given attribute, doesn’t mean a hacker can’t add it to the request.

From a security perspective, using attr_accessible and attr_protected forces you to think about what should be editable and how to protect the ways in which your class’s attributes are set.

Use Non-database-backed Models

In Rails, Model is not restricted to associate with table. To organize application logic, write it down by creating a new model.

Virtual Attributes

If you are manipulating data before passing it to a model, use virtual attributes instead.

Virtual attributes are a simple own getter and setter methods.

For example
To set a user’s name:

@user = User.new(params[:user])
@user.first_name, @user.last_name = params[:user][:name].split(" ", 2)

By using virtual method inside the model

def name=(value)
self.first_name, self.last_name = value.to_s.split(“ ”, 2)
end

Whenever you set the name attribute, your model will automatically set the first_name and last_name attributes for you, even though name doesn’t exist in the database.

Use Translations

Rails i18n framework makes it easy to declare the map of an abstract context to a string. All you need to do is maintain a YAML file of translations, and use I18n.t / t in your code where there is data shown to the use.

I18n is useful to avail your app to more locales.

Using of after_commit callback

Use “after_commit” instead of using after_create/after_update/after_destroy callbacks to start background processes. Because, in relational database, several operations are wrapped in one unit and pass or fail of transaction depends upon all the operations.

If you use after_create/after_update/after_destroy in first model and if any error occurs in the second model then the background process will raise NotFoundError.

Use select in ActiveRecord association

Use select with has_many and belongs_to on Active Record Associations to speed up the query.

For example:

class Patient < ActiveRecord::Base
belongs_to :physician, :select => 'id,name, surname'
end

class Physician < ActiveRecord::Base
has_many :patients, :select => 'id,name, physician_id'
end

Fix N+1 Queries

N+1 Queries is a serious database performance problem. Use “Bullet” gem to avoid N+1 query problem

Conclusion:

Employing the above mentioned Rails best practices would keep the code cleaner and reusable. The application performance would increases tremendously and the maintenance of the code will be easier.

Tags | ,

08

Oct
2013

No Comments

In Ruby on rail

By Srikant M.

Supercharge your Rails app development with “Metric_fu”

On 08, Oct 2013 | No Comments | In Ruby on rail | By Srikant M.

Why we need Metric_fu?

Sometimes we are unaware of unknown complexities in our rails code and it gets messy. Moreover, it reduces application performance, scalability and maintainability.

What is Metric_fu?

Metric_fu is a set of rake tasks and compilation of several different tools that provides reports. This show which parts of your rails code might need extra work. It uses the following built-in tasks to create a series of reports.

  • Rcov – Measures test coverage
  • Flog – Measures code complexity
  • Saikuro – Measures cyclomatic complexity
  • Flay – Finds duplication (both copy/paste and structural)
  • Reek – Spots code smells
  • Roodi – Finds lots of general problems
  • Churn – Identifies files that changes too often
  • Rails best practices – code matric tool
  • Cane -code quality threshold violations
  • HotSpot– Meta analysis of your metrics to find hotspots in the code

Benefits of Metric_fu

  • You can measure the complexity of rails code
  • Creates a “hit list” of most complex methods
  • Reveals hidden issues like bugs and other complexities
  • Examine worst offenders
  • Refactoring complex methods
  • Creates smaller, easier to understand methods

Step#1

  • Add ‘metric_fu’ gem to your gem file
gem "metric_fu"
  • Run “bundle install”
  • Metric_fu will install several other dependencies unless they are already present.
    These include Flay, Flog, Rcov, Reek, Facets and Roodi.

  • Run following command to generate the metrics
  • rake metrics:all

    It will generate a metric of your code in the temp/matric_fu repository,
    it uses a number of other open source project to generate the metric.
    metrics_home_page-1024x551

    Rails_best_pratices_metrics-840x1024

    Code analysis isn’t an exact science and none of the tools shown are perfect in themselves.
    So they should all be used as an aid to help you find complex areas of your code and
    supercharge Rails app development.

    Tags | , ,

    09

    Mar
    2011

    No Comments

    In Ruby on rail

    By Jay Dee

    Ruby Rails Development Sphere & Associated Myths

    On 09, Mar 2011 | No Comments | In Ruby on rail | By Jay Dee

    rorRuby on Rails development is fast changing the norms of web development across the globe. Companies around the world are fast catching up with this magical web development framework for exploring and executing its true potentials; thereby serving their clients with really cost-effective, quick and dynamic Ruby on Rails Applications. Ruby developers and Rails developers are becoming the most sought after skilled professionals, for Software companies to hunt for.

    Ruby on Rails, being an Open Source tool, coupled with fast development life cycle, requires much less resources in terms of Programmers and man-hours; which results in the service provider and client being the ultimate beneficiaries. Silicon Valley based leading Software firm, Andolasoft Inc. is a formidable force to reckon with as far as Ruby on Rails development is concerned. With a vast pool of Programmers as well as Domain Leads, this fairly young Enterprise has carved out many Social Networking Sites, Social Media Marketing web apps. Andolasoft services include but not limited to RoR Development, RoR Application Migration, Social Media Integration, System Administration, Redesigning of Existing Apps, Performance Improvement Related Tasks and Rescue Support.

    Irrespective of all its popularity, RoR also has few myths related to it.

    Applications can be built hundreds of thousands times faster than other technologies: The fact is Rails doesn’t write the code automatically. It just lets the developers work easy by managing certain functionalities; thereby allowing them to focus on other crucial modules. It also manages the laborious part of lifting of user interactive modules. Having said that, such myths reflects a wrong opinion upon customers, whose expectations sometimes become too high for the service providers.

    Even Non-programmers can build web applications: This is by far the silliest perception about Rails development. Although the simplicity of this framework and clean syntax of ruby language assist in quick development, but still experience is required as far as writing code is concerned. Rails developers do need to write new and unique code, apart from using the Rails conventions on top a comprehensive web development framework.

    Tags | , ,

    09

    Oct
    2012

    No Comments

    In Ruby on rail

    By Jay Dee

    Creation of a new Rails App using Refinery CMS

    On 09, Oct 2012 | No Comments | In Ruby on rail | By Jay Dee

    refinerycms-logo1RefineryCMS is a powerful Ruby on Rails CMS. Here I have created a blog-cms application using Ruby 1.9.3 and Rails 3.2.8

    Step#1
    Install the refinerycms gem version 2.0.8 from the terminal

    gem install refinerycms

    Create a new rails application with ‘mysql’ database using command line in the terminal

    refinerycms myblog -d mysql

    It will automatically run the following commands

    bundle install</div>
    <div>rake  db:create db:migrate</div>
    <div>rake  db:seed

    Step#2
    Go to the app on the terminal

    cd myblog

    Step#3
    Start the rails server in the terminal

    rails s

    Step#4
    Open a browser window and navigate to “http://localhost:3000/”
    The signup window pops up to prompt to create your first Refinery user. This is the Superuser of Refinery, who has the ability to create other users.
    That’s it!
    The application runs now.

    Other useful information to customize Refinery CMS application

    • You can change the “Site Name” to a name of your choice currently displaying in the home page

    In “config/initializers/refinery/core.rb”

    config.site_name = “Company Name”

    • You can customize the Design or functionality

    To override files from refinerycms to existing app we have to use the below commands

    rake refinery:override view=file_name

    Here are some examples:

    rake refinery:override view=pages/home</div>
    <div>rake refinery:override view=refinery/pages/home</div>
    <div>rake refinery:override view=**/*menu</div>
    <div>rake refinery:override view=_menu_branch</div>
    <div>rake refinery:override javascript=admin</div>
    <div>rake refinery:override javascript=refinery/site_bar</div>
    <div>rake refinery:override stylesheet=home</div>
    <div>rake refinery:override stylesheet=refinery/site_bar</div>
    <div>rake refinery:override controller=pages</div>
    <div>rake refinery:override model=page</div>
    <div>rake refinery:override model=refinery/page</div>
    <div>rake refinery:override presenter=refinery/page_presenter

    Implementation of other refinerycms engines are also available

    For example:

    Add the gem to your applications Gemfile

    • gem ‘refinerycms-page-images’, ‘~> 2.0.0′
    • Execute bundle install
    • rails generate refinery:engine name

    Example:

    • rails generate refinery:page_images
    • rake db:migrate

    Tags | , , ,

    13

    Jun
    2014

    No Comments

    In Ruby on rail

    By Srikant M.

    Why Refinery CMS is chosen to be best among all other Rails CMS?

    On 13, Jun 2014 | No Comments | In Ruby on rail | By Srikant M.

    Refinery-CMS(1)What is a CMS?

    A content management system or CMS is a computer program that allows a user to publish, edit and modifying of the content through a editor. CMS often used for websites & blogs to avoid the hand coding and provide easy to use interface so that anybody can manage the content without depending on a programmer.

    Here, I want to specify one of the popular Ruby on Rails CMS – RefineryCMS. There are some other CMS available in Ruby On Rails like BrowserCMS, LocomotiveCMS, Radiant CMS, etc…

    RefineryCMS is an open source content management system written in Ruby on Rails with jQuery used as the JavaScript library. It is perfect for creating custom content manageable websites. If you need to quickly create an informational site that can be easily edited, consider using a content management system.

    Key features of RefineryCMS are:

    • 100% free and open source
    • Super simple and easy to use
    • Slick, clean user interface
    • Modular and extendable
    • Design flexibility
    • Multilingual

    RefineryCMS is popular because of following reasons :

    • Built with Ruby on Rails
    • Refinery is the most user-friendly for a non-technical end-user
    • Installing RefineryCMS is very easy
    • Supports creating of custom engines
    • There are tons of engines, plugins and extensions available
    • Strong community for support
    • Easier to integrate into existing rails project or the other way round
    • Includes Devise as authentication
    • Has a pretty admin control panel

    See Also : How to create a form page in Refinery CMS app

    Do you like this blog? I’d love to hear something from you. Thanks for sharing your comments.

    Tags | , ,

    19

    Sep
    2014

    No Comments

    In Ruby on rail

    By Srikant M.

    Rails or Django – which one to choose?

    On 19, Sep 2014 | No Comments | In Ruby on rail | By Srikant M.

    Rails-vs-django-300x300

    Python and Ruby are the most popular dynamic programming languages. Developers are using these two languages for high level application development. Python and Ruby are popular among web developers because of their rapid development cycle.

    Here, I have discussed most important difference between Python and Ruby:

    Philosophy

    Python has been designed to emphasize programmer’s productivity and code readability. The philosophy of Python requires almost everything explicitly defined by a programmer, whereas Ruby allows programmers to reuse the in-built components in development. The philosophy behind Ruby is that programmers should have the flexibility and privilege to write concise and compact code.

    Functional Programming

    Both Rails and Django use object relational mapping to link the application to the underlying database. In Django, the developer is required to explicitly specify each attribute of every class.
    But, In rails, all module attributes are not defined in the class definition. Developer can retrieve all the information from the database based on the class name.
    In Rails database migrations is very easy and in-built compared to Django, as it uses third party library like South.

    Convention over Configuration

    Ruby on Rails defines certain features that make web programming more effective and user-friendly. Convention over configuration (CoC) is one of the important feature of Rails.

    “Convention over Configuration” means a developer only needs to specify unconventional aspects of the application. There are some predefined layout and sensible defaults available in rails projects.

    All components such as models, controllers, and static CSS and JavaScript files are located in standard sub-directories and you just need to drop your implementation files into those directories. CoC saves a lots of time of developers, because in rails you don’t need to write the same code again and again.

    While in Django, you have to specify the path where the component files are located. So the development cycles in Rails are shorter as compared to it’s counterparts.

    Model-View-Controller and REST

    Ruby on Rails is unique because it supports REST protocol. It helps you to organize your application. In Rails, all model objects are accessed and handled in an uniform manner using the standard HTTP verbs like GET, PUT, DELETE and POST.

    CSS, Javascript and images

    Rails has in-built asset pipeline.Rails’ asset pipeline is having feature of minifying, concatenating and compressing Javascript and CSS files. Not only that, it also supports other languages such as Coffeescript, Sass and ERB.
    Django’s support of assets it very amateurish compared to Rails and leaves everything to the developer. Django offers static files, which basically collects all static files from each application to a single location.

    URL mapping

    Both Rails and Django allow for the use of regular expressions to customize the mapping of URLs to controller actions. Both are flexible enough to allow you to create pretty much any mapping scheme you wish.
    But, Rails does automatic URL mapping based on the class and function names within controllers by default.

    Testing

    Testing is very easy in Rails and there’s a much stronger emphasis on it in Rails than in Django.

    Popularity

    Python is generally more widely used than Ruby. Due to the rising popularity of the Ruby on Rails Web application development framework, Ruby’s popularity too has seen rapid growth.

    Both Rails and Django are effective web frameworks powered by efficient programming languages. However, Rails is the best platform for rapid web app development.

    Andolasoft offers quality rails development service. We specialize in developing database driven web application in an efficient and hassle-free way.

    Recommended Blog: Steps to add ‘Elasticsearch’ to Rails App

    Have something to add to this topic? Share it in the comments

    Tags | ,

    10

    Jul
    2013

    No Comments

    In Ruby on rail

    By Srikant M.

    Why Rails framework popular among Ruby developers

    On 10, Jul 2013 | No Comments | In Ruby on rail | By Srikant M.

    Introduction:

    Most companies whether it’s a start-up or an established enterprise have evidently landed to the conclusion that, Ruby on Rails is the most viable option for rapid and cost efficient web app development.

    Ruby on Rails or simply called ‘Rails’ is an open-source, full-scale multilevel web app framework that implements MVC development architecture, for the Ruby programming language and is supported by a strong community around it.

    Let’s take a quick look on the features of ROR:

    Mature Framework

    Ruby on Rails was first released in 2003, which possessed several large and actively maintained APIs those make application development faster, easier and more manageable. One of the best examples is CSRF (Cross Site Request Forgery) protection; using which, you don’t have to do anything to add CSRF. Active Record is an extremely powerful feature in terms of building the usable data models.

    Speed and Development

    Generators/Scaffolding:

    It’s a rapid prototyping tool; Rails’ scaffold will generate a starting point that allows us to list, add, remove, edit, and view things. It will explain the command, the model name and related database table, naming conventions, attributes and types.

    The generated script will produce files of Ruby code that the application can use to interact with the database. It is somewhat less convenient than dynamic scaffolding, but gives the programmer the flexibility of modifying and customizing the generated APIs.

    Gems/Plugin:

    Ruby gems are highly portable chunks of Ruby code that can be used inside any Ruby script or application.

    Rails plugins have the flexibility to hook into every part of Rails, including generators, rake tasks and tests/specs. They are specific to Rails and could not be (directly) used with another Ruby framework like Merb, Sinatra, etc.

    Active Record ORM:

    Object-Relational Mapping (ORM) is a technique that connects the rich objects of an application to tables in a relational database management system.

    Active record pattern is an architectural pattern found in Ruby on Rails that stores its data in relational databases. It relies heavily on the naming in that it uses class and association names to establish mappings between respective database tables and foreign key columns.

    Integrated testing tools:

    Rails features a convenient testing tool, for which, it automatically starts producing the skeleton test code in background whilst you are creating the application models and controllers.

    Rails tests can also simulate browser requests and thus you can test your application’s response without having to test it over browser.

    Some convenient tools for testing Rails application:

    • Test Unit
    • RSpec
    • Cucumber
    • Mocha
    • Flexmock
    • Factory Girl

    Version Control Systems:

    There are numerous version control systems. CVS was the first system widely used in the open-source community. Several years ago, it was largely replaced by Subversion (SVN). And in early 2008, most of the Rails world moved to a newer version control system, called GIT.

    GIT is the usual “best choice” if you are new to Ruby, because nearly all code you’ll have to fetch as examples/libraries will be available via hosted GIT repositories.

    Conclusion

    With Ruby on Railsproviding a programming framework that includes reusable, easily configurable components commonly used for creating web-based applications, it is gaining traction with developers.

    From the recent studies on the job growth trends, it is seen that Ruby on Rails developers are a very hot commodity. Ruby as the language of the cloud, the job market will continue to show high demand for Rails developers. It’s nearly impossible to be an unemployed Ruby on Rails developer.

    RoR_graph_new1-1024x532 (1)

     

    Tags | ,

    22

    Apr
    2013

    No Comments

    In Ruby on rail

    By Jay Dee

    4 Simple Steps to Implement “Delayed Job” in Rails

    On 22, Apr 2013 | No Comments | In Ruby on rail | By Jay Dee

    Rails-123

    A brief Introduction to Delayed_job (or DJ)

    “delayed_job” is a ruby gem which is used to execute the tasks as a background process in Rails environment which in turn increases page rendering speed.

    Delayed::Job (or DJ) is used to asynchronously execute longer tasks in the background.

    Is background process really that important!

    Let’s consider a scenario where a mailing application needs to send emails to a huge list of recipients. In such cases it is obvious to take a longer time while processing such huge lists. This way, the processing time gets too long, which is annoying for the users.

    Hence, it would be wise to move the long running tasks as a background process by using “delayed_job” gem.

    Detailed steps to integrate DJ in a Rails application

    Step# 1 

    • Add the gem to the Gemfile
    • “delayed_job” supports multiple backends for storing the job queue
    • To use “delayed_job” with Active Record use the gem ‘delayed_job_active_record’
    • To use “delayed_job” with Mongoid use the gem ‘delayed_job_mongoid’

    Example

    /Gemfile.rb

    gem 'delayed_job_active_record', '0.4.3'
    • Run “bundle install” to install the “delayed_job” gem

    Step# 2 

    • Generate the related file for the Job run
    • Generate related files required to run the background job by running the following command
    rails generate delayed_job:active_record

    It will add following files to the application

    • A Script named as “delayed_job” inside “/script” folder to run the jobs which are in queue.
    • Migration file to create a table to store the job with the other information such as priority, attempts, handler, last_error, run_at, locked_at, failed_at, locked_by, queue.

    Run the migration file by using the following command

    rails db:migrate

    Step# 3 

    • Start up the jobs process

    There are two ways to do this.

    • If application is in development mode, we would use the below rake task instead.
     rake jobs:work
    • If application is in production mode, then it is preferred to use the “delayed_job” script. This daemonizes the job process and allows multiple background processes to be spawned.

    To use this, pursue the following steps

    • Add gem “daemon-spawn”, “0.4.2” to your Gemfile
    • Run bundle install
    • Create a new file /lib/background_job
    • Copy n paste the below statements in the file
           #!/usr/bin/env ruby
    # -*- ruby -*-
    require 'rubygems'
    require 'daemon_spawn'
    
    RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
    
    class DelayedJobWorker < DaemonSpawn::Base
    def start(args)
    ENV['RAILS_ENV'] ||= args.first || 'development'
    require File.join(RAILS_ROOT, 'config', 'environment')
    
    Delayed::Worker.new.start
    end
    
    def stop
    system("kill `cat #{RAILS_ROOT}/tmp/pids/delayed_job.pid`")
    end
    end
    
    DelayedJobWorker.spawn!(:log_file => File.join(RAILS_ROOT, "log", "delayed_job.log"),
    :pid_file => File.join(RAILS_ROOT, 'tmp', 'pids', 'delayed_job.pid'),
    :sync_log => true,
    :working_dir => RAILS_ROOT)
    
    • Open the console and use the below command as per your requirement
    ruby lib/background_job start
    ruby lib/background_job stop
    ruby lib/background_job restart
    

    Step# 4

    • Add task to run in background
    • In Controller just call .delay.method(params) on any object and it will be processed in the background.

    For Example:
    UsersController before adding to background job

    class UsersController < ApplicationController
    def send_email
    User.find_each(is_subscribed: true) do |user|
    NewsMailer.newsletter_mail(user).deliver
    flash[:notice] = "Mail delivered"
    redirect_to root_path
    end
    end
    end
    

    UsersController after adding to background job

    class UsersController < ApplicationController
    def send_email
    User.find_each(is_subscribed: true) do |user|
    # add .delay method to add it to background process. In case of mail sending remove the .deliver method to make it work.
    NewsMailer.delay.newsletter_mail(user)
    flash[:notice] = "Mail delivered"
    redirect_to root_path
    end
    end
    end
    

    Advantages of implementing above steps:

    • Waiting for a response after clicking a link to do a big stuff is over
    • Just call .delay.method(params) on any object and it will be processed in the background.
    • Job objects are serialized to yaml and stored in the delayed_jobs table, so that they can later be restore by the job runner.
    • It will automatically retry on failure. If a method throws an exception it will be caught and the method rerun later. The method will be retried up to 25 times at increasingly longer intervals until it passes.
    • “delayed_job” gem maintain log by creating a log file “/log/delayed_job.log”

    Here is what we have benefited by using “delayed_job”. – A case study:

    What was the challenge?

    • Prior to implementing delayed_job page load time of job details page in KurrentJobs time  (as shown in below figure) was well over 5 seconds as process of incrementing summation of Like counts of all Social Media sites(Twitter, Facebook, Google+, LinkedIn) and incrementing count of views by getting data from Google analytics was taking considerable amount of time.

    How “delayed_job” helped us?

    • Delayed job is well known for asynchronously executing longer tasks in the background
    • This was achieved by handling executing process of incrementing summation of ‘Like’ counts of Social media sites and incrementing count of # of views(Google analytics) through delayed_job in a different thread and thereby letting the page render faster than ever before.
    • As the above mentioned process separated to run in background asynchronously,the page loading time of the job details page in KurrentJobs reduced from 5 seconds to less than 1 second,  performance stepped-up by 500% .

    Hope you like this. If you have any question, please mention it in comments.

    Tags | ,

    25

    Jun
    2013

    No Comments

    In Ruby on rail

    By Srikant M.

    How to configure Rails application with Puma and Ngnix on CentOS

    On 25, Jun 2013 | No Comments | In Ruby on rail | By Srikant M.

    Rails__new_0912

    Puma is a multi-threaded high performance web server written in Ruby. Currently it is very popular in market as a ruby application server. We can use it for any kind of ruby web application that supports rack. Here, I have mentioned detailed steps to help you configure Rails application with Puma and Nginx on CentOS.

    Steps to install Puma:

    We can install puma via RubyGems.

    1. Append the below line to your Gemfile, if you have Rails 3.0 or above:

    gem 'puma', '~> 2.0'

    2. Then we have to issue the below command to install puma

    # bundle install

    3. Now you can run your application with puma using the below command

    # RAILS_ENV=production bundle exec puma -e production –b unix:///var/run/my_app.sock

    You should see the following outcomes:

    Puma 2.0.1 starting...
    * Min threads: 0, max threads: 16
    * Environment: production
    * Listening on unix:///var/run/my_app.sock
    Use Ctrl-C to stop

    4. Press Ctrl-C and stop the process for now. We will start the server again after installation and configuration of ‘Ngnix’.

    Steps to Install Ngnix:

    1. To install Nginx on CentOS type below commands

    # wget http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
    # rpm -ivh nginx-release-centos-6-0.el6.ngx.noarch.rpm
    # yum install nginx

    Configuring Ngnix:

    1. First we have to create a virtual host file

    #vi /etc/nginx/conf.d/my-NewProject.conf

    2. Now add the below line to your config file (Change fields as your requirement)

    upstream my_app
    {
    server unix:///var/run/my_app.sock;
    }
    server {
    listen 80
    server_name www.example.com; # change to match your URL
    root /var/www/html/my_app/public; # I assume your app is located at this location
    location / {
    proxy_pass http://my_app; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    }

    3.Then we have to restart the Ngnix

    #service nginx restart

    4.After restarting the Ngnix we need to again start puma

    # cd /var/www/html/my_app/
    # RAILS_ENV=production bundle exec puma -e production -b unix:///var/run/my_app.sock
    Puma 2.0.1 starting...
    * Min threads: 0, max threads 16
    * Environment: production
    * Listening on unix:///var/run/my_app.sock
    Use Ctrl-C to stop</pre>
    <pre>

    Now you will be able to browse your application.

    Type the Server Name you mentioned on your virtual host configuration.

    For example: http://www.example.com

    How to run Puma as a demon:

    1. If you want to run puma as a foreground process (daemon) then start puma with –d option with the following command

    # RAILS_ENV=production bundle exec puma -e production -d -b unix:///var/run/my_app.sock

    2.To verify whether puma is running or not we have to issue the below command

    # ps aux | grep puma
    root  19119 13.1  1.3  43276 27792 ?   Sl   21:02   0:01 ruby /usr/local/rvm/gems/ruby-1.9.3-p0@tapas1/bin/puma -e production -d -b unix:///var/run/my_app.sock

    Finally-steps to stop and restart our puma server

    ‘pumactl’ is a command line that helps to stop and restart the application server. It takes parameter from the file where we store the puma process state.

    1.Currently we have to kill the running process of puma by issuing following command.

    pkill –f puma

    2. You can again verify the process is running or not by issuing the following command:

    # ps aux | grep puma

    3.Then start the puma with –S option

    RAILS_ENV=production bundle exec puma -e production -d -b unix:///var/run/my_app.sock -S /var/run/my_app.state --control 'unix:///var/run/my_app_ctl.sock'

    4.Now puma would generate the file /var/run/my_app.state like below content:

    pid: 20937
    config: !ruby/object:Puma::Configuration
    options:
    :min_threads: 0
    :max_threads: 16
    :quiet: true
    :debug: false
    :binds:- unix:///var/run/my_app.sock
    :workers: 0
    :daemon: true
    :worker_directory: /var/www/html/my_app/
    :environment: production
    :state: /var/run/my_app.state
    :control_url: unix:///var/run/my_app_ctl.sock
    :control_auth_token: c0c3983017b972da3318a33349e8ee
    

    5.Now, you can restart and stop your application with ‘pumactl’ using the file /var/run/my_app.state

    a) To restart puma server issue the following command

    bundle exec pumactl -S /var/run/my_app.state restart

    b) To stop the puma server issue the following command

    bundle exec pumactl -S /var/run/my_app.state stop

    Following the above mentioned steps would result you with a clean configuration of Rails application with ‘Puma’ and ‘Nginx’.

    Recommended Reading: New features of Rails4

    Tags | ,

    13

    Dec
    2012

    No Comments

    In Ruby on rail

    By Jay Dee

    Importance of Filter in Rails

    On 13, Dec 2012 | No Comments | In Ruby on rail | By Jay Dee

    Rails1(1)

    In Ruby on Rails development filters play a vital role. Filters are the methods that are executed ‘before’, ‘after’  or  ‘around’ a controller action. For example, one filter might check to see if the user has the credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ‘ApplicationController’, it would run on every controller in your application.

    Below is an example to explain how a filter can be used to restrict a non-logged in user to access specified actions in a controller

    Step#1

    • In Application controller write the following block of code according to the requirement.
    def user_login_required
     if !session[:username]
     flash[:notice] = "Oops you need to login!"
     redirect_to :controller => "user_sessions", :action => "new"
     end
    end

    Step#2

    • Now write the before_filter block in the controller you want to restrict the not registered users. You can also restrict particular actions of a controller by writing the action name.
    class UsersController < ApplicationController
     before_filter :user_login_required, :only => [:profile]
     def profile
     [Your code block goes here]
     end
    end
    

    In the above block the ‘before_filter’ restrict the not registered user to access
    the profile page and redirect them to login page. We can also restrict multiple
    actions by writing like this

    before_filter :user_login_required, :only => [:profile,:edit]

    In this case the filter is applied to only these two methods of a particular controller.

    before_filter :user_login_required, :except => [:index,:show]

    In this case the filter is applied to all other actions except index and show
    action of a particular controller.
    If you write the before_filter block in the “ApplicationController” then the
    filter will be applied to all the controllers.

    Tags | , ,

    15

    May
    2013

    No Comments

    In Ruby on rail

    By Srikant M.

    3 Easy Steps to optimize Queries in Rails using ‘Bullet’

    On 15, May 2013 | No Comments | In Ruby on rail | By Srikant M.

    rorimage-123

    First,

    let me introduce you to the ‘Bullet’ gem

    ‘Bullet’ is a ruby gem which facilitates the developers by alerting when an application performs an inefficient database query, such as an N+1 query. It is one of the most efficient tool to optimize a Rails application.

    Traditional Method (w/o optimization):

    This example illustrates the old-fashioned method of optimizing a query.

    For example there are two models, one is Order and other is Product’. And an order has many products. Then the code for order listing page will be

    In app/controllers/orders_controller.rb

    class OrdersController < ApplicationController
      def index
        @orders = Order.all
      end
    end

    In app/views/orders/index.html.erb

    <h1>Orders</h1>
    
    <% @orders.each do |order| %>
      <div class="order">
        <h2><%=link_to order.title, order_path(order)%></h2>
      </div>
      <%order.products.each do |product|%>
         <ul class=”product”>
            <li><%=link_to product.title, product_path(product)%></li>
         </ul>
      <%end%>
    <% end %>

    These codes would generate N+1 query issues, because here we have queried just once to get the orders and then separate queries for each order to fetch its products. These sorts of problems can be easily overlooked during development.

    ‘Bullet’ gem comes in handy for avoiding such problems.

    Optimized Method – integrating gem ‘Bullet’:

    Let me explain in just 3 easy steps, how the gem ‘Bullet’ can be integrated to optimize the query,

    Step#1 – Add the gem to the Gemfile

    Example

    /Gemfile.rb

      gem 'bullet', '4.6.0', :group => “development”

    Run “bundle install” to install the bullet gem in the development group.

    Step#2 – Configuration setting in development.rb file

    To enable Bullet change its configuration with the after_initialize block in the development.rb file. Set alert as true to get alert popup through the browser.

    config.after_initialize do 
        Bullet.enable = true 
        Bullet.alert = true  
        Bullet.bullet_logger = true 
        Bullet.console = true 
        Bullet.rails_logger = true 
      end

    Step#3 – Restart the Server

    Restart the server as well as reload the page.
    After completing the above mentioned steps a JavaScript alert popup would appear with the detected N+1 query. The alert would display the file containing the issue as well as what could be done to overcome the problem.

    The previous N+1 query can be fixed by following below mentioned steps:

    In Controller,

    lass OrdersController < ApplicationController
      def index
        @orders = Order.includes(:products)
      end
    end

    After changing the statement from ‘Order.all’ to ‘Order.includes’(:products). We can fetch the products through eager loading. Now, if we reload the page we wouldn’t get any alert as we are fetching the efficiently. Here the data is fetched by only two queries, one to get the orders and the other to get the products in those orders.

    ‘Bullet’ can also tell us when we’re doing eager loading unnecessarily. Let’s say in the order listing page only order will be displayed. So, we removed the code that was displaying the list of products. Now after reloading the page we will get an alert popup displaying that Bullet has detected unused eager loading.

    Benefits:

    • No need to search the codes in each file to figure out the inefficient database query.
    • Bullet can notify us, through an alert message, by writing in the console or in the log file.
    • Prevent our application from performing an inefficient database query like an N+1 query.
    • It can also detect unused eager loading.

    Tags | ,

    08

    May
    2010

    No Comments

    In Ruby on rail

    By Jay Dee

    Why choose Ruby on Rails for your web app

    On 08, May 2010 | No Comments | In Ruby on rail | By Jay Dee

    rails_image2

    Ruby on Rails, popularly known as RoR, is developed using the Model-View-Controller (MVC) design pattern along with the agile development methodology. Ruby on Rails is intended to emphasize Convention over Configuration (CoC), and the rapid development principle of Don’t Repeat Yourself (DRY).


    Benefits of Ruby on Rails

    • Development Speed

    Ruby on Rails allows features to be developed quickly by using existing methods and components with the help of modular design. The factors behind its time saving results include- modular design, leaner code base and availability of existing gems/plug-ins. So the development cycles in Rails are shorter as compared to it’s counterparts.

    • Flexibility

    In Rails, there are lots of in-built components of specific functionalities already available. These modules can be reused in development rather than building everything from scratch. Ruby on Rails offers the ability to easily modify a web application in response to customers needs.

    • Cost-effectiveness

    In addition to the flexibility and development speed, Ruby on Rails is an open source web application framework which helps in developing cost-effective web applications without sacrificing performance, speed and quality.

    • High code quality

    The Ruby development community is very active and responsive. There are a lot of resources available over the Internet and any problem encountered during ROR development can be easily solved by communicating to the community. Also security updates and bug fixes are released regularly which helps in maintaining top notch code quality for application development.

    • Industry support

    There are many Ruby on Rails web hosting/consulting companies such as AWS (amazon EC2), Heroku & EngineYard offering cloud based services. They offer scalable hosting environment and provide support for development and deployment of RoR applications.

    Andolasoft offers quality rails development service. We specialize developing database driven web application in a efficient and hassle-free way. Visit our portfolio and Contact us for further details.

    SEE ALSO: Why Rails framework popular among Ruby developers

    Tags | , ,

    29

    Oct
    2012

    No Comments

    In Ruby on rail

    By Jay Dee

    CUSTOMIZING Error Messages in RAILS

    On 29, Oct 2012 | No Comments | In Ruby on rail | By Jay Dee

    ror2

    In every application regardless of its complexity we require to customize error messages to make more sense.

    There are several ways to achieve it in Rails3 and in Rails2.3.x which are mentioned specifically and that can be handled either in models or controllers or helpers.

    Solution# 1:

    If it is needed to be handled in model and message need to be have customized instead of attribute name. Like if the attribute name is “name”but you want to display messages “Employee name cannot be blank” then we have to install “custom-err-msg” plug-in.

    This plugin gives you the option to not have your custom validation error message prefixed with the attribute name. Ordinarily, if you have, say:

    validates_acceptance_of : terms, :message => 'Please accept the terms of service'

    You’ll get the following error message: Terms Please accept the terms of service

    This plugin allows you to omit the attribute name for specific messages. All you have to do is begin the message with a ‘^’ character. Example:

    validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'

    step# 1

    To install the ”custom-err-msg” plug-in you have to use the command.

    “ruby script/plugin install https://github.com/gumayunov/custom-err-msg.git”

    If you are facing problem by installing the plugin then clone it and just copy the folder (”gumayunov-custom-err-msg-640db42”) inside “Vendor/plugin/” folder

    step# 2

    In view file just display it as mentioned below:

    Similarly it can use in other places like,

    validates_presence_of :claim_no, :message => "^Work Order/Claim number cannot be blank!"

    The plugin also lets you use procs instead of strings.

    Example:

    validates_acceptance_of :accepted_terms, :message => Proc.new {|service| "You must accept the terms of the service #{service.name}" }

    The above plug-in usage can be avoided by declaring alias for each attribute as mentioned below.
    You should have a file named config/locales/en.yml, if not simply create one. There you can add your own custom names.

    en:
    activerecord:
    models:
    order: "Order"
    attributes:
    order:
    b_name: "Business Name"

    This will replace your attribute “b_name” with “Business Name”
    Your Order model in app/models/order.rb should look like:

    class Order < ActiveRecord::Base
    validates :b_name, :presence => true

    The error message will be displayed like

    Business Name cannot be blank

    Solution# 3:

    Another way is to define a method and an error message inside the method in the model.

    Class Employee < ActiveRecord::Base
    validate :zip_must_be_valid
    def zip_must_be_valid
    unless zip.map(&:valid?).all?
    errors.add_to_base " zip code is invalid"
    end
    end
    end

    We can also customize the error messages in Controllers.
    Suppose “First Name” cannot be blank to be checked. Then use below code to check for it and show customized messages

    if(params[:employee][:first_name].nil?)
    flash[:error] = "First name should not be blank.\n"
    end

    Subsequently if it is required to add other messages to the above for other attribute then it can be written as,

    if(params[:employee][:address].nil?)
    flash[:error] += Address should not be blank.\n"
    end

    Solution# 5

    Customization of error messages can be done in controllers by adding messages to existing error object’s method “add_to_base”.

    if email_data[:"email_no_#{i}"] != "" && email_data[:"email_no_#{i}"] !~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
    valid_params = false
    @company_info_new.errors.add_to_base( "Invalid Email Id!" )
    End

    In views it can be displayed by writing below code:

    0 %>
    nil, :message => nil >

    Solution# 6

    The customization that can be handled in views using

    “error_message_on” helpers (Rails 2.3.8)”

    In case you wish to show one error message in a specific location that relates to a specific validation then use “error_message_on” helper. You might have used “error_message_on” to display field-specific error messages. Here is an example that would display an error message on a name field:

    Solution# 7

    You can also use “error_message_on”(Rails 2.3.8) to display non-field-specific error messages.

    class User < ActiveRecord:Base
    validate :user_is_active
    private
    def user_is_active
    if self.is_active != true
    errors.add : user_is_active, 'User must be active to continue'
    end
    end
    end

    Now, to display this custom validation error message with “error_message_on”, we simply need to reference “:user_is_active” when we call the helper. Consider this implementation:

    Solutions# 8

    class User < ActiveRecord::Base validates_presence_of :email validates_uniqueness_of :email validates_format_of :email, :with => /^[\w\d]+$/ :on => :create, :message => "is invalid"
    end

    In Rails 3 it’s possible to call a validate method and pass it a hash of attributes to define the validations instead of defining each validation separately as mentioned above.
    /app/models/user.rb

    class User < ActiveRecord::Base validates :email, :presence => true,
    :uniqueness => true,
    :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
    end

    In the Usermodel we’re still validating that the field has a value and that the value is unique. For validating the format there are a number of options we can pass so we use a secondary hash to define those.

    We can supply any number of validations for an attribute with a single command. While this is useful it can become cumbersome if there are a large number of validations but for most situations it works nicely.

    We can make the “:format” option more concise and clean it up a little. We often want to validate email addresses and having the same long regular expression in each validator is a little ugly and introduces repetition into the code. We can extract this out into a separate validation by creating a new class in our application’s /lib directory. We’ll call the file email_format_validator.rb.

    class EmailFormatValidator < ActiveModel::EachValidator
    def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i object.errors[attribute] << (options[:message] || "is not formatted properly")
    end
    end
    end

    The EmailFormatValidator class inherits from ActiveModel::EachValidator. We have to define one method in the class “validate_each”, that takes three parameters called object, attribute and value. The method then checks that the value matches the regular expression we’re using to validate an email address and if not it will add the attribute to the objects errors.
    We can use this technique to define any kind of validation we like. Now that we have our custom validator we can update the validator in the “User” model to use it.
    /app/models/user.rb

    class User < ActiveRecord::Base
    validates :email,
    :presence => true,
    :uniqueness => true,
    :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
    end

    Having an email_format key in the “validates” hash means that the validator will look for a class called email_format_validator and passes the validation behavior into the custom class that we just wrote.
    If we try to create a new user now and enter an invalid email address we’ll see the expected error message.

    If you have some trick to share, do it in the comments.

    Tags | , ,

    27

    Jun
    2014

    No Comments

    In Ruby on rail

    By Srikant M.

    Rails: Things you must know about TDD and BDD

    On 27, Jun 2014 | No Comments | In Ruby on rail | By Srikant M.

    What does “Testing” means ?

    Testing of a product of services is an investigation to find out how well it is working against the expectation. Thus the quality of product can be assessed. Whether computer hardware or software development, testing is done at key checkpoints in the overall process to determine whether objectives are being met.

    TDD-vs-BDD

    What is TDD (Test-Driven Development) ?

    TDD is a way of designing the code by writing a test which expresses what you intend the code to do. It defines a set of rules for developing software in which test cases are written before any code and the only code written will be enough to make the tests pass.

    TDD is basically a software development technique that relies on the repetition of a very short development cycle. In this technique, first the developer starts by writing a failing automated test case (Red), implement the simplest solution that will pass the test cases (Green) and then finally improves or refactor the code (Refactor).”RED-GREEN-REFACTOR” is the main agenda for TDD.

    Tools to use:
    There are some popular gems available to implement TDD in Ruby on Rails like rspec-rails, capybara, factory_girl_rails, spork, launchy etc…

    Example:
    Below is the code snippet for writing controller tests, like this:

    describe ArticlesController do
    it "renders the index template" do
    get :index
    response.should render_template("index")
    end
    end

    What is BDD (Behavior-Driven Development)?

    BDD extends Test driven development by writing test cases in a way anyone can understand.With the help of BDD, software development is managed by both business interests and technical insight. It focuses and associates behavioral specifications with each unit of software under development.

    Basically BDD is an Agile software development technique that encourages collaboration between developers, QA and non-technical or business participants in a software project. It extends TDD by writing test cases in a natural language that non-programmers can read. In other way it is like story writing.

    The main thing to know is that BDD is meant to eliminate issues that TDD might cause.

    Tools to use:
    Some popular gems are available to implement BDD in Rails are rpsec-rails, factory_girl_rails, cucumber-rails, guard-cucumber, mocha etc…

    Example:
    Below is the code snippet for writing the BDD:

    #articles.feature
    Given an article exists called "Testing Demonstration"
    When I visit the list of articles
    Then I should see an article called "Testing Demonstration"
    
    #article_steps.rb
    Given /^an article exists called "(.+)"$/ do |title|
    FactoryGirl.create(:article, title: title)
    end
    When /^I visit the list of articles$/ do
    visit articles_path
    end
    Then /^I should see an article called "(.+)"$/ do |title|
    page.should have_content title
    end
    

    TDD or BDD, which is better?
    The main difference between TDD and BDD is the business readability factor. BDD’s main draw is that the specifications or features are separate from the test code, so the product owners can provide or review the specification without having to go through code. TDD has a similar mechanism, but instead you describe a step with a Describe, Context or It block that contains the business specification, and then immediately have the code that executes that statement.

    Few drawbacks of TDD are as follows:

    • Big time investment: For the simple case you lose about 20% of the actual implementation, but for complicated cases you lose much more.
    • Additional Complexity: For complex cases, test cases are harder to calculate.
    • Design Impacts: Sometimes the design is not clear at the start and evolves as you go along – this will force you to redo your test which will generate a big time lose.
    • Continuous Tweaking: For data structures and black box algorithms unit tests would be perfect, but for algorithms that tend to change, this can cause a big time investment that one might claim is not justified.

    Verdict

    If you are the sole developer and a product owner too, then you should go for TDD. It’s easier for a technical person to understand, which is an advantage in keeping things scoped and under control. Thus keeps you out of messing up with RegExs for test steps. On the flip side, you should go with BDD,  if you are building this for a client, and they are hands-on with regard to the specifications.

    See Also : Security Checks you must do before Rails App release

    Hope you liked it. Go ahead and post your comments what you think about this?

    Tags | , , ,

    17

    Jan
    2013

    No Comments

    In Ruby on rail

    By Jay Dee

    How to do tagging in Rails with gem ‘Acts_as_taggable_on’

    On 17, Jan 2013 | No Comments | In Ruby on rail | By Jay Dee

    ror41Tagging is a way to give a keyword and search by that particular keyword. In Rails “acts-as-taggable-on” is one of the popular gem for tagging. With ‘acts_as_taggable_on’, you can tag a single model on several contexts, such as skills, interests, and awards

    Below is an example to describe how to implement it in a Rails application:

      Step#1
    • Add the gem to your Gemfile:
    gem ‘acts-as-taggable-on'
  • Then run the bundle
  • bundle install

    Step#2

  • Run the generator command
  • rails g acts_as_taggable_on:migration
  • Run the migration file
  • rake db:migrate

    This migration will create two tables in the database: tags and taggings.
    Step#3
    Now you have to modify your model where you want to implement tagging.
    For example, we like to implement the tagging on Post model.

  • Add the following codes to the “Post” model to have acts_as_taggable and also add a “tag_list” field to the attr_accessible list.
  • attr_accessible :content, :name, :tag_list
    acts_as_taggable

    Step#4

  • Add a new field to your post form.
  • <%= f.label :tag_list, "Tags (separated by commas)" %>
    <%= f.text_field :tag_list %>

    Step#5

  • Add the following codes, if you want to show the tags for the tagged posts in the listing page:
  • <% @posts.each do |post| %>
    <h2><%= link_to post.name, post %></h2>
    <%= simple_format post.content %>
    <p>
    Tags: <%= raw post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %>
    </p>
    <% end %>

    Step#6

  • Modify your route file to get the tags
  • get 'tags/:tag', to: 'posts#index', as: :tag

    Step#7

  • Modify your controller:
  • class PostsController < ApplicationController
    def index
    if params[:tag]
    @posts = Post.tagged_with(params[:tag])
    else
    @posts = Post.all
    end
    end
    end
    

    Voila! You have done it.

    Tags | , ,

    11

    Jun
    2013

    No Comments

    In Ruby on rail

    By Srikant M.

    How to create dynamic sitemap in Rails?

    On 11, Jun 2013 | No Comments | In Ruby on rail | By Srikant M.

    rails_image2-123

    Is dynamic sitemap really that important?

    Ideally a website should have all the pages listed in the sitemap. However, in some cases, developers missed out to add newly created page links to the sitemap. For this reason the sitemap is inconsistent and leads to the most common the “404-not found” error in Rails app. Crawlers like ‘Google bot’ are unable to get updated website links from the prevailing outdated sitemap. This in turn affects search engines and eventually the business prospects. So it’s always advisable to have a dynamic sitemap for your website.

    What is the solution?

    the solution is implementing dynamic sitemap.

    Introduction to Sitemap:

    Sitemap is a list of web pages which is accessible to crawlers and users. It is the most convenient way to tell search engines about the pages in your website. Keeping it updated is always recommended if you want visitors to find your web-pages in search engines like Google, Bing etc.

    Dynamic Sitemap:

    If your website has a database, then implementing ‘dynamic XML sitemap’ would be a convenient way to prevent above issues. This enables the developers to customize each URL of the sitemap as well as updates the sitemap links almost immediately. This comes in handy when you are dealing with hundreds and thousands of URLs in a website.

    Below I have provided an example, illustrating the ‘steps to integrate dynamic sitemap gem into your rails app’.

    Let’s assume that your app has a list of users and blogs. In such cases you could implement a dynamic sitemap to generate new links automatically for the users as well as blogs. Search engines on the other hand love fresh and updated contents, and providing them with the newest links would trigger frequent spidering and indexing.

    Step 1

    Add the gem to your gem file

    gem 'dynamic_sitemaps'

    Run ‘bundle install’.

    Step 2

    Run the following command to generate initializer and route:

    rails generate dynamic_sitemaps sitemap

    The above command will create new file ‘sitemap.rb’ at
    config/initializers/sitemap.rb” and add a line in routes “match ‘sitemap.xml’ => ‘sitemaps#sitemap‘”

    Step 3

    Go to the initializer folder and open “sitemap.rb”. Add your custom code to get the latest added users and blogs from the database.

    url root_url, :last_mod =&amp;gt; DateTime.now, :change_freq =&amp;gt; 'daily', :priority =&amp;gt; 1&lt;/p&gt;<br />
    &lt;p&gt;User.all.each do |user|&lt;br /&gt;<br />
    url user_url(user), :last_mod =&amp;gt; user.updated_at, :change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br</pre>
    <div>Extremely clean I <a href="http://www.thinkdcs.com/">viagra online</a> it Tightening Resurfacing <a href="http://www.embassyofperu.org/">viagra price</a> and arrive <a href="http://3dprintshow.com/">buy cialis online</a> mixed not dry <a href="http://www.embassyofperu.org/">viagra price</a> kind anxious still <a href="http://3dprintshow.com/">cialis coupon</a> easy what the though lead...</div>
    <pre>
      />
    end&lt;/p&gt;<br />
    &lt;p&gt;Blog.all.each do |blog|&lt;br /&gt;<br />
    url blog_url(blog), :last_mod =&amp;gt; blog.updated_at, :change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br />
    end

    Now, restart the server. Launch your browser with “http://localhost:3000/sitemap.xml” URL. You can see the users and blogs links in an XML format. Whenever you add new user or blog, it will dynamically create the links from database.

    Step 4

    You can add static URLs of your site such as “About-us”,”Contacts”,”Privacy” etc by adding the following code.

    static_url = [home_contact_path,home_privacy_path,home_about_path]&lt;/p&gt;<br />
    &lt;p&gt;static_url.each do |static|&lt;br /&gt;<br />
    url &amp;quot;http://localhost:3000&amp;quot; + static,:last_mod =&amp;gt; DateTime.now,:change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br />
    end

    Finally, when you refresh the page you can see all the URLs of your app in an XML format.

    Step 5

    Now go to your public folder and open the file “robots.txt” and add the following line.

    Sitemap: http://yourdomain.com/sitemap.xml

    This will enable crawlers to find your sitemap.

    Conclusion:

    Implementing the above method would create dynamic sitemap such that the links will be exposed to the crawlers consistently making the site search engine friendly.

    Tags | ,

    02

    Oct
    2012

    No Comments

    In Ruby on rail

    By Jay Dee

    Implementing Sortable Columns in Rails through Helper

    On 02, Oct 2012 | No Comments | In Ruby on rail | By Jay Dee

    Use of a sortable column in a listing view. For an example there is a list of “Programs”

    Step# 1

    • Here our controller is named as “Programs” and the model is named as “Program”
    • Add the following helper methods to the controller
    class ProgramsController < ApplicationController
    helper_method :sort_column, :sort_direction
    protected
    def sort_column
    Program.column_names.include?(params[:sort]) ? params[:sort] : "position"
    end
    def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
    end
    def your_custom_action
    end
    end

    Step# 2

    • In Helper class of “Program” add the following codes
    module ProgramsHelper
    def sortable(column, title = nil)
    title ||= column.titleize
    active = column == sort_column
    ascending = active && sort_direction == 'asc'
    direction_html = ascending ? ' ▲ ' : ' ▼ ' if active
    css_class = active ? "current #{sort_direction}" : nil
    direction = ascending ? "desc" : "asc"
    link_to(title, { :sort => column, :direction => direction }, :remote => true, :class => css_class) << raw(direction_html)
    end
    end


    Step# 3

    • In the view (index.html.slim) file add the helper method “sortable” in the columns you want to sort
    • Please note: Here slim is used for the view pages
    #main
    table style="text-align:left;"
    tr
    th align="left" = sortable "name"
    th align="left" = sortable "created_at", "Added"
    th align="left" = sortable "subscription_level_id", "Subscription"
    th align="left" = sortable "rating_average", "Rating"
    - programs.each do |program|
    = content_tag_for :tr, program, 'row_for' do
    td= link_to program.name, program_url(program)
    td.attribute= program.created_at.strftime("%B %Y")
    td.attribute= program.subscription_level.name.capitalize if program.subscription_level
    td.attribute= ratings_for program
    .pagination_container style="padding-bottom:20px;"
    = will_paginate programs

    Tags | , , ,