Project Report: Web Development Using Angular Js and Ruby On Rails
Project Report: Web Development Using Angular Js and Ruby On Rails
WEB DEVELOPMENT
USING ANGULAR JS AND RUBY ON RAILS
The project “Angular js with Ruby On Rails” is implemented to show how modern day website
are developed using this technology and how this method is effective than other modern day
trechnologies.
ii
ACKNOWLEDGMENT
It gives us great pleasure to express our sincere feelings of gratitude to all those, whose
invaluable guidance and useful suggestions helped us to complete this project successfully. . We
are also indebted to our guide Mr. Prashant Kumar who is responsible for the achievement of the
goal. We here by acknowledge our gratitude to all of them who were directly or indirectly
involved in carrying out this project.
ABHINAV RAJ
iii
INDEX
INTRODUCTION
IMPLEMENTATION
AngularJS
FEATURES
CONCEPT
ADVANTAGES OF AngularJS
DISADVANTAGES OF AngularJS
AngularJS COMPONENTS
SCOPE
CONCLUSION AND FUTURE ENHANCEMENT
iv
INTRODUCTION
AngularJS is a structural framework for dynamic web apps. With AngularJS, designers can use
HTML as the template language and it allows for the extension of HTML's syntax to convey the
application's components effortlessly. Angular makes much of the code you would otherwise
have to write completely redundant.
Despite the fact that AngularJS is commonly related to SPA, you can use Angular to build any
kind of app, taking advantage of features like: Two-way binding, templating, RESTful api
handling, modularization, AJAX handling, dependency injection, etc.
What is Ruby?
Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base
of Rails.
Ruby is the successful combination of −
Easy to learn
Open source (very liberal license)
Rich libraries
Very easy to extend
Truly object-oriented
Less coding with fewer bugs
v
Helpful community
Although we have many reasons to use Ruby, there are a few drawbacks as well
that you may have to consider before implementing Ruby −
Performance Issues − Although it rivals Perl and Python, it is still an
interpreted language and we cannot compare it with high-level
programming languages like C or C++.
Threading model − Ruby does not use native threads. Ruby threads are
simulated in the VM rather than running as native OS threads.
What is Rails?
An extremely productive web-application framework.
vi
Metaprogramming
Where other frameworks use extensive code generation from scratch, Rail
framework uses Metaprogramming techniques to write programs. Ruby is one of
the best languages for Metaprogramming, and Rails uses this capability well.
Rails also uses code generation but relies much more on Metaprogramming for
the heavy lifting.
Active Record
Rails introduces the Active Record framework, which saves objects into the
database. The Rails version of the Active Record discovers the columns in a
database schema and automatically attaches them to your domain objects using
metaprogramming.
Convention over configuration
Most web development frameworks for .NET or Java force you to write pages of
configuration code. If you follow the suggested naming conventions, Rails doesn't
need much configuration.
Scaffolding
You often create temporary code in the early stages of development to help get an
application up quickly and see how major components work together. Rails
automatically creates much of the scaffolding you'll need.
Built-in testing
Rails creates simple automated tests you can then extend. Rails also provides
supporting code called harnesses and fixtures that make test cases easier to write
and run. Ruby can then execute all your automated tests with the rake utility.
Three environments
Rails gives you three default environments: development, testing, and production.
Each behaves slightly differently, making your entire software development cycle
easier. For example, Rails creates a fresh copy of the Test database for each test
run.
vii
class Hello
def salute
puts "Hello #{@name}!"
end
end
viii
If you want the result of the code execution to be printed out, as a part of the
output, enclose the code between <%= and %>.
Here's an example. Save the code in erbdemo.rb file. Note that a Ruby file will
have an extension .rb −
<html>
<head>
<title><%= page_title %></title>
</head>
<body>
<p><%= salutation %></p>
<p>This is an example of how ERB fills out a template.</p>
</body>
</html>
Now, run the program using the command-line utility erb.
tp> erb erbdemo.rb
This will produce the following result −
<html>
<head>
<title>Demonstration of ERb</title>
ix
</head>
<body>
<p>Dear programmer,</p>
<p>This is an example of how ERb fills out a template.</p>
</body>
</html>
IMPLEMENTATION
x
To develop a web application using Ruby on Rails Framework, we need to install
the following software −
Ruby
The Rails Framework
A Web Server
A Database System
xi
Step 1: Check Ruby Version
First, check if you already have Ruby installed. Open the command prompt and type ruby -v. If
Ruby responds, and if it shows a version number at or above 2.2.2, then type gem --version. If
you don't get an error, skip Install Ruby step. Otherwise, we'll install a fresh Ruby.
Note − The above command may take some time to install all dependencies. Make sure you are
connected to the internet while installing gems dependencies.
Output
Rails 4.2.4
xii
Congratulations! You are now on Rails over Windows.
Use the following command for setting up the current Ruby version as default.
tp> rbenv global 2.2.3
Output
ruby 2.2.3p173 (2015-08-18 revivion 51636) [X86_64-linux]
Ruby provides a keyword gem for installing the supported dependencies; we call them gems. If
you don't want to install the documentation for Ruby-gems, then use the following command.
tp> echo "gem: --no-document" > ~/.gemrc
Thereafter, it is better to install the Bundler gem, because it helps to manage your application
dependencies. Use the following command to install bundler gem.
tp> gem install bundler
xiii
Step 4: Install Rails
Use the following command for installing Rails version 4.2.4.
tp> install rails -v 4.2.4
Output
tp> Rails 4.2.4
Ruby on Rails framework requires JavaScript Runtime Environment (Node.js) to manage the
features of Rails. Next, we will see how we can use Node.js to manage Asset Pipeline which is
a Rails feature.
Accept the prompt, by responding with a y. Use the following command to create a PostgreSQl
database cluster.
tp> sudo postgresql-setup initdb
xiv
Output
The following screenshot shows a Windows command prompt. The Linux terminal also
provides the same output.
This will automatically update your Rails installation. The next time you restart your
application, it will pick up this latest version of Rails. While using this command, make sure
you are connected to the internet.
Installation Verification
You can verify if everything is set up according to your requirements or not. Use the following
command to create a demo project.
tp> rails new demo
Output
xv
It will generate a demo rail project; we will discuss about it later. Currently we have to check if
the environment is set up or not. Next, use the following command to run WEBrick web server
on your machine.
tp> cd demo
tp> rails server
xvi
exist in this universe and how the items in it relate to each other. This is equivalent to
modeling a database structure to keep the entities and their relationship.
Specify what can happen in this domain − The domain model is static; you have to
make it dynamic. Addresses can be added to an address book. Musical scores can be
purchased from music stores. Users can log in to a dating service. Students can register
for classes at a university. You need to identify all the possible scenarios or actions that
the elements of your domain can participate in.
Choose and design the publicly available views of the domain − At this point, you can
start thinking in Web-browser terms. Once you've decided that your domain has
students, and that they can register for classes, you can envision a welcome page, a
registration page, and a confirmation page, etc. Each of these pages, or views, shows the
user how things stand at a certain point.
Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC)
framework.
Model (ActiveRecord )
It maintains the relationship between the objects and the database and handles validation,
association, transactions, and more.
This subsystem is implemented in ActiveRecord library, which provides an interface and
binding between the tables in a relational database and the Ruby program code that manipulates
database records. Ruby method names are automatically generated from the field names of
database tables.
View ( ActionView )
It is a presentation of data in a particular format, triggered by a controller's decision to present
the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate
with AJAX technology.
This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb)
based system for defining presentation templates for data presentation. Every Web connection
to a Rails application results in the displaying of a view.
Controller ( ActionController )
The facility within the application that directs traffic, on the one hand, querying the models for
specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into
a form that fits the needs of a given view.
This subsystem is implemented in ActionController, which is a data broker sitting between
ActiveRecord (the database interface) and ActionView (the presentation engine).
xvii
Pictorial Representation of MVC Framework
Given below is a pictorial representation of Ruby on Rails Framework −
You will see subdirectories including (but not limited to) the following −
actionpack-x.y.z
activerecord-x.y.z
rails-x.y.z
Over a windows installation, you can find them like this −
tp>cd ruby\lib\ruby\gems\2.2.0\gems
ruby\lib\ruby\gems\2.2.0\gems\>dir
You will see subdirectories including (but not limited to) the following −
xviii
ActionView and ActionController are bundled together under ActionPack.
ActiveRecord provides a range of programming techniques and shortcuts for manipulating data
from an SQL database. ActionController and ActionView provides facilities for manipulating
and displaying that data. Rails ties it all together.
xix
Sessions
To save data across multiple requests, you can use either the session or the flash hashes. A flash
stores a value (normally text) until the next request, while a session stores data during the
complete session.
session[:user] = @user
session :only => :foo, # only for :foo when doing HTTPS
Cookies
Following is the syntax for setting cookies −
# Set a simple session cookie
cookies[:user_name] = "david"
cookies.size # => 2
xx
Following is the syntax for deleting cookies −
cookies.delete :user_name
During the life cycle of an active record object, you can hook into 8
events −
(-) save
(-) valid?
before_validation
before_validation_on_create
(-) validate
(-) validate_on_create
after_validation
after_validation_on_create
before_save
before_create
(-) create
after_create
after_save
xxi
Examples
class Subscription < ActiveRecord::Base
before_create :record_signup
private
def record_signup
self.signed_up_on = Date.today
end
end
before_destroy{
before_destroy{
end
This examples shows how we can nest with_scope to fetch different results based on
requirements.
# SELECT * FROM employees
# LIMIT 10
# Will be written as
Employee.with_scope(
:limit => 10 }) do
Employee.find(:all)
xxii
end
# LIMIT 10
# Will be written as
Employee.with_scope(
Employee.find(:all)
Employee.find(:all)
end
end
# is written as
Employee.with_scope(
Employee.find(:all)
Employee.find(:all)
end
Employee.find(:all)
end
end
xxiii
Following are the ways to find out records with and without conditions −
The following will find an author with ID 50.
Author.find(50)
The following will find all the authors with first name alam.
Author.find :all
The following will find the first record of the authors with first name alam.
Author.find :first
If there is a field last_name, then you can use the following to find records by last name.
Person.find_all_by_last_name(last_name)
xxiv
If there are fields user_name and password, then you can use the following to find a record for
a given user name and password.
Person.find_by_user_name_and_password(user_name, password)
Ruby provides many useful scripts, which you use during your project implementation. Here are
few scripts which you will use most frequently.
Script Description
Script Example
Here is an example to call a script. Following script will start development server.
C:\ruby> ruby script/server
Ruby provides many useful scripts, which you use during your project implementation. Here are
few scripts which you will use most frequently.
Script Description
xxv
script/breakpointer Starts the breakpoint server.
Script Example
Here is an example to call a script. Following script will start development server.
C:\ruby> ruby script/server
Ruby provides a script called Generator. This script can be used to generate many useful items
in Rails. Most important generators are listed below.
Generator Description
xxvi
script/generate plugin PluginName Generates Plugin.
Following is the list of options, which can be used along with generators −
-p, --pretend Run but do not make any changes.
-f, --force Overwrite files that already exist.
-s, --skip Skip files that already exist.
-q, --quite Suppress normal output.
-t, --backtrace Debugging: show backtrace on errors.
-h, --help Show this help message.
-c, --svn Modify files with subversion.
xxvii
AngularJS
What is AngularJS?
AngularJS is an open source web application framework. It was originally developed in 2009 by
Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.
Definition of AngularJS as put by its official documentation is as follows −
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template
language and lets you extend HTML's syntax to express your application's components clearly and
succinctly. Angular's data binding and dependency injection eliminate much of the code you currently
have to write. And it all happens within the browser, making it an ideal partner with any server
technology.
Features
AngularJS is a powerful JavaScript based development framework to create RICH
Internet Application(RIA).
AngularJS provides developers options to write client side application (using JavaScript)
in a clean MVC(Model View Controller) way.
Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache License version 2.0.
Overall, AngularJS is a framework to build large scale and high performance web application
while keeping them as easy-to-maintain.
Core Features
Following are most important core features of AngularJS −
Data-binding − It is the automatic synchronization of data between model and view
components.
Scope − These are objects that refer to the model. They act as a glue between controller
and view.
Controller − These are JavaScript functions that are bound to a particular scope.
Services − AngularJS come with several built-in services for example $https: to make a
XMLHttpRequests. These are singleton objects which are instantiated only once in app.
Filters − These select a subset of items from an array and returns a new array.
xxviii
Directives − Directives are markers on DOM elements (such as elements, attributes, css,
and more). These can be used to create custom HTML tags that serve as new, custom
widgets. AngularJS has built-in directives (ngBind, ngModel...)
Templates − These are the rendered view with information from the controller and
model. These can be a single file (like index.html) or multiple views in one page using
"partials".
Routing − It is concept of switching views.
Model View Whatever − MVC is a design pattern for dividing an application into
different parts (called Model, View and Controller), each with distinct responsibilities.
AngularJS does not implement MVC in the traditional sense, but rather something closer
to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as
Model View Whatever.
Deep Linking − Deep linking allows you to encode the state of application in the URL
so that it can be bookmarked. The application can then be restored from the URL to the
same state.
Dependency Injection − AngularJS has a built-in dependency injection subsystem that
helps the developer by making the application easier to develop, understand, and test.
xxix
Concepts
Following diagram depicts some important parts of AngularJS which we will discuss in detail in
the subsequent chapters.
Advantages of AngularJS
AngularJS provides capability to create Single Page Application in a very clean and
maintainable way.
AngularJS provides data binding capability to HTML thus giving user a rich and
responsive experience
AngularJS code is unit testable.
AngularJS uses dependency injection and make use of separation of concerns.
AngularJS provides reusable components.
With AngularJS, developer write less code and get more functionality.
xxx
In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
On top of everything, AngularJS applications can run on all major browsers and smart phones
including Android and iOS based phones/tablets.
Disadvantages of AngularJS
Though AngularJS comes with lots of plus points but same time we should consider the
following points −
Not Secure − Being JavaScript only framework, application written in AngularJS are not
safe. Server side authentication and authorization is must to keep an application secure.
Not degradable − If your application user disables JavaScript then user will just see the
basic page and nothing more.
xxxi
The Model
The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.
The View
A presentation of data in a particular format, triggered by the controller's decision to present the
data. They are script-based template systems such as JSP, ASP, PHP and very easy to integrate
with AJAX technology.
The Controller
The controller responds to user input and performs interactions on the data model objects. The
controller receives input, validates it, and then performs business operations that modify the
state of the data model.
AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS uses
MVC methodology.
AngularJS directives are used to extend HTML. These are special attributes starting with ng-
prefix. We're going to discuss following directives −
xxxii
ng-app − This directive starts an AngularJS Application.
ng-init − This directive initializes application data.
ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
ng-repeat − This directive repeats html elements for each item in a collection.
ng-app directive
ng-app directive starts an AngularJS Application. It defines the root element. It automatically
initializes or bootstraps the application when web page containing AngularJS Application is
loaded. It is also used to load various AngularJS modules in AngularJS Application. In
following example, we've defined a default AngularJS application using ng-app attribute of a
div element.
<div ng-app = "">
...
</div>
ng-init directive
ng-init directive initializes an AngularJS Application data. It is used to put values to the
variables to be used in the application. In following example, we'll initialize an array of
countries. We're using JSON syntax to define array of countries.
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-
FR',name:'France'}]">
...
</div>
ng-model directive
This directive binds the values of AngularJS application data to HTML input controls. In
following example, we've defined a model named "name".
<div ng-app = "">
...
</div>
ng-repeat directive
ng-repeat directive repeats html elements for each item in a collection. In following example,
we've iterated over array of countries.
<div ng-app = "">
xxxiii
...
<ol>
</li>
</ol>
</div>
Example
Following example will showcase all the above mentioned directives.
testAngularJS.htm
<html>
<head>
<title>AngularJS Directives</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-
FR',name:'France'}]">
<ol>
</li>
</ol>
</div>
xxxiv
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</body>
</html>
Output
Open textAngularJS.htm in a web browser. Enter your name and see the result.
Expressions are used to bind application data to html. Expressions are written inside double
braces like {{ expression}}. Expressions behaves in same way as ng-bind directives. AngularJS
application expressions are pure javascript expressions and outputs the data where they are
used.
Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>
Using strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
Using object
<p>Roll No: {{student.rollno}}</p>
Using array
<p>Marks(Math): {{marks[3]}}</p>
Example
Following example will showcase all the above mentioned expressions.
testAngularJS.htm
<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>
xxxv
<div ng-app = "" ng-init = "quantity = 1;cost = 30; student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};marks = [80,90,75,73,60]">
<p>Marks(Math): {{marks[3]}}</p>
</div>
</body>
</html>
Output
Open textAngularJS.htm in a web browser. See the result.
Scope
xxxvi
Even with traditional, multi-page sites, having solutions that make development
and testing of those sites quicker and easier is always going to be welcome and
appealing.
AngularJS already has the ability to handle your project’s wireframes during initial
development and testing, as well as other demands like animations and transitions
for powerful websites and web applications. With more and more web designers
and developers turning to these JavaScript-powered solutions, we can also expect
them to become even easier to use as a whole – which is ultimately great news for
everyone looking to design and develop rich web experiences.
FUTURE ENHANCEMENT
In future our report could help others to easily develop websites using ruby on rails
and angular js.
xxxviii