Rails Or Django – Which One To Choose?

Rails or Django - which one to choose?

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 the most important difference between Python and Ruby:

Philosophy

Python has been designed to emphasize the 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. A 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 features 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 lot 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 the REST protocol. It helps you to organize your application. In Rails, all model objects are accessed and handled in a uniform manner using the standard HTTP verbs like getting, PUT, DELETE, and POST.

CSS, JavaScript and images

Rails have an 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 to 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 applications 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

What is TDD and BDD in Rails App Development

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.

Test-Driven Development (TDD) is a software development process that focuses on writing tests before writing the actual code. The TDD cycle typically follows three steps:

  • Write a Test:
    Developers begin by writing a test that defines the desired behavior of a particular piece of code. This test initially fails because the code to fulfill the behavior hasn’t been implemented yet.
  • Write Code:
    Next, the developer writes the minimum amount of code necessary to make the test pass. This phase emphasizes simplicity and getting the code to work.
  • Refactor:
    After the test passes, developers refactor the code to improve its quality, maintainability, and efficiency. This step ensures that the codebase remains clean and easy to maintain.

TDD is renowned for its ability to catch bugs early in the development process, enhance code quality, and provide clear documentation of how the code is intended to work.

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:

[sourcecode language=”plain”]
describe ArticlesController do
it "renders the index template" do
get :index
response.should render_template("index")
end
end[/sourcecode]

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.

Behavior-Driven Development (BDD) is an extension of TDD that focuses on the behavior of software from the user’s perspective.

BDD emphasizes collaboration between developers, testers, and business stakeholders to ensure that the software meets the desired behaviors and outcomes. Key components of BDD include:

  • Specifying Behavior:
    In BDD, behaviors are specified using human-readable language, often in the form of “Given-When-Then” scenarios. These scenarios describe the expected behavior of the software from the user’s viewpoint.
  • Collaboration:
    BDD promotes collaboration between technical and non-technical team members. Developers, testers, and business stakeholders work together to define and understand the software’s behavior.

Automated Testing: BDD scenarios are translated into automated tests that verify the desired behaviors. These tests serve as living documentation that ensures the software aligns with the intended behavior.

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:

[sourcecode language=”plain”]
#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
[/sourcecode]

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.

Benefits of TDD and BDD in Rails Development

  • Early Bug Detection:
    TDD and BDD catch bugs at an early stage of development, reducing the likelihood of critical issues arising in production.
  • Enhanced Code Quality:
    Writing tests before code enforces well-structured, modular, and maintainable code, resulting in a more robust application.
  • Clear Documentation:
    Test cases serve as clear documentation of the code’s intended behavior, making it easier for developers to understand and work with the codebase.
  • Collaboration:
    BDD encourages collaboration between technical and non-technical team members, leading to a shared understanding of requirements.
  • Regression Prevention:
    Automated tests created through TDD and BDD ensure that new changes do not break existing functionalities.

Best Practices for TDD and BDD in Rails

  • Start Small:
    Begin by writing tests for small, incremental features. This helps you master the TDD/BDD process and ensures a gradual buildup of test coverage.
  • Red-Green-Refactor:
    Follow the TDD cycle religiously: write a failing test, make it pass with minimal code, then refactor to improve code quality.
  • Human-Readable Scenarios:
    In BDD, use human-readable language to describe scenarios, making them understandable to all team members.
  • Automate Everything:
    Automate your tests so that they can be executed frequently and consistently.
  • Maintain Test Suite:
    Regularly maintain and update your test suite to reflect changes in requirements and keep it relevant.

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?

Related Questions

What is the fundamental principle behind Test-Driven Development (TDD) in Rails development?

Test-Driven Development (TDD) in Rails involves writing tests before writing the actual code. This approach ensures that the code meets the desired behavior defined by the tests.

The TDD cycle includes writing a failing test, writing the minimum code required to pass the test, and then refactoring the code for improved quality.

How does Behavior-Driven Development (BDD) differ from Test-Driven Development (TDD)?

Behavior-Driven Development (BDD) extends the principles of TDD by focusing on the behavior of software from the user’s perspective.

BDD emphasizes collaboration between developers, testers, and business stakeholders to define behavior using human-readable scenarios like “Given-When-Then.” BDD scenarios are translated into automated tests, serving as living documentation that ensures the software aligns with intended behaviors.

Q3: What benefits does Test-Driven Development (TDD) bring to Rails development projects?

Test-Driven Development (TDD) offers benefits such as early bug detection, enhanced code quality, clear documentation of desired behavior, collaboration among team members, and prevention of regressions.

TDD ensures that the codebase is well-structured, modular, and maintainable, leading to a more robust and dependable Rails application.

