Ruby/Rails Flashcards

1
Q

Explain the difference between Active Record and Action Pack in Rails?

A

In essence, while Active Record focuses on the data layer, allowing seamless interaction between the application and its database, Action Pack deals with the web request-response cycle, managing controllers, views, and routing. It consists of Action Controller and Action View.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain Active Record

A

Active Record is the Object-Relational Mapping (ORM) layer for Rails. It provides the interface and functionality to connect Ruby objects with database tables. This allows Rails developers to interact with the database using object-oriented methods without writing raw SQL queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the key features of Active Record?

A
  • Model Representation: Each table in the database corresponds to a Ruby class in the application. Rows in the table are represented as objects of the class. The columns correspond to the attributes of the objects.
  • CRUD Operations: Active Record gives methods to create, read, update, and delete records in the database without manually writing SQL.
  • Associations: Active Record makes it easier to create relations between models (e.g., has_many, belongs_to).
  • Validations: Before saving to the database, Active Record can validate the data to ensure it meets certain criteria.
  • Query Interface: Active Record provides a rich API for querying the database and chaining conditions, which translates to SQL queries behind the scenes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the key features of Action Pack?

A
  • Action Controller: Manages the controller aspect of the MVC framework. It processes incoming HTTP requests, handles user input, session management, and routes the request to appropriate actions and views.
  • Action View: Manages views of the MVC framework. It’s responsible for rendering the HTML or other output formats in response to the user’s request. Embedded Ruby (ERB) is often used within Action View templates to embed Ruby code within HTML.
  • Routing: Works in tandem with Action Controller to decode the incoming HTTP requests’ URLs and dispatch them to the correct controller’s action method.
  • Helpers: Provides utility methods that can be used in views to render HTML content.
  • Asset Pipeline: Supports the inclusion and management of application assets like JavaScript, CSS, and images.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are Models?

A
  • Purpose: Represents the data structure, business logic, and the rules of the application. A model corresponds to a table in the database.
    Key Responsibilities:
  • Data Interaction: Handles interactions with the database. You can create, read, update, and delete records in the database using models without writing raw SQL.
  • Validations: Ensures that the data being saved to the database meets predefined criteria.
  • Associations: Defines the relationships between models (e.g., has_many, belongs_to, has_one, has_and_belongs_to_many).
  • Business Logic: Encapsulates the core functions that the application can perform on the data, like calculations or transformations.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are Views?

A
  • Purpose: Presents data to the user in a readable format. It’s the user interface of the application.
    Key Responsibilities:
  • Data Presentation: Displays the data to the user. For instance, when you see a list of blog posts on a website, that’s typically the work of a view.
  • Template Rendering: Uses Embedded Ruby (ERB) to embed Ruby code within HTML templates, allowing dynamic content generation based on the data provided by controllers.
  • Helpers: Utilizes view helpers to streamline the rendering process. Helpers are methods that can be used in views to perform common tasks, like generating links or forms.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are Controllers?

A
  • Purpose: Acts as an intermediary between models and views. It processes incoming requests, interacts with models to get or manipulate data, and then sends that data to the view to be displayed.
    Key Responsibilities:
  • Request Handling: Processes incoming HTTP requests (like GET, POST) and routes them to the appropriate action method.
  • Data Processing: After fetching or manipulating data via models, the controller prepares it for the view.
  • Response Management: Determines which view to display and sends the final rendered view back to the client’s browser.
  • Session Management: Maintains data that should persist across requests, like the info of a logged-in user.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Describe a typical Rails application flow.

A
  1. The user sends a request from their browser, which hits the Rails router.
  2. The router directs the request to the appropriate controller’s action.
  3. The controller might interact with one or multiple models to fetch or manipulate data.
  4. The controller sends the necessary data to a view.
  5. The view renders the data and sends the resulting HTML back through the controller and to the user’s browser.
    This separation in MVC ensures a clear distinction between different responsibilities, leading to organized and maintainable code.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How would you set up a one-to-many relationship between two models using Active Record?

A

Database Setup: Ensure that the child model’s table (the “many” side) has a foreign key column referring to the parent model. For instance, if we’re associating User and Post, the posts table should have a user_id column.
Model Association: In the parent model (e.g., User), you’d use the has_many method to denote the relationship:
class User < ApplicationRecord
has_many :posts
end
In the child model (e.g., Post), you’d use the belongs_to method:
class Post < ApplicationRecord
belongs_to :user
end
Using the Relationship: Once set up, you can fetch associated records easily. For instance, for a given user, user.posts would fetch all their posts, and for a given post, post.user would fetch its associated user.
Caveats and Good Practices: It’s worth noting the option to add the dependent: :destroy on the has_many side. This means if the parent record is destroyed, all associated child records are also destroyed. Also, for data integrity, it’s often a good idea to add validations to ensure every child record has an associated parent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is RESTful routing, and how is it implemented in Rails?

A

In the context of Rails, RESTful routing ensures that controllers and their actions are organized around CRUD operations (Create, Read, Update, Delete) for a particular resource.

