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.

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.

Memcached Vs Redis, Which One to Pick for Large Web App?

Introduction:

MemcacheD is easy yet powerful. It’s manageable design promotes fast deployment, ease of exaggeration, and solves many problems related to large data caches. It has its inbuilt APIs which provide a very large hash table distributed across multiple machines & uses internal memory management which is more efficient in the simplest use cases because it consumes comparatively less memory for metadata. MemcacheD supports only String data type which are ideal for storing read-only data.

Memcached is a volatile in-memory key-value origin. It is rude, multi-threaded and used primarily for caching objects.

Redis is an open source in-memory data structure store which also can be used as a database as well as caching. It supports almost all types of data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes through radius queries. Redis also can be used for messaging system used as pub/sub.

Internal Architecture:

Internal Architecture

 

Here are the key points to consider,

Installation:

Installing Redis is so much easier. No dependencies required.

Memory Usage:

MemcacheD’s internal memory supervision, while not exactly a substitute to Redis; Is more efficient because it consumes comparatively less memory resources for metadata. For easy key-value pairs, MemcacheD is more memory efficient than Redis. Redis is more memory efficient, only after you use Redis hashes.

Persistence:

If you are using MemcacheD, data might be lost with a restart and rebuilding cache is a costly process. On the other hand, Redis can handle persistent data. By default it syncs data to the disk at least every 2 seconds, offering optional & tuneable data persistence meant to bootstrap the cache after a planned shutdown or an unintentional failure. While we tend to regard the data in caches as volatile and transient, persisting data to disk can be quite valuable in caching scenarios.

Replication:

MemcacheD does not support replication, whereas Redis supports master-slave replication. It allows slave Redis servers to be the exact copies of master servers. Data from any Redis server can replicate to any number of slaves. Replication can be used for implementing a cache setup that can withstand failures and find the maintenance for uninterrupted facilitation to the application.

Storage type:

MemcacheD stores variables in its memory & retrieves any information directly from the server memory instead of hitting the database again. On the other hand, Redis is like a database that resides in memory. It executes (reads and writes) a key/value pair from its database to return the result set. Developers use Redis for real-time metrics & analytics too.

Read/Write Speed:

MemcacheD is very good to handle high traffic websites. It can read lots of information at a time and give you back at a great response time. Redis can neither handle high traffic on read nor heavy writes.

Data Structure:

MemcacheD uses strings and integers in its data structure. Hence, everything you save can either be one or the other. With integers, the only data manipulation you can do is adding or subtracting them. If you need to save arrays or objects, you will have to serialize them first and then save them. To read them back, you will need to un-serialize.

In comparison Redis has stronger data structures, which can handle not only strings & integers but also binary-safe strings, lists of binary-safe strings, sets of binary-safe strings and sorted sets.

Key Length:

MemcacheD’s key length has a maximum of 250 bytes, whereas Redis has a maximum of 2GB.

Here is the benchmarking result by DB-Engines, which clearly shows the leader.

Conclusion:

Use Redis, if you need to do operations on cached datasets at once or need to spread one enormous cache over a geographically challenged area. Read-write splitting against caching will enormously help performance and alleviate the cache connection starvation.

On the other hand, you might want to stick to Memcached for its simplicity, reliability and speed.

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

If you’re thinking anything on Ruby on Rails, get in touch with Andolasoft’s experts. Let’s convert your idea into an App.

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

Enhance Speed of your web app with Backbone.js

Backbone.js is a popular open source JavaScript framework that allows us to develop single page web application. It offers a MVC framework for organizing Javascript application.

backbonerails-new1

 

 

 

 

 

 

 

 

What is Backbone.js?

  • Building single-page web apps or complicated user interfaces will get extremely difficult by simply using JQuery alone. Because JavaScript libraries are great at what they do, without realizing it you can build an entire application without any formal structure. Whereas Backbone.js is a lightweight framework that allows us to create single page applications in a structured manner. Backbone.js enforces that communication to the server should be done entirely through a RESTful API. The web is currently trending such that all data will be exposed through an API, because the browser is no longer the only client, now we have mobile devices, tablets and electronic fridges etc.
  • Website speed is the demand of the day. Running a website with full server dependencies, is not cost effective in terms of speed. If for each and everything we depend upon server and every request is served with a page refresh, then it will be annoying to any user. If you use MVC client architecture like Backbone.js, then most of the load on server is reduced and the website is depends on server only for getting json data and not for the logic of how to display it.
  • Better user experience is needed for every website that wants more and more users to visit it. And Backbone.js provides a very good user experience, as the demand of the users are served only in the client machine. User does not need a page refresh for any action.

Advantages of Backbone.js

  • Streamlined Event handling
    When a project grows, the jQuery declarations and callbacks gets more complex. The code becomes more cluttered. Backbone.js overcome this problem by providing an event-driven communication between views and models. The backbone.js events build on top of regular DOM events, which makes the mechanism very versatile and extensible.
  • Syncing with a back-end
    The models in Backbone.js can be easily tied to a back-end. The framework provides excellent support for RESTful APIs in that models can be mapped to RESTful endpoints.
  • Maintainability by following conventions
    Conventions are a great way to introduce a common coding style without the need of coming up with an extensive set of coding standards. Backbone.js is particularly helpful to maintain a clean code base despite having multiple developer involved in the coding.
  • Organized Code
    Backbone.js is a client-side MVC architecture. It is a design pattern where we separate the data from the way it is defined, manipulated and displayed. It allows you to structure your Javascript code in an MVC pattern.
  • Speed
    In the MVC platform, web application depends upon server for getting json data for the logic on how to display it. Here load on server is reduced and it helps in increasing the speed of the website.
  • Reduced data transfer
    Normally when client searches a record from the database, it sends a request to server.And then, to render output, database starts processing and send response.
    Server -> database processing-> rendering output-> Response
    But with Backbone.js request will be sent only for data and data will be returned from server in json format. Those data is manipulated at client-side.

 

In essence the backbone is the way to structure your application better. You can easily organize client side ‘JavaScript’ code into MVC pattern of Rails applications. Check out implementation of ‘Backone.js’ into Rails applications.

We have implemented numerous Rails applications with backbone.js. Two out of them are KurrentJobs and OrangeGigs.

Please share your experience of implementation of Backbone.js in Rails.