CSC/ECE 517 Fall 2012/ch2b 1w61 ns: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(66 intermediate revisions by the same user not shown)
Line 1: Line 1:
==Connecting Architectural Concepts to Rails Apps==
==Overview==
The scope of this wiki is to create a document explaining the contents of the video lecture [http://www.youtube.com/watch?v=kcKR1Y2hRes SaaS - 3.9 - Rails from Zero to CRUD]. Details outside this video have not been covered. This document gives an introduction about the MVC Framework and how a typical Rails application maps to the same. It also gives an overview of the flow of execution of a Rails application, all the way from when a request is issued by the web browser, to an appropriate web page being loaded.


The structure of a typical Rake file is as follows:
==Connecting Architectural Concepts to Rails Applications==


The structure of a typical [http://rake.rubyforge.org/files/doc/rakefile_rdoc.html Rake] file is as follows:
<pre>
app      /models/, views/, controllers/
app      /models/, views/, controllers/
         /helpers
         /helpers
         /assets/stylesheets/application.css
         /assets/stylesheets/application.css


config /routes.rb
config /routes.rb
        /database.yml
        /database.yml
 
db /development.sqlite3,test.sqlite3
        /migrate/
 
log /development.log, test.log
</pre>
 
There is no special format for a Rakefile. A Rakefile contains executable [http://www.ruby-lang.org/en/ Ruby] code. Anything legal in a ruby script is allowed in a Rakefile. It is tailored to specifying tasks and actions, the idioms used in a Rakefile are designed to support that.
 
===Tasks===
 
Tasks are the main unit of work in a Rakefile. Tasks usually have a name, a list of prerequisites and a list of actions.
<pre>
task :name //the task method takes a single parameter which is the name of the task
</pre>
 
Any prerequisites are given as a list which are inclosed in square brackets followed by the name and an arrow (=>).
<pre>
task :name => [:prereq1, :prereq2]
</pre>
 
Actions can be defined by passing a block to the task method. Any Ruby code can be placed in the block. The block may reference the task object via the block parameter.
<pre>
task :name => [:prereq1, :prereq2] do |t|
  # actions (may reference t)
end
</pre>
 
==A Typical Rails Application==


db /development.sqlite3,test.sqlite3
[http://en.wikipedia.org/wiki/Ruby_on_Rails '''Ruby on Rails'''] is a web application development framework written in the [http://www.ruby-lang.org/en/ Ruby] language. It has been designed to make programming web applications easier and allows the programmer to write less code when compared to other languages and frameworks.
        /migrate/
An exemplary Rails application has the following structure.


log /development.log, test.log
[[File:Rails_Layered_Architecture.PNG‎|500 px|thumb|center|alt=Layered Architecture of a Rails Application|Layered Architecture of a Rails Application]]


There is no special format for a Rakefile. A Rakefile contains executable Ruby code. Anything legal in a ruby script is allowed in a Rakefile.
The upper most layer consists of the web application that is seen running on the browser and this is the part of the application that the user is made to see.
There is no special syntax in a Rakefile, there are some conventions that are used in a Rakefile that are a little unusual in a typical Ruby program. Since a Rakefile is tailored to specifying tasks and actions, the idioms used in a Rakefile are designed to support that.
Tasks are the main unit of work in a Rakefile. Tasks have a name (usually given as a symbol or a string), a list of prerequisites (more symbols or strings) and a list of actions (given as a block).
Rails is a web application development framework written in the Ruby language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks.


==Tier System==
The middle layer consists of the 3 tier architecture which provides horizontal scaling. The [http://en.wikipedia.org/wiki/Cascading_Style_Sheets CSS] style sheets are used to style the html view of the application. As seen in the diagram, the '''Presentation''' tier consists of the Web Server, the '''Logic''' tier is represented by the App Server and the '''Persistence Tier''' by the Database. The routes play a crucial role in communication between the Presentation tier and the Logic tier. The persistence tier consists of three different types of databases that are used during the course of development and testing of the application. All the activities carried out in setting up and testing the application are logged for future reference and easier debugging.


Each entity has a model, controller and a set of views.
The lowermost layer consists of the [http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller '''MVC'''] (Model View Controller) which is the core aspect of the Ruby On Rails application. Each entity has a model, controller and a set of views. This layer provides isolation of business logic from the user interface and also facilitates in keeping the code [http://en.wikipedia.org/wiki/Don't_repeat_yourself '''DRY'''](Don’t Repeat Yourself).
The css style sheets are used to style the html view of the application.
Routes.rb maps the URI’s and methods to things that happen in the controller.
The routes play a crucial role in communication between the Presentation tier and the logic tier.
The persistence tier consists of three different types of databases that are used during the course of development and testing of the application.
All the activities carried out in setting up and testing the application are logged for future reference and easier debugging.


==Rails as an MVC Framework==
==Rails as an MVC Framework==


Our Application consists of:
The core of the Rails application is the [http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller '''MVC'''] i.e the '''Model'''-'''View'''-'''Controller'''.
Controllers – which effectively make use of the routing subsystem
As mentioned earlier, the MVC helps to keeps your business logic separated from the [http://en.wikipedia.org/wiki/HTML HTML] views and also keeps your code clean and neat helping in easier maintenance.
Models – which are linked to the persistence tier i.e the database and store the data in the relational database tables
 
Controllers are needed to make views to be rendered which turn .haml to .html which is the view markup
[[File:mvc-small.jpg|135 px|thumb|left|alt=MVC]]
Models are sub classes of ActiveRecord::Base which is an object relational mapping layer (ORM layer)that is useful in connecting to the database
 
Views are subclasses of ActionView consisting of reusable code that is used to manipulate views
===Model===
Controllers are subclasses of ApplicationController which provide common functionality which can be used accordingly in the user application
 
Model represents the information or data of the application and the rules to manipulate that data. It is the Model that is linked to the Persistence Tier and is primarily used for managing the rules of interaction with a corresponding relational database table. Typically, each table in the database will correspond to one model in the application. A major bulk of the application’s business logic is concentrated in the models.
 
Models are sub classes of <code>'''''ActiveRecord::Base'''''</code> which is an [http://en.wikipedia.org/wiki/Object-relational_mapping '''Object Relational Mapping'''] layer (ORM) that is useful in connecting to the database.
 
[[File:mvc-architecture.png|425 px|thumb|right|alt=MVC|Model View Controller Architecture]]
 
===View===
 
View represents the user interface of the application. They are often HTML files with embedded Ruby code that perform tasks related solely to the presentation of the data. It is the View that is responsible for providing data to the web browser or any other source that accesses the application.
 
Views are sub classes of <code>'''''ActionView'''''</code> which provides reusable code that is used to manipulate views.
 
===Controller===
 
Controller is the component that glues the models and views. The controller is responsible for processing the incoming requests from the web browser, effectively use the routing system, interrogating the models for data, and passing that data and causing the rendering of the correct view for presentation.
 
Controllers are sub classes of <code>'''''ApplicationController'''''</code> which provide common functionality which can be used accordingly in the user application.
 
==A Trip through a Rails Application==
 
This section describes how the moving parts of a rail application all fit in and work smoothly.
 
[[File:step1.png|220 px|thumb|left|alt=step1|Step 1]]
<span style="font-variant:small-caps"><u>'''Step 1'''</u></span> The browser issues a request for the <tt>/users</tt> [http://en.wikipedia.org/wiki/Uniform_resource_identifier URI]. This could be the result of typing a URI in the address bar or clicking on a link. For example, the URI shown in the diagram is issued when the user tries to access movie details.
 
<span style="font-variant:small-caps"><u>'''Step 2'''</u></span> A Rails server running locally on port 3000 receives the request and the dispatcher is invoked. Rails tries to find a route (in the file <tt>config/routes.rb</tt>) to match the URI <tt>/movies/3</tt>. The URI to the appropriate [http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol HTTP] method such as get or post to the appropriate controller action is mapped. (The [http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods '''GET'''] operation, used for reading data on the web whereas the [http://en.wikipedia.org/wiki/POST_(HTTP) '''POST'''] is the request sent by your browser when you submit a form). Also, optional parameters, if present, get extracted. Routeʼs ''wildcard'' parameters (For example: <tt>:id</tt>), plus any stuff after ''?'' in [http://en.wikipedia.org/wiki/Uniform_resource_locator URL], are put  into <tt>params[]</tt> hash accessible in controller actions.


===The MVC Architecture===
[[File:step2.png|270 px|thumb|right|alt=step2|Step 2]]
At the core of Rails is the Model, View, Controller architecture, usually just called MVC.
The default route <tt>:controller/:action/:id</tt> matches the URI and the dispatcher instantiates the movies controller and invokes its show method with the <tt>:id</tt> parameter set to <tt>3</tt>. i.e the URI invokes the config/routes.rb file. This is mapped to the HTTP '''GET''' method, of the <tt>movies</tt> controller, with action being <tt>show</tt>. The <tt>:id</tt> field is going to be a wildcard (depicted by : ). When this route is matched by an appropriate controller (movies_controller.rb) the <tt>show</tt> method then gets invoked.
MVC benefits include:


Isolation of business logic from the user interface
<span style="font-variant:small-caps"><u>'''Step 3'''</u></span> Once the controller and the controller action have been decided, the  appropriate instance variables that are going to be used by the views are set. The views are arranged such that the subdirectories and file names of views, match the controllers & action names.  
Ease of keeping code DRY
Making it clear where different types of code belong for easier maintenance
2.1.1 Models


A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.
[[File:step3.png|220 px|thumb|left|alt=step3|Step 3]]
Here, as the <tt>routes.rb</tt> file points to a movies controller, an appropriate file movies_controller.rb is found, within which the show method is invoked. Now, as seen earlier, the wildcard <tt>:id</tt> is available here as routes maps this to the value <tt>3</tt> from the URI and then passed to params hash(which is duck typed to be a hash). This <tt>id</tt> is then used to lookup a movie in the movies database. The controller captured the appropriate movie in the instance variable <tt>@mv</tt>, which is passed to the view. This is done as the local variable <tt>id</tt> goes out of scope once outside the controller method.  


2.1.2 Views
[[File:step4.png|270 px|thumb|right|alt=step4|Step 4]]
<span style="font-variant:small-caps"><u>'''Step 4'''</u></span> Controller action eventually renders a view using the instance variables that were setup in the controller. A naming convention is being followed which clearly states which view file inside which subdirectory is to be followed i.e the controller (<tt>Movies</tt>) tells us which subdirectory under views, and the controller action (<tt>show</tt>) tells us the base file name of the view to be called. This naming convention is called [http://en.wikipedia.org/wiki/Convention_over_configuration '''Convention over configuration'''].


Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
<br>
[[File:full-picture.png|650 px|thumb|center|alt=full-picture|The Full Picture]]


2.1.3 Controllers
==Rails Philosophy==
===Convention over configuration===


Controllers provide the “glue” between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
[[File:coc.png|150 px|thumb|right|alt=coc]]
[http://en.wikipedia.org/wiki/Convention_over_configuration ''Convention over configuration''] primarily means that a developer only needs to specify unconventional aspects of the application. This is a very important principle behind Rails. It goes hand-in-hand with another attribute of Rails, that it is '''opinionated software'''. The Rails design embodies lots of opinions about how you should structure your code, name your classes and files, and organize your database tables. There are methods to override most of these conventions, but if you go with the flow and follow the conventions, then you can avoid almost all configuration code. That’s convention over configuration — and the payoff is huge.


==Rails Philosophies==
In earlier app frameworks, a separate configuration file used to be maintained that used to explicitly state correspondences between the different objects. In ruby, due to reflection and metaprogramming, we can query objects about themselves, and hence such a file is no longer required if proper naming conventions as mentioned above are followed.


The Rails philosophy includes several guiding principles:
===Donʼt Repeat Yourself (DRY)===
DRY – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.
• Convention Over Configuration – means that Rails makes assumptions about what you want to do and how you’re going to do it, rather than requiring you to specify every little thing through endless configuration files.
• REST is the best pattern for web applications – organizing your application around resources and standard HTTP verbs is the fastest way to go.


[[File:dry.png|150 px|thumb|right|alt=dry]]
[http://en.wikipedia.org/wiki/Don't_repeat_yourself ''Don't repeat yourself''] means that information is located in a single, unambiguous place. Keeping your code '''DRY''' means avoiding repetition. In its simplest form, it means that if you need the same code in two places, put it in a method so you can write it once and call if from both places. It sometimes increases the amount of work it takes to write your code initially, but it save headaches in the long run. There are a number of mechanisms that rails offers to extract common functionality to ensure that you do not end up repeating code with minor variations, but it is something you need to pay attention to when writing your code.


==References==
==References==


[http://docs.rubyrake.org/user_guide/chapter03.html]
#http://docs.rubyrake.org/user_guide/chapter03.html
[http://rake.rubyforge.org/files/doc/rakefile_rdoc.html]
#http://rake.rubyforge.org/files/doc/rakefile_rdoc.html
[http://guides.rubyonrails.org/getting_started.html]
#http://guides.rubyonrails.org/getting_started.html
#http://en.wikibooks.org/wiki/Ruby_on_Rails/Getting_Started/Model-View-Controller
#https://class.coursera.org/saas/lecture/preview/index
#http://www.youtube.com/watch?v=kcKR1Y2hRes
#http://ruby.railstutorial.org/chapters/beginning#sec-mvc
#http://en.wikipedia.org/wiki/Ruby_on_Rails
#http://en.wikipedia.org/wiki/Convention_over_Configuration
#http://en.wikipedia.org/wiki/Don%27t_Repeat_Yourself
#http://www.buildingwebapps.com/articles/79188-understanding-ruby-on-rails

Latest revision as of 23:51, 19 November 2012

Overview

The scope of this wiki is to create a document explaining the contents of the video lecture SaaS - 3.9 - Rails from Zero to CRUD. Details outside this video have not been covered. This document gives an introduction about the MVC Framework and how a typical Rails application maps to the same. It also gives an overview of the flow of execution of a Rails application, all the way from when a request is issued by the web browser, to an appropriate web page being loaded.

Connecting Architectural Concepts to Rails Applications

The structure of a typical Rake file is as follows:

app      /models/, views/, controllers/
         /helpers
         /assets/stylesheets/application.css

config	 /routes.rb
         /database.yml

db	 /development.sqlite3,test.sqlite3
         /migrate/

log	 /development.log, test.log

There is no special format for a Rakefile. A Rakefile contains executable Ruby code. Anything legal in a ruby script is allowed in a Rakefile. It is tailored to specifying tasks and actions, the idioms used in a Rakefile are designed to support that.

Tasks

Tasks are the main unit of work in a Rakefile. Tasks usually have a name, a list of prerequisites and a list of actions.

task :name //the task method takes a single parameter which is the name of the task

Any prerequisites are given as a list which are inclosed in square brackets followed by the name and an arrow (=>).

task :name => [:prereq1, :prereq2]

Actions can be defined by passing a block to the task method. Any Ruby code can be placed in the block. The block may reference the task object via the block parameter.

task :name => [:prereq1, :prereq2] do |t|
  # actions (may reference t)
end

A Typical Rails Application

Ruby on Rails is a web application development framework written in the Ruby language. It has been designed to make programming web applications easier and allows the programmer to write less code when compared to other languages and frameworks.

An exemplary Rails application has the following structure.

Layered Architecture of a Rails Application
Layered Architecture of a Rails Application

The upper most layer consists of the web application that is seen running on the browser and this is the part of the application that the user is made to see.

The middle layer consists of the 3 tier architecture which provides horizontal scaling. The CSS style sheets are used to style the html view of the application. As seen in the diagram, the Presentation tier consists of the Web Server, the Logic tier is represented by the App Server and the Persistence Tier by the Database. The routes play a crucial role in communication between the Presentation tier and the Logic tier. The persistence tier consists of three different types of databases that are used during the course of development and testing of the application. All the activities carried out in setting up and testing the application are logged for future reference and easier debugging.

The lowermost layer consists of the MVC (Model View Controller) which is the core aspect of the Ruby On Rails application. Each entity has a model, controller and a set of views. This layer provides isolation of business logic from the user interface and also facilitates in keeping the code DRY(Don’t Repeat Yourself).

Rails as an MVC Framework

The core of the Rails application is the MVC i.e the Model-View-Controller. As mentioned earlier, the MVC helps to keeps your business logic separated from the HTML views and also keeps your code clean and neat helping in easier maintenance.

MVC

Model

Model represents the information or data of the application and the rules to manipulate that data. It is the Model that is linked to the Persistence Tier and is primarily used for managing the rules of interaction with a corresponding relational database table. Typically, each table in the database will correspond to one model in the application. A major bulk of the application’s business logic is concentrated in the models.

Models are sub classes of ActiveRecord::Base which is an Object Relational Mapping layer (ORM) that is useful in connecting to the database.

MVC
Model View Controller Architecture

View

View represents the user interface of the application. They are often HTML files with embedded Ruby code that perform tasks related solely to the presentation of the data. It is the View that is responsible for providing data to the web browser or any other source that accesses the application.

Views are sub classes of ActionView which provides reusable code that is used to manipulate views.

Controller

Controller is the component that glues the models and views. The controller is responsible for processing the incoming requests from the web browser, effectively use the routing system, interrogating the models for data, and passing that data and causing the rendering of the correct view for presentation.

Controllers are sub classes of ApplicationController which provide common functionality which can be used accordingly in the user application.

A Trip through a Rails Application

This section describes how the moving parts of a rail application all fit in and work smoothly.

step1
Step 1

Step 1 The browser issues a request for the /users URI. This could be the result of typing a URI in the address bar or clicking on a link. For example, the URI shown in the diagram is issued when the user tries to access movie details.

Step 2 A Rails server running locally on port 3000 receives the request and the dispatcher is invoked. Rails tries to find a route (in the file config/routes.rb) to match the URI /movies/3. The URI to the appropriate HTTP method such as get or post to the appropriate controller action is mapped. (The GET operation, used for reading data on the web whereas the POST is the request sent by your browser when you submit a form). Also, optional parameters, if present, get extracted. Routeʼs wildcard parameters (For example: :id), plus any stuff after ? in URL, are put into params[] hash accessible in controller actions.

step2
Step 2

The default route :controller/:action/:id matches the URI and the dispatcher instantiates the movies controller and invokes its show method with the :id parameter set to 3. i.e the URI invokes the config/routes.rb file. This is mapped to the HTTP GET method, of the movies controller, with action being show. The :id field is going to be a wildcard (depicted by : ). When this route is matched by an appropriate controller (movies_controller.rb) the show method then gets invoked.

Step 3 Once the controller and the controller action have been decided, the appropriate instance variables that are going to be used by the views are set. The views are arranged such that the subdirectories and file names of views, match the controllers & action names.

step3
Step 3

Here, as the routes.rb file points to a movies controller, an appropriate file movies_controller.rb is found, within which the show method is invoked. Now, as seen earlier, the wildcard :id is available here as routes maps this to the value 3 from the URI and then passed to params hash(which is duck typed to be a hash). This id is then used to lookup a movie in the movies database. The controller captured the appropriate movie in the instance variable @mv, which is passed to the view. This is done as the local variable id goes out of scope once outside the controller method.

step4
Step 4

Step 4 Controller action eventually renders a view using the instance variables that were setup in the controller. A naming convention is being followed which clearly states which view file inside which subdirectory is to be followed i.e the controller (Movies) tells us which subdirectory under views, and the controller action (show) tells us the base file name of the view to be called. This naming convention is called Convention over configuration.


full-picture
The Full Picture

Rails Philosophy

Convention over configuration

coc

Convention over configuration primarily means that a developer only needs to specify unconventional aspects of the application. This is a very important principle behind Rails. It goes hand-in-hand with another attribute of Rails, that it is opinionated software. The Rails design embodies lots of opinions about how you should structure your code, name your classes and files, and organize your database tables. There are methods to override most of these conventions, but if you go with the flow and follow the conventions, then you can avoid almost all configuration code. That’s convention over configuration — and the payoff is huge.

In earlier app frameworks, a separate configuration file used to be maintained that used to explicitly state correspondences between the different objects. In ruby, due to reflection and metaprogramming, we can query objects about themselves, and hence such a file is no longer required if proper naming conventions as mentioned above are followed.

Donʼt Repeat Yourself (DRY)

dry

Don't repeat yourself means that information is located in a single, unambiguous place. Keeping your code DRY means avoiding repetition. In its simplest form, it means that if you need the same code in two places, put it in a method so you can write it once and call if from both places. It sometimes increases the amount of work it takes to write your code initially, but it save headaches in the long run. There are a number of mechanisms that rails offers to extract common functionality to ensure that you do not end up repeating code with minor variations, but it is something you need to pay attention to when writing your code.

References

  1. http://docs.rubyrake.org/user_guide/chapter03.html
  2. http://rake.rubyforge.org/files/doc/rakefile_rdoc.html
  3. http://guides.rubyonrails.org/getting_started.html
  4. http://en.wikibooks.org/wiki/Ruby_on_Rails/Getting_Started/Model-View-Controller
  5. https://class.coursera.org/saas/lecture/preview/index
  6. http://www.youtube.com/watch?v=kcKR1Y2hRes
  7. http://ruby.railstutorial.org/chapters/beginning#sec-mvc
  8. http://en.wikipedia.org/wiki/Ruby_on_Rails
  9. http://en.wikipedia.org/wiki/Convention_over_Configuration
  10. http://en.wikipedia.org/wiki/Don%27t_Repeat_Yourself
  11. http://www.buildingwebapps.com/articles/79188-understanding-ruby-on-rails