General Ruby on Rails concepts Flashcards
How the web works:
What is HTTP and how does it work?
The web has a bunch of layers (Application, TCP, Internet, Hardware layers) that are all connected. But basically, it works through HTTP (Hypertext Transfer Protocol).
The HTTP works like a request — response cycle in the client — server model.
We have a client, a web browser. We type the www.google.com URL, and the client submits the HTTP request (request message) to the server. The server returns the HTTP response (response message — in this case, the response is the HTML from Google’s website).
The client does the request and receives the response from the server. The client handles the UI and user interactions. On the server, we can store and retrieve data (on databases), process logic on the background (workers/jobs), and a lot of other things.
What is the MVC architecture?
MVC stands for Model, View, and Controller. It’s basically an architecture for how applications are built.
In this architecture, we have the “separation of the concerns” among Models, Views and, Controllers. Each part has its own responsibility.
In MVC, what is the Model and what is its role?
It “maintains the relationship between Object and Database and handles validation, association, transactions”
The Model represents the data, and does nothing else. Basically, the Model is a class that maps to the data table. It can have methods for manipulating the corresponding data.
Put differently: Each model (can) represent a database table (in case of SQL databases). This model object gains capabilities (inherited from ActiveRecord — Rails class) to retrieve, save, edit, and delete data from database table. ActiveRecord allows you to present the data from database rows as objects and embellish these data objects with business logic methods.
NOTE: We use model objects as a layer between our application and the database.
Besides that relation with the database, the model can create validations and associations between models.
In MVC, what is the View and what is its role?
“A presentation of data in a particular format, triggered by a controller’s decision to present the data.”
This is the presentation of the request’s response. This presentation can be in a bunch of format types: PDF, HTML, JSON, etc. The final result of a view will likely be the user interface (UI) — Part of the “Client.”
In MVC, what is the Controller and what is its role?
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services.
It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well.
It manages helper modules, which extend the capabilities of the view templates without bulking up their code.
IN SUMMARY, the user does stuff (request to the server), the the Rails application has the router to map the URL path to the right controller. In the controller, we can do all things with a model (or more than one model) — CRUD meaning creating, reading, updating, deleting data — and render a view to the user.
What does the Devise gem do?
Devise is a popular authentication solution for Rails applications. It helps you check users credentials and let them into the site or not, or you can pick and choose additional authentication features such as:
- password reset via email
- locking users out after a number of failed attempts
- email activation being required before a new account is allowed to sign in
- timing users out after a period of inactivity
Basically, it’s a Rails tool/solution for managing user authentication.
Footnote: Devise takes care of a lot of the legwork of setting up an authentication system. You could build your own with bcrypt or the Active record secure password functionality but you’d need to implement the forms, helpers and emails on your own. Devise is a 10 minute set up.
What are params? What are the 3 types of params?
Params are key:value pairs (hashes) passed from the users browsers to the application.
Three groups of parameters:
- User supplied parameters (query string)
- GET (http://domain.com/url?param1=value1¶m2=value2 will set params[:param1] and params[:param2])
- POST (e.g. JSON, XML will automatically be parsed and stored in params)
- Note: By default, Rails duplicates the user supplied parameters and stores them in params[:user] if in UsersController, can be changed with wrap_parameters setting - Routing parameters – links to a specific object (uses the id of the object, like a SKU)
match ‘/user/:id’ in routes.rb will set params[:id] - Post params – info to pass in arguments in creating e.g. articles, products, blog posts, user profile, etc., through a form.
- Default parameters
params[:controller] and params[:action] is always available and contains the current controller and action
Rails uses something routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params for that controller. For example, a URL like http://example.com/products/42 will set params[:id] to 42.
What is Rails?
An open source Ruby framework for developing database-backed web applications.
Full Stack Framework
- includes everything needed to create a database-driven web application, using the Model-View-Controller pattern.
Convention over Configuration
- Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions. (Most web development frameworks for .NET or Java force you to write pages of configuration code.)
Your application code and your running database already contain everything that Rails needs to know!
Rails strengths:
- What is Active Record framework?
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
Rails strengths:
- What is Scaffolding?
Scaffolding generally refers to a quickly set up skeleton for an app (other platforms have it as well). Rails basically creates basic CRUD (create, read, update, delete) screens.
You then go through and add the code to manage the data the way you want replacing the scaffolding. It is generally only intended to get you up and running quickly.
Rails strengths:
- What is Rake?
The rake utility allows you to execute all your automated tests with one command.
Rails strengths:
- How many default environments does Rails create at set up and what are they for?
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.
In order develop a web application using Rails, what four software does one need to set up?
To develop a web application using Ruby on Rails Framework, you need to install the following software −
Ruby
The Rails Framework
A Web Server
A Database System (e.g. PostgreSQL)
What is a Framework?
A framework is a program, set of programs, and/or code library that writes most of your application for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want.
So basically a framework is something that takes care of redundant basic tasks so that sophisticated applications can be written on top of it in simple manner. Frameworks are generally generic add-on on top of a programming language. They don’t function by themselves, code needs to be written that utilizes that framework’s feature to give the framework life.
In simple terms, you can call libraries, while frameworks call YOUR code.
What are the three primary tasks you have to perform when you write a Rails application? (think M-V-C)
When you set out to write a Rails application, leaving aside the configuration and other housekeeping chores, you have to perform three primary tasks:
1) MODEL: describe and model your application’s domain
− The domain is the universe of your application. The domain may be a music store, a university, a dating service, an address book, or a hardware inventory. So here you have to figure out what’s in it, what entities 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.
2) CONTROLLER: 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.
3) VIEW: 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.
Ruby on Rails MVC Framework – the Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems. Explain each:
Model (ActiveRecord )
View ( ActionView )
Controller ( ActionController )
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.
This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation in a human readable format.
Controller ( ActionController )
A controller’s purpose is to receive specific requests for the application. It’s 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).
NOTE: ActionController and ActionView are bundled together under ActionPack. These two layers are bundled in a single package due to their heavy interdependence.
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.
When first setting up a Rails project, what does the ‘rails demo’ command do?
‘rails demo’ is a Rails helper command that sets up a demo application along with the entire (default) directory structure for the application.
Explain the purpose of each directory in the directory structure:
app
app/controllers
app/helpers
app/models
app/view
app/view/layouts
components
config
db
doc
lib
log
public
script
test
vendor
Apart from these directories, the following file is also in the directory:
Rakefile
app − It organizes your application components. It’s got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).
app/controllers − The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user.
app/helpers − The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.
app/models − The models subdirectory holds the classes that model and wrap the data stored in our application’s database.
app/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user’s browser.
app/view/layouts − Holds the template files for layouts to be used with views.
components − This directory holds components, tiny self-contained applications that bundle model, view, and controller.
config − This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.
db − Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.
doc − Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation.
lib − You’ll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).
log − Error logs go here. Rails creates scripts that help you manage various error logs. You’ll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).
public − Like the public directory for a web server, this directory has web files that don’t change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).
script − This directory holds scripts to launch and manage the various tools that you’ll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).
test − The tests you write and those that Rails creates for you, all goes here. You’ll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).
vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here.
Apart from these directories, there will be two files available in demo directory.
README − This file contains a basic detail about Rail Application and description of the directory structure explained above.
Rakefile − This file helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation.
How does one create a new Rails application?
Create a project folder, mkdir into in, then run the command ‘rails new [name_for_your_project]. create a skeleton for library application. This will create the Rails directory structure in the current directory.
What does the ‘Rails server’ command do?
It starts the built-in WEBrick web server. It will be started from the application directory and run on port number 3000.
How many databases does Rails normally set up and and where can you configure them (to set usernames etc)?
Ruby on Rails recommends to create three databases - a database each for development, testing, and production environment. According to convention, their names should be −
[project_name]_development
[project_name]_production
[project_name]_test
You should initialize all three of them and create a user and password for them with full read and write privileges. You do this in the file database.yml, available in the library\config subdirectory.
About the Model layer, what does this statement mean?
“Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model.”
Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows −
- tables map to classes,
- rows map to objects and
- columns map to object attributes.
Rails Active Records provide 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.
Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straight forward mappings between database tables and application objects.