How can Behavior-Driven Development (BDD) foster effective collaboration in Rails development teams?

Behavior-Driven Development (BDD) promotes collaboration by involving technical and non-technical team members in defining behavior scenarios.

Developers, testers, and business stakeholders work together to create human-readable scenarios that describe the software’s behavior. This shared understanding ensures that everyone is on the same page regarding the requirements and expectations.

What are some best practices for successfully implementing Test-Driven Development (TDD) and Behavior-Driven Development (BDD) in Rails projects?

Best practices for TDD and BDD include starting small by writing tests for incremental features, following the red-green-refactor cycle, using human-readable language for BDD scenarios, automating tests for frequent execution, and regularly maintaining and updating the test suite to reflect changes in requirements.

These practices ensure that TDD and BDD are effectively integrated into the development process, leading to high-quality Rails applications.

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

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.

Steps to add ‘Elasticsearch’ to Rails App

ElasticSearch-to-Rail-AppsWhat is Elasticsearch?

Searching on websites is important from a content discovery and user usability perspective. It allows readers to control the way they look for content instead of navigating through menus. Elasticsearch is a distributed open source search server based on Apache Lucene, much like Solr. It allows for real-time searching and the ability to scale easily through replicas. It has a REST API and communicates over JSON. We will use a gem called Tire to communicate with it.

What is the Problem if you don’t use a search engine?

If your application requires a full text search, then it is better to add a search engine like elasticsearch to the application. As normal queries to the database for the full text search might slow down your performance. You will end up with complex queries.

Tire is an elasticsearch ruby client. It can be used in any Ruby project, but it also has some nice model functionality to make it easy to integrate into a Rails application. It is actively maintained, has a large amount of users, and also integrates nicely with Rails and ActiveModel.

Step#1
Install elasticsearch in your server

$curl -L -O -k https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.0.Beta1.zip
$unzip elasticsearch-0.90.0.Beta1.zip
$mv elasticsearch-0.90.0.Beta1 elasticsearch

Install the Elasticsearch Service Wrapper

$curl -L -k http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
$mv *servicewrapper*/service elasticsearch/bin/
$elasticsearch/bin/service/elasticsearch install
$ln -s `readlink -f elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch (optional use )
$rcelasticsearch start or /etc/init.d/elasticsearch start

By default the server on port 9200 ex: http://localhost:9200
We can communicate to the server manually if we want through the JSON REST API.

Step#2
Add the following gem in your gemfile

gem 'tire'

Run the bundle install

Step#3
To make the Article searchable with Tire, just include below lines of code in your model

class Article < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
end1
 
<strong>Setp#4</strong>
To create index for elasticsearch server run the below command
 
1$ rake environment tire:import:all

You can also force-import the data by deleting the index first

$ rake environment tire:import CLASS=’Article’ FORCE=true

Step#5
Add the following in your model

def self.search(params)
tire.search(load: true) do
query { string params[:query]} if params[:query].present?
end
end

Step#6
Add the following in your controller

def index
if params[:query].present?
@articles = Article.search(params).paginate(:page => params[:page], :per_page => 12)
else
@articles = Article.all
end
end
Step#7 Add the search form>
<%= form_tag articles_path, method: :get do %>
<p>
<%= text_field_tag :query, params[:query] %>
<%= submit_tag "Search", name: nil %>
</p>
<% end %>

To know the which model are indexed you can test by running the followings in your browser

http://localhost:9200/_aliases?prett

To test the elasticsearch run the followings in your browser which will return the data in JSON format

http://192.168.2.100:9200/articles/_search?q=news

Conclusion:

Andolasoft is one stop shop for Ruby on Rails app development. We Design, develop & deploy Rails application in cloud for start-ups & established businesses. If you look for any type of assistance, please contact us.

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

5 Reasons Why Web Development is Faster With Ruby On Rails

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

Never miss an update from us. Join 10,000+ marketers and leaders.

It’s possible to build sites that used to take 12 weeks in just 6 weeks using Ruby on Rails. It means you can save 50% on your development expenses.

2. Less Code Writing

Rails creates a skeleton for an application or module by executing all the code libraries. You must write some commands to accomplish this. This is what makes the process of web development faster.

Rails makes database deployments simpler than any open, or proprietary solution by allowing for migrations.

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

I’ve worked with the team at Andolasoft on multiple websites. They are professional, responsive, & easy to work with. I’ve had great experiences & would recommend their services to anyone.

Ruthie Miller, Sr. Mktg. Specialist

Salesforce, Houston, Texas

LEARN MORE

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 .

Asynchronous processing with Sidekiq gem in Rails

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.