Ruby on Rails Flashcards
What is an MVC? What’s an example of an MVC that you’ve used, and in what context?
Model–view–controller (MVC) is an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.[1][2] The MVC design pattern decouples these major components allowing for efficient code reuse and parallel development.
Traditionally used for desktop graphical user interfaces (GUIs), this architecture has become popular for designing web applications and even mobile, desktop and other clients.[3] Popular programming languages like Java, C#, Ruby, PHP and others have popular MVC frameworks that are currently being used in web application development straight out of the box.
What is a has_many :through association?
A has_many :through
association: it builds new associations out of existing ones. It “traverses” two associations, first it gets the posts, then it gets the comments on those posts. Note that posts
is the name of a User
association, and comments
is the name of a Post
association.
Discuss MVC Interaction between its components
The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself.
The view means presentation of data in a particular format, triggered by a controller’s decision to present the data.
The controller is responsible for responding to the user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model.
Discuss the MVC components
The model is the central component of the pattern. It expresses the application’s behavior in terms of the problem domain, independent of the user interface.[6] It directly manages the data, logic and rules of the application.
A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
The third part or section, the controller, accepts input and converts it to commands for the model or view.[7]
What is Rack?
Rack is a middleware that sits between a web server and a web application framework to make writing frameworks and web servers that work with existing software easier. We can make a functional server with only a few lines of code from the Rack module.
In order to use Rack you have to give it an app that it will call after receiving and processing the request from the web server. A Rack app can do very complicated things internally (like Rails), but it can also be very simple. All a Rack app needs to do to function properly is respond to the call method when passed one argument consisting of env (the request environment generated by Rack::Server containing the request data) and then return a properly formatted response.
How can we use Rack to simulate “rails s” command in terminal? Examples?
Rack::Server.start( app: Proc.new do |env| ['200', {'Content-Type' => 'text/html'}, ['hello world']] end )
This is using Rack to start a web server and telling it that the app we are going use is the Proc we are making. Since Proc objects respond to the call method this constitutes a totally valid, if simple Rack application!
Using the env object and returning a properly formatted response object can be confusing when you’re doing something more complicated than just returning hello world, so Rack makes available Request and Response classes that provide a more friendly API.
app = Proc.new do |env| req = Rack::Request.new(env) res = Rack::Response.new res['Content-Type'] = 'text/html' res.write("Hello world!") res.finish end
In order to make our code a bit more readable we are going to create the app first and then pass it into Rack::Server#start.
This is creating an app that we could give to Rack that would simply return the text “Hello world!” Notice here we are creating req and res objects to make our lives easier. Setting the Content-Type header tells the browser what the server has given to it in response. We will only bother with HTML in this project. In order to actually put things into the response body you use Rack::Response#write. Finally you want to call Rack::Response#finish when the res is done being built so Rack knows to wrap everything up for you.
In order to actually have a functioning web application we need to actually give app to Rack.
Rack::Server.start( app: app, Port: 3000 ) You can specify whatever port you want here, but 3000 is a common choice.
Write the code above (both the app and the Rack::Server#start call) in bin/p01_basic_server.rb. Run the file with bundle exec ruby bin/p01_basic_server.rb (ensures you run with local gems), then in your browser navigate to http://localhost:3000. You should see Hello world!.
What would ActionController::Base look like under the hood?
ControllerBase#initialize should take a Rack::Request and Rack::Response object as inputs and save them as instance variables (ivars) for later use. The stored request will be used to help fill out the response in one of the actions (:new, :edit, etc.) defined within controllers that inherit from it.
First, write a method named #render_content(content, content_type). This should set the response object’s content_type and body. It should also set an instance variable, @already_built_response, so that it can check that content is not rendered twice.
Next, write a method named #redirect_to(url). Issuing a redirect consists of two parts, setting the ‘Location’ field of the response header to the redirect url and setting the response status code to 302. Do not use #redirect; set each piece of the response individually. Check the Rack::Response docs for how to set response header fields and statuses. Again, set @already_built_response to avoid a double render.
What is ERB?
What would it look like in pry?
ERB (Embedded RuBy) is a feature of Ruby that enables you to conveniently generate any kind of text, in any quantity, from templates. The templates themselves combine plain text with Ruby code for variable substitution and flow control, making them easy to write and maintain.
[1] pry(main)> require 'erb' => true [2] pry(main)> template = ERB.new('') => #, @filename=nil, @safe_level=nil, @src= "#coding:UTF-8\n_erbout = ''; _erbout.concat(( (1..10).to_a.join(\", \") ).to_s); _erbout.force_encoding(\_\_ENCODING\_\_)"> [3] pry(main)> template.result => "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
What is binding in Ruby?
What would it look like in pry?
binding is a Kernel method that packages up the environment bindings (variables, methods, and self) that are in-scope at the current point of a Ruby program and makes them available in another context
1] pry(main)> def f [1] pry(main)* x = 4 [1] pry(main)* binding [1] pry(main)* end => :f [2] pry(main)> context_within_f = f() => # [3] pry(main)> context_within_f.eval('x') => 4
Calling f creates a local variable, x, which would usually not be visible outside of the method. However, f returns the result of Kernel#binding, which is an instance of Binding. The Binding class has one important instance method, #eval, which takes in a string, running it as Ruby code within the context that was preserved in the Binding instance.
You can see that binding is a very special method, and we’ll hardly ever use it. However, it should make sense what it does: encapsulate all of the in-scope variables and methods, storing them in an object, so that the current context can be passed around and used in another context.
What is Action Controller::Base?
Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.
By default, only the ApplicationController in a Rails application inherits from ActionController::Base. All other controllers inherit from ApplicationController. This gives you one class to configure things such as request forgery protection and filtering of sensitive request parameters.
Discuss the different methods in Action Controller::Base.
Requests
For every request, the router determines the value of the controller and action keys. These determine which controller and action are called. The remaining request parameters, the session (if one is available), and the full request with all the HTTP headers are made available to the action through accessor methods. Then the action is performed.
Parameters
All request parameters, whether they come from a query string in the URL or form data submitted through a POST request are available through the params method which returns a hash. For example, an action that was performed through /posts?category=All&limit=5 will include { “category” => “All”, “limit” => “5” } in params.
Sessions
Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted, such as a Signup object constructed in a multi-paged process, or objects that don’t change much and are needed all the time, such as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it’s likely they could be changed unknowingly. It’s usually too much work to keep it all synchronized – something databases already excel at.
Responses
Each action results in a response, which holds the headers and document to be sent to the user’s browser. The actual response object is generated automatically through the use of renders and redirects and requires no user intervention.
Renders
Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It’s automatically configured. The controller passes objects to the view by assigning instance variables:
Redirects
Redirects are used to move from one action to another. For example, after a create action, which stores a blog entry to the database, we might like to show the user the new entry. Because we’re following good DRY principles (Don’t Repeat Yourself), we’re going to reuse (and redirect to) a show action that we’ll assume has already been created
Methods M make_response! R request, response W without_modules