Routes are organized around resources, typically corresponding to models in your application. For instance, if you have a Book model, your routes will be set up to handle operations on books.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the Standardized Routes and HTTP Verbs?

A

Rails’ RESTful routes use a combination of standard HTTP verbs and URLs to represent CRUD actions:
- Create: POST /books
- Read: GET /books/:id
- Update: PATCH/PUT /books/:id
- Delete: DELETE /books/:id
* And so on for other actions, including listing all books (GET /books) and presenting a form to create a new book (GET /books/new).

With the resources method in the routes.rb file, Rails provides a way to generate standard RESTful routes for a given resource with a single line of code:
resources :books
* This generates all the standard CRUD routes for books.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What tools or gems do you use for testing in Rails?

A

RSpec: testing framework for Rails applications. It’s expressive and integrates seamlessly with Rails, allowing for highly readable tests.
FactoryBot: For creating test data, I use the FactoryBot gem. It lets me set up test objects with default attributes and provides a clean and DRY approach to initializing test data.
Capybara: For feature or integration tests, Capybara is my go-to. It simulates how a user interacts with the app and tests the entire stack, including JavaScript behavior when used with drivers like Selenium or WebKit.
DatabaseCleaner: It ensures a clean slate for tests by cleaning up the test database between each run, ensuring data residue doesn’t interfere with other tests.
Shoulda Matchers: It provides RSpec-compatible one-liners that test common Rails functionalities, like validations and associations, making tests concise and easy to read.
SimpleCov: To ensure I have good test coverage across my application, I use SimpleCov. It provides a visual report of lines of code that haven’t been executed during test runs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can you describe your testing approach or strategy for a Rails application?

A

Model Tests: I begin by writing unit tests for models, ensuring that validations, associations, and any custom logic are correctly functioning. This provides a solid foundation and ensures data integrity.
Controller Tests: Here, I focus on testing various outcomes based on received parameters and user roles, ensuring not just that actions work, but that they also provide the right HTTP responses, render the expected views, or redirect as anticipated.
Feature/Integration Tests: These are crucial for testing user flows end-to-end. From logging in, performing actions, to logging out, I simulate real user behaviors to make sure the entire user experience works seamlessly.
TDD/BDD: Whenever possible, I adopt a Test-Driven Development (TDD) or Behavior-Driven Development (BDD) approach, writing tests first, then the application code. This not only ensures everything is testable from the start but also helps in designing the architecture.
Continuous Integration (CI): Implementing CI tools like Jenkins or GitHub Actions to run tests automatically for every pull request ensures that new code integrations don’t introduce regressions.
Regular Code Reviews: Beyond automated testing, I believe in the value of regular code reviews. They provide a chance for team members to spot potential issues and discuss better approaches.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What strategies would you use to identify and resolve performance bottlenecks in a Rails application?

A

Profiling: Before diving into solutions, it’s crucial to identify where the bottlenecks are. Profiling your application helps you understand which parts of the codebase are consuming the most resources.

Log Analysis: Rails logs provide a wealth of information. Regularly examining them can give insights into slow database queries, excessive rendering times, and other inefficiencies.

Benchmarking: Measure the performance of specific code sections or actions both before and after making optimizations to quantify improvements.

Database Optimization: Slow database queries are often culprits. By examining the SQL being executed, you can optimize queries, add necessary indexes, and denormalize tables if required.

Caching: Introduce caching mechanisms at various levels - page caching, action caching, fragment caching, or low-level caching using something like Redis or Memcached.

Frontend Performance: Sometimes, bottlenecks are on the client side. This might involve optimizing asset delivery, reducing the number of requests, or improving JavaScript performance.

Regular Code Reviews: Encourage the team to review each other’s code. Another pair of eyes can often spot inefficient algorithms or suboptimal queries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is CSRF? How does Rails protect against it?

A

CSRF stands for Cross-Site Request Forgery. This is a form of an attack where the attacker submits a form on your behalf to a different website, potentially causing damage or revealing sensitive information

In order to protect against CSRF attacks, you can add protect_from_forgery to your ApplicationController. This will then cause Rails to require a CSRF token to be present before accepting any POST, PUT, or DELETE requests.

Attackers are prevented from stealing the CSRF token by browsers’ “same origin” policy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between Ruby’s Hash and ActiveSupport’s HashWithIndifferentAccess?

A

The Hash class in Ruby’s core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :my_value) cannot be retrieved using the equivalent String (e.g. ‘my_value’).

On the other hand, HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:
h = HashWithIndifferentAccess.new
h[:my_value] = ‘foo’
h[‘my_value’] #=> will return “foo”

17
Q

What’s the issue with the controller code below? How would you fix it?

class CommentsController < ApplicationController
def users_comments
posts = Post.all
comments = posts.map(&:comments).flatten
@user_comments = comments.select do |comment|
comment.author.username == params[:username]
end
end
end

A

