downarrow loading loading loading loading
Scroll to Top

To Top

Scroll to Top

To Top

Search Results for: label/Ruby developer

Module in ‘Ruby’ and its usages in ‘Rails’

On 20, May 2016 | No Comments | In Ruby on rail, Uncategorized | By Omkar

Module ruby on rail

Ruby is basically an Object Oriented Programming (OOP) language which is based upon various components such as classes, object, variables etc. It also provides a nice building block for applications which is known as module. A module is a collection of methods and constants. It defines a namespace in which other methods and constant can’t step on your methods and constants.

Purpose of a module:
Ruby module is a component to regroup similar things. Ruby methods, classes and constants can be grouped by similarity with the help of modules. Ruby modules provide two benefits:

  • Modules provide ‘namespace’, it basically helps to prevent name clashes.
  • Ruby’s ‘mixin’ facility is implemented with the help of modules.

The basic syntax of module is:

module Identifier


Ruby module mainly functions as a namespace. It lets us define various methods for the actions that will perform. When a method defined inside a module does not clash with other methods that are written anywhere else, though they are having the same names.

Module constants are named like class constants with an initial uppercase letter. Module methods are also defined like class methods. Here is an example.

module MyModule
  def method
    puts “hello”

To access the methods and constants inside a module in a class include key word is used.

class Customer < ActiveRecord::Base
  include MyModule

To use the method that is defined inside a module, specify the module name followed by a dot and then the method name.

Ruby Mixins and Ruby Modules:

Ruby is purely an OOP language. But it does not support multiple inheritances directly, which is handled beautifully by Modules. They provide a facility called ‘mixin’ that eliminates the requirement of multiple inheritance. In Ruby when ‘mixins’ are called and used in proper manner they provide high degree of versatility functionality.

A module ‘mixin’ generally consists of several lines of codes to set up conditions where the module can mix in with a class or classes to improve the functionality of the class or itself too. Here is an example of a module ‘mixin’.

module A
  def a1
  def a2

module B
  def b1
  def b2

class MyClass
 include A
 include B
 def s1

obj =

Here module A and B consist of two methods individually. They are included in the classMyClass. Now MyClass can access all the four methods a1, a2, b1, b2. So it can be said that Myclass inherits from multiple modules. Thus multiple inheritances are implemented with the help of module’s ‘mixin’ facility.


Modules don’t have any direct analogy in any mainstream programing language. They are used mostly in Ruby language. They are one of the key features making Ruby’s design beautiful. With the facility of ‘namespacing’ and ‘mixin’ modules make Ruby more flexible Object Oriented Programming language. They also make the application highly secure as classes and their objects inherit from modules and modules are having ‘mixins’.


167 total views, 39 views today

Tags | , , ,



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.


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


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.


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.


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)


33 total views, 6 views today

Tags | ,



No Comments

In Infographic
Ruby on rail

By Omkar

Why Ruby is getting popular among languages?

On 24, Jul 2015 | No Comments | In Infographic, Ruby on rail | By Omkar

Welcome back to yet another fresh article from Andolasoft. Here, I discuss why Ruby is getting famous.

Ruby is purely an Object Oriented Programming Language which focuses on simplicity thus giving more productivity. It was designed by Yukihiro Matsumoto from Japan in the year 1995. With time, Ruby has gained a wide reputation in the Internet World and adopted by many programmers. It’s also known as a developer’s best friend. With Ruby on Rails Framework, more efficient and fast web applications are developed and the numbers are increasing. The latest stable release is version 2.2.2.

When it comes to using a programming language, every developer considers the benefits and extra features provided by this language. As being Opensource, developer can modify the codes and share it with others. Ruby has a rich library support which is very helpful in optimizing the code.

Ruby is a High Level Programming language and it uses a strong abstraction of a computer. Its syntax is more like a natural language which is very easy to understand.

It’s Your Turn To Make Things Better With Ruby
Ruby on Rails is now hot in the market as it does provide the most productive way to build Web/Internet based applications. Minimizes the code, adding effective time management as it’s the most crucial perspective in today’s market.