This is a classic example of the notorious “n+1” bug. This can all be avoided by changing the first line in the method to:
posts = Post.includes(comments: [:author]).all
This tells ActiveRecord to retrieve the corresponding Comment and Author records from the database immediately after the initial request for all Posts, thereby reducing the number of database requests to just three.

18
Q

What paths (HTTP verb and URL) will be defined by the following snippet in config/routes.rb?

resources :posts do
member do
get ‘comments’
end
collection do
post ‘bulk_upload’
end
end

A

Using the resource method to define routes will automatically generate routes for the standard seven restful actions:
1. GET /posts
2. POST /posts
3. GET /posts/new
4. GET /posts/:id/edit
5. GET /posts/:id
6. PATCH/PUT /posts/:id
7. DELETE /posts/:id

The extra routes defined inside of the block passed to resources will generate one route valid for individual posts (GET /posts/:id/comments) as well as one defined for the top-level resource (POST /posts/bulk_upload).

19
Q

Suppose we have a Student with id=”4”. If we delete the Student with id=”4”, what will be the result of the following queries:
Student.find(4)
Student.find_by_id(4)

A

Student.find(4) will raise an error: ActiveRecord::RecordNotFound: Couldn’t find Student with id=4
Student.find_by_id(4) will return nil and will not raise an error.

20
Q

Given this input:
x = [{“a” => 10},{“b” => 20},{“c” => 30}]

How can you obtain the following?
1. one array containing all keys
2. another containing all values
3. the sum of all the values

A

y = x[0].merge(x[1]).merge(x[2])
But a better first line would be this:
y = x.reduce(:merge)
…because it would work on an array of any size, not just the exact input given.

y.keys # will return all keys
y.values # will return all values
y.values.inject(:+) # will return the sum of all values

21
Q

What is Ruby on Rails?

A

Ruby on Rails is an open-source, web-application framework. Built within the Ruby programming language, it helps people create various applications. Ruby is a high-level, interpreted programming language that supports a variety of programming paradigms. Rails is a framework that can be used to build web applications.

22
Q

What does garbage collection do?

A

Garbage collection is a technique for controlling the amount of memory used by computer programs. Garbage collection and other memory management techniques, like reference counting, work by having the language keep track of which objects are in use by a program rather than the developer. This allows the programmer to concentrate on the business logic or other challenge at hand rather than the intricacies of memory allocation and release. This also aids program stability and security, as improper memory management can cause crashes, and memory management bugs account for a major fraction of security bugs.

23
Q

Name the 4 types of variables available in Ruby Classes.

A

Instance variable – A variable that only exists within the context of the current object
Begins with @
Global variables – Begins with $
Local Variable – a variable that only exists within the context of the current method.
Class variables – Begins with @@

24
Q

Explain the naming convention in Rails

A

Variables – all lowercase letters – words are separated by underscores
Class and Modules – Mixed case, no underscore, each word starts with an uppercase
Database Tables – the db table name should have lowercase letters and underscore between words. All table names should be in the plural form.
Model – mixed case, always has singular with the table name
Controller – Represented in plural form like OrdersController

25
Q

What is the ORM (Object-Relationship-Model)?

A

In Rails, the ORM indicates that your classes are mapped to the database table, and objects are directly mapped to the table rows. The attributes and relationships of objects in an app may be easily stored and retrieved from a database using ORM, which requires less overall database access code and does not require writing SQL queries directly.

26
Q

What is the difference between String and Symbol?

A

Strings are any text typed between quote marks and symbols are text that starts with a colon (:symbol). Symbols are immutable strings.

27
Q

What do app/controllers and app/helpers do?

A

App/controller – where controller classes are found which Rails searches for when it receives a request from a route.
App/helper – any helper classes needed to assist the model, view, and controller classes are stored here. This keeps the mvc code clean, simple, and focused.

28
Q

What is a Rails Controller?

A

Your application’s logical heart is the Rails Controller. It orchestrates the user’s interaction with the views and the model.
* It is in charge of directing external request to internal processes
* It controls caching, which can improve application performance by orders of magnitude
* It handles helper modules, which add functionality to view templates without adding code to them.
* It keeps track of sessions, creating the impression that users are still intracting with our apps.

29
Q

Explain how Rails implements AJAX?

A

Different user actions force the browser to display a new web page or initiate an AJAX activity after the original web page has been produced and displayed.
1. Some trigger is fired – This could be a user clicking a button or link, a user changing data on a form or in a field, or just a recurring trigger (based on a timer).
2. The server is contacted by the web client – The XMLHttpRequest JavaScript function transmits data associated with the trigger to a server action handler. The data could be the checkbox ID, text in an entry field, or the entire form.
3. The server performs the processing – the server-side action handler (Rails controller action) manipulates the data and sends an HTML fragment to the web client.
4. The HTML fragment is received by the client-side JavaScript – The client-side JS which Rails generates automatically is used to alter a specific are of the current page’s HTML , usually the content of a <div> element.

30
Q

What are access modifiers in Ruby?

A

Public: In this, all members are available to everyone to modify.
Private: In this, only functions inside the class can access members.
Protected: In this, the members can only be accessed by functions inside the subclass.