At Andolasoft, we help you to build custom software that can help your business differentiate itself from others and provide a deep competitive advantage through data collection, visualization, and distribution at the edges of your organization. Ruby on Rails makes these type of software development economical.

The facts we have shown above would have made you aware and upgrade your knowledge about Ruby Language. We are sure this article will be of help.

We welcome your comments. Please Visit Andolasoft’s Ruby on Rails Service for more information and details. You can also write to us at Send us your inputs in under the comments section below and don’t forget to share with your family ‘n’ friends!


71 total views, 7 views today

Tags | , , ,



No Comments

In Ruby on rail

By Jay Dee

Ruby on Rails releases fixes for DoS, XSS Vulnerabilities

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


In 18th March, Ruby on Rails released four new versions along with fixes for a number of vulnerabilities, which could have lead to denial of service attacks and XSS injections. According to a post in company’s blog a total of 4 vulnerabilities were addressed in version 3.2.13, 3.1.12 and 2.3.18 of Rails. The company wrote “All versions are impacted by one or more of these security issues,”

The patches were released for symbol denial service (DoS) vulnerability (CVE-2013-1854) in ActiveRecord function and for two cross-sites scripting vulnerabilities i.e. sanitize helper (CVE-2013-1857) and sanitize_css method in Action Pack (CVE-2013-1855).

According to one of the warnings, an additional XML parsing vulnerability in JDOM backend of ActiveSupport could have also allowed attackers to perform denial of service attack when using JRuby (CVE-2013-1856) or could have enabled to gain access to files stored in the app server.

The XSS vulnerability could have allowed attackers to embed tag URL, which executes arbitrary JavaScript code.

The XSS vulnerabilities in particular could have allowed an attacker to embed a tag containing a URL that executes arbitrary JavaScript code.

Ruby on rails developer have fixed a number of similar issues in Ruby on Rails last month, which also included a YAML issue in ActiveRecord that lead to remote code execution

37 total views, 7 views today

Tags | , ,



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:

<p class="categorylist">
<%= render :partial => 'categorylist', :collection => @category %>
  • 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.



39 total views, 4 views today

Tags | , , , ,



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.

58 total views, 3 views today

Tags | , ,



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.

34 total views, no views today

Tags | , ,



No Comments

In Ruby on rail

By Jay Dee

Usage of PDFKit with Rails 3.2.8 and Ruby 1.9.3

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

PDFkit is a powerful library which generates PDF from HTML + CSS. It uses “wkhtmltopdf” on the back-end which renders HTML using Webkit. Here is a simple example which describes the installation of “wkhtmltopdf” and usages of pdfkit. I have used rails 3.2.8 and ruby 1.9.3 as my environment.


Install the “wkhtmltopdf” library

Download the “wkhtmltopdf” library from the link


  • Download the exe file and install it.
  • Remember the installation path


  • Download the binary for your architecture at the
  • Extract the file to a directory that is in your PATH, such as /opt or /usr/local/bin and run from there.

For Debian/Ubuntu use the following command:

apt-get install wkhtmltopdf

Step-2: Installing PDFKit

In your bundle file write

gem 'pdfkit'

Then install

bundle install

Step-3: Configuration of PDFKit

Create a new file “pdfkit.rb” in “config/initializers/” path and write the following

If you are in windows then you need to give the path to the exe file generated after installation. If you are in linux and the path is set as the default path then you don’t need to give the path.

PDFKit.configure do |config|
config.wkhtmltopdf = 'C:\Program Files\wkhtmltopdf\wkhtmltopdf .exe'
config.default_options = {
:page_size => 'Legal',
:print_media_type => true
# config.root_url = "http://localhost" # Use only if your external hostname is unavailable on the server.

Step-4: Middleware Setup

Write the following in the “config/application.rb

require 'pdfkit'
config.middleware.use PDFKit::Middleware

Step-5: Usages

Creating PDF in a file path

Now to generate the pdf file by writing down the following codes on one of your controller actions

kit ="<h1>Hello</h1><p>This is PDF!!!</p>"
file_path = your_file_path
pdf = kit.to_file file_path

Now you can find the PDF file being generated on the file path.

Displaying PDF on browser

<p id="pdf_link"><%= link_to "Download Invoice (PDF)", order_path(@order, :format => "pdf") %></p>

Your PDF will be displayed on the browser.

You can also add “.pdf” to any of our application’s URLs to get a PDF version of that page.

70 total views, 8 views today

Tags | , , ,



No Comments

In Ruby on rail

By Jay Dee

Successful Mobile App and Ruby on Rails Projects

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


Andolasoft is remarkable and energetic to start the ball rolling in numerous products in mobile application development and Ruby on rails development arena.

Among them Christmas Tree Puzzle game app, job management app for IPhone. Also Social email reminder app, Social media Job portal app in RoR are getting used by lots of people everyday.

Some of our new projects are product based and we are focusing on the advance technology of mobile and web application development like IPhone, Android, RoR, PHP/CakePHP. Very soon we are going to launch/release some new apps those are under development and will available in the market very shortly. Check out our recent portfolio and domains and technologies. We’re also growing by increasing our team size. We’ve a team of dedicated and skilled developers and designers who’re helping Andolasoft to do the job perfectly in right time. Quality assurance is one of our aim for all projects with a quick turnaround period. Continuously we keep hunting and hiring right folks with mobile as well as web technologies. Please check out current job openings.

99 total views, 6 views today

Tags | , , ,



No Comments

In Ruby on rail

By Jay Dee

Security Issues Related to Ruby on Rails Applications

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

Rails3-123Security of any software product or application is something which every software solution provider is wary of. It is no different in the case of a Ruby on Rails application. Even after an application is successfully developed and deployed, there can be possibilities for many unseemly activities. US based high end software solution provider Andolasoft.Inc sheds some light on some of the basic precautions that are worked upon before deploying an application. The Company’s Rails developers pay special attention to security issues in every undertaken venture.
Authentication and authorization of User model are two different things. Actions like create/update/delete always need to be protected. Even popular plug-ins like Restful authentication and Clearance only authenticate whereas providing no helper methods for authorization.

Mass assignment of sensitive attributes from re-assignment should be protected. This can be taken care of by disabling mass assignment with the help of attr_accessible or attr_protected in the respective models. Attributes like account_id’s and user_id’ should be protected. Also disabling updates on protected attributes can be by using attr_readonly, so that the Ids don’t get updated once set.

Content types of files being uploaded can be faked, so uploaded files should be placed in protected directories or servers. Also file extensions should be checked and the web server should be disabled so as not to execute such files in the uploaded directories.

Sessions are prone to vulnerabilities like hijacks, replaying cookies and session fixation. Extra caution must be taken regarding storing data in sessions. Active record Objects should never be stored in sessions which might change that Object’s behavior while migration and future code changes. Best practice is to only store the ids of the records. Also sensitive data like User access privileges and money based information should not be stored in sessions.

18 total views, 4 views today

Tags | , ,



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


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

1,959 total views, 442 views today

Tags | , ,



No Comments

In Ruby on rail

By Srikant M.

What new features you will get in the latest release of Rails4

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



Finally, the most awaited Rails 4.0 version has been released by the Rails team on 25th of June. Rails 4 has got huge changes. There are tons of new features available, which can make your life as a Rails developer a lot easier. We will talk about the most exciting features in Rails 4 and why you should upgrade from Rails 3 version as soon as possible.

New features of Rails4

1. Ruby Versions

It is essential to note that Rails 4 would require Ruby 1.9.3 or higher, in fact Ruby 2.0.0 is recommended for your Rails 4 apps.

2. ‘Gemfile’

Rails now uses a ‘Gemfile’ in the application root to determine the gems you need for your app to start. This ‘Gemfile’ is processed by the Bundler gem, which then installs all the dependencies. It can also install all the dependencies locally to your app so that it doesn’t depend on the system gems.

Read Also: How to do tagging in Rails with gem ‘Acts_as_taggable_on’?

3. ‘Threadsafe’ by Default

Rails 4 will be thread-safe by default i.e. removing overhead and improving the performance on threaded servers, like thin and puma. You will have to ensure that your application and its dependencies are thread-safe, in other words, avoiding global state e.g. class or global variables.

4. No More vendor/plugins

Rails 4.0 will no longer support loading of plugins from vendor. You must replace any plugins by extracting them to gems and adding them to your ‘Gemfile’. If you choose not to make them gems, you can also move them into a different directory such as lib/my_plugin/* and add an appropriate initializer in config/initializers/my_plugin.rb.

5. New Testing Directories

The biggest change made to the testing of Rails 4 app is not the swapping of the testing framework, rather the testing folder structure. The test folder will now have a structure very similar to RSpec:

  • controllers:
  • fixtures
  • helpers
  • integration
  • mailers
  • models

Developers will no longer have to worry if the test is “functional” or a “unit”. The structure provides a clear separation of where the tests in your application should go.

6. Strong Parameters

In Rails 4, a new pattern has been introduced to secure your models from mass assignment. You can filter the parameters passed to your model in the controller instead of ‘whitelisting’ the attributes in your model using “attr_accessible”.

class PostController < ApplicationController
 def create
 @post = Post.create(params[:user])

You can protect against unexpected input with declarations in the model using “attr_accessible”.

attr_accessible :title, :description

In Rails 4, you don’t need to worry about unexpected input attributes in your model anymore.
Strong Parameters gem moves user input into the controller.

class PostController < ApplicationController
 def create
 @post = Post.create(post_params)

 def post_params
 params.require(:post).permit(:title, :description)

The “params hash” in your controller is not a normal hash. It’s actually an instance of ActionController::Parameters, which exposes the “require” and “permit” methods.

The “require” method ensures that the specified key is available in the “params” hash, and raises an ActionController::ParameterMissing exception if the key doesn’t exist.

The “permit” method protects you from unexpected mass assignment.

7. Renamed Callbacks

Action callbacks in controllers are now renamed from *_filter to *_action


before_filter :before_action
arround_filter :arround_action
after_filter :after_action

All existing *_filter methods will still work with no deprecation warnings. However, It would recommend to replace of *_filter calls to *_action

8. Rails 2 Model.find(:[all|:first:last]) syntax is now deprecated.

9. Deprecated dynamic finders

Rails 4 deprecates all dynamic finder methods (with the exception of find_by and find_by_…). Instead, you’ll use where

find_all_by_... => where(...)
scoped_by_... => where(...)
find_last_by_... => where(...).last
find_or_initialize_by... => where(...).first_or_initialize
find_or_create_by... => where(...).first_or_create
find_or_create_by_...! => where(...).first_or_create!

The deprecated finders gem will be included as a dependency in 4.0 and removed in 4.1. The gem, however, will be around and maintained until 5.0.

10. Queuing system

Rails4 added the support for a queue to run background jobs. The queuing API is very simple. The ActiveSupport::Queue class comes with a push method that accepts any object, as long as that object defines a run method.

Let’s say that you have a job class TestJob that prints the name of an author

class TestJob
 def run
 puts "I am running!"

You can queue a job to print “I am running!” in the background by pushing an instance of that class to Rails.queue:

"I am running!"

The job will run in a background thread and it will not block any of your operations.

11. Live Streaming

Live Streaming is a major new feature in Rails 4. It facilitates you to stream data to the browser. Enabling live streaming requires you to mix in the ActionController::Live class in your controller.

class MyController < ActionController::Base
 include ActionController::Live
 def stream
 response.headers['Content-Type'] = 'text/event-stream'
 100.times { "hello world\n"
 sleep 1

It will stream the string “hello world” to your client 100 times.

You should take notice of following things

  • Manually close the stream after you are done streaming in the browser.
  • Headers must be written first before writing anything to the client.
  • You will need a concurrent Ruby web server, such as, Rainbow or Thin. Using the default ‘WEBrick’ server won’t work, since it buffers all the output. Also note that Unicorn won’t work either, since it kills the connection after 30 seconds.
  • All controllers that include ActionController::Live would be executed in another thread, so make sure your code is thread-safe.

12. Rails 4 and Hstore from Postgres 9.2

ActiveRecord in Rails 4 will now support the PostgreSQL hstore extension. This database extension allows a new data type for a column in PostgreSQL called ‘hstore’ which effectively represents a string-only hash. For most purposes this would be similar to serializing data in a text column, but the fact that this is now a native datatype, it would grant a huge performance boost and the capability to query against it directly. You can now have a hint of a schema-less database available to your application without needing to perform a full upgrade to MongoDB, CouchDB, Riak or other similar schema-less data store.

13. Cache Digests (Russian Doll Caching)

Make it super easy to do Russian Doll-caching through key-based expiration with automatic dependency management of nested templates

14. Turbolinks

Now you can speed-up the client-side with ‘Turbolinks’. It essentially turns your app into a single-page ‘JavaScript’ application in terms of speed, but with none of the developmental drawbacks (except, maybe, compatibility issues with some existing JavaScript packages).

15. Routing Concerns

In Rails 4, routing concerns has been added to the router. The basic idea is to define common sub-resources (like comments) as concerns and include them in other resources/routes.

16. Rails3 code

resources :posts do
 resources :comments
resources :articles do
 resources :comments
 resources :remarks

In rails4 the concern routes will only be included within a resource by passing it to the routing option :concerns. The :concerns option can accept one or more concerns.

concern :commentable do
 resources :comments
concern :remarkable do
 resources :remarks
resources :posts, :concerns, :commentable
resources :articles, :concerns =>[:commentable, :remarkable]

Why we should upgrade to rails4?

Rails4 is recommended to be used with Ruby 2.0.0. It stopped supporting Ruby 1.8.x after Rails 3.2. Ruby 1.9.2+ will be supported until Rails 5 is released!

Aware of any other not-so-obvious features? Please post it in the comments below.

114 total views, 10 views today

Tags | ,



No Comments

In Ruby on rail

By Srikant M.

Steps to execute pagination using “Kaminari” gem in Rails3

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


Kaminari” is a clean, powerful, customizable and sophisticated pagination for the modern web applications. Here we have to bundle the gem and the models that are ready to be paginated and no extra configuration is required for the process.

Key Features:

  • Easy to use.
  • Customizable engine-based I18n-aware helper.
  • The pagination helper outputs the HTML5 <nav> tag by default and the helper supports Rails 3 unobtrusive Ajax.

Recommended Reading: AJAX Pagination using jQuery in Rails3

Here are the steps to implement “kaminari gem” in a Rails app.


  • Put this code in your Gemfile:
gem 'kaminari'
  • Run “bundle install”


  • Modify the controller as mentioned below
@blogs = Blog.order("name").page(params[:page])


  • Now, add the paginate helper method in your listing page which is provided by Kaminari, by passing in the list we’re paginating.
<%= paginate @blogs%>


  • When the page reloads, the pagination links will be visible. Kaminari will show 25 items per page by default, but we can easily change that by calling another scope called “per” as mentioned below.
@blogs = Blog.order("name").page(params[:page]).per(10)
  • Now it should display 10 items per page.


  • You can configure the below mentioned default values of kaminari by running the command
rails g kaminari:config

It’ll generate a file “kaminari_config.rb” in your config/initializers folder with the following code snippet as commented.

default_per_page   # 25 by default
max_per_page       # nil by default
window             # 4 by default
outer_window       # 0 by default
left               # 0 by default
right              # 0 by default
page_method_name   # :page by default
param_name         # :page by default
  • Next, you can change the values according to your requirement.
  • If you change your view page like:
<%= paginate @blogs, :window => 2 %> 
  • The output will be:
« First ‹ Prev 1 2 3 4 5 … Next › Last »
  • There are some other custom attributes you can use in view page like:
<%= paginate @users, :outer_window => 3 %>
<%= paginate @users, :left => 1, :right => 3 %>
<%= paginate @users, :params => {:controller => 'foo', :action => 'bar'} %>
<%= paginate @users, :remote => true %> 

Kaminari also includes a handy template generator. You can override them by running following command.

rails g kaminari:views default

It’ll generate a “Kaminari” folder in app/views with dependent files inside it.

I hope you liked it. If you want you can contact our experienced ruby on rails developer for your webs and mobile application.
Please leave your comment about this post on the comment section below.

40 total views, 7 views today

Tags | ,



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.


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
# 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; # 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>

Now you will be able to browse your application.

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

For example:

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
: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

955 total views, 19 views today

Tags | ,



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” 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

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])
@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)

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'

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

Fix N+1 Queries

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


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.

109 total views, 2 views today

Tags | ,



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.


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…

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")

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…

Below is the code snippet for writing the BDD:

Given an article exists called "Testing Demonstration"
When I visit the list of articles
Then I should see an article called "Testing Demonstration"

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

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.


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?

271 total views, 19 views today

Tags | , , ,



No Comments

In Ruby on rail

By Jay Dee


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


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”

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.


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

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.

order: "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
errors.add_to_base " zip code is invalid"

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

flash[:error] = "First name should not be blank.\n"

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

flash[:error] += Address should not be blank.\n"

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!" )

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
def user_is_active
if self.is_active != true
errors.add : user_is_active, 'User must be active to continue'

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"

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.

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

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")

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.

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

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.

410 total views, 8 views today

Tags | , ,



No Comments

In Ruby on rail

By Srikant M.

Parsing Feeds In Rails app Using FeedZirra Gem

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


What is a feed?

A feed is a data format which is used to provide frequent updates and latest contents to the users. A feed has no particular type; it could be news, latest technology, game, gadgets, sports etc. These feeds can be easily parsed into your Rails application to make it more useful for the users. The feed is build up with XML and has particular format type.

What is feedzirra?

“Feedzirra” on the other hand is a feed library built on Ruby that is designed to get and update a number of feeds as fast as possible. This includes using “libcurl-multi” through the “curb” gem for faster http gets, and “libxml” through “nokogiri” and “sax-machine” for faster parsing.

Suppose you need to add some updated information to your Rails application from other feed site like ‘feedburner’, in such cases you can easily work it out by using the gem “feedzirra”.

Here are the steps to use ‘feedzirra’ in your Rails application.


Add the gem ‘feedzirra’ in to your gem file.

gem 'feedzirra'

Run ‘bundle install’ to install the gem along with its dependencies.


Modify your controller where you are fetching the feeds.

require 'feedzirra'


Now, write the following code in your method in order to parse feeds from an external site.

feed =Feedzirra::Feed.fetch_and_parse("")
@entry = feed.entries

Note: Here we are parsing the feeds from ‘feedburne’r site with updated information on gaming news.


Now, open your view section and write the following code snippet to display the information regarding the feeds.

<%@entry.each do |t|%>
<%= link_to "#{t.title}", "#{t.url}",:target => "_blank" %>

Note: The above code will display the feed title, author name, content, published date and category type. Clicking the feed title, will launch a new tab in browser and display the detail information of that feed.


You can also fetch multiple feeds by writing the following code.

feed_urls = ["", ""]
feeds = Feedzirra::Feed.fetch_and_parse(feed_urls)


The prime feature of “Feedzirra” is its speed. It facilitates ruby developers with faster parsing of feeds, and not just that it is enabled to parse a number of feeds of multiple types.

78 total views, 7 views today

Tags | ,



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.


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;, :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="">viagra online</a> it Tightening Resurfacing <a href="">viagra price</a> and arrive <a href="">buy cialis online</a> mixed not dry <a href="">viagra price</a> kind anxious still <a href="">cialis coupon</a> easy what the though lead...</div>
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 />

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;,:change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br />

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.


This will enable crawlers to find your sitemap.


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.

140 total views, 3 views today

Tags | ,



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.



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

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


<% @orders.each do |order| %>
  <div class="order">
    <h2><%=link_to order.title, order_path(order)%></h2>
  <%order.products.each do |product|%>
     <ul class=”product”>
        <li><%=link_to product.title, product_path(product)%></li>
<% 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



  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 

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)

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.


  • 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.

54 total views, 3 views today

Tags | ,