Ruby on Rails Ruby on Rails Testing, Security & API Development 2 — Questions and Answers
Question 1: What is the Rails Asset Pipeline used for?
- Managing database migrations
- Concatenating, minifying, and serving CSS/JS assets efficiently (Correct answer)
- Routing API requests
- Handling background job processing
Correct answer: Concatenating, minifying, and serving CSS/JS assets efficiently
The Asset Pipeline (Sprockets) concatenates and compresses JavaScript and CSS files, and handles asset fingerprinting for cache busting.
Question 2: How do you protect a Rails API endpoint so only authenticated users can access it?
- By using `secure_action` in routes.rb
- By calling `before_action :authenticate_user!` or a custom auth callback (Correct answer)
- By setting `private: true` on the action
- By adding SSL to the route
Correct answer: By calling `before_action :authenticate_user!` or a custom auth callback
`before_action :authenticate_user!` (Devise) or a custom `before_action` method runs before the action to check authentication.
Question 3: What does `rails generate scaffold Post title:string body:text` create?
- Only the model and migration
- Model, migration, controller, views, and routes for full CRUD (Correct answer)
- Only the routes and controller
- A database backup of the posts table
Correct answer: Model, migration, controller, views, and routes for full CRUD
The scaffold generator creates the full CRUD stack: model, migration, controller with all RESTful actions, views, and routes in one command.
Question 4: What gem is most commonly used for authentication in Rails applications?
- Cancancan
- Pundit
- Devise (Correct answer)
- OmniAuth
Correct answer: Devise
Devise is the most widely used Rails authentication gem, providing sign-up, sign-in, password reset, and session management out of the box.
Question 5: In Rails, what is the purpose of environment variables stored in `.env` files?
- Defining database schema
- Storing sensitive configuration like API keys outside of version control (Correct answer)
- Setting up test fixtures
- Configuring route namespaces
Correct answer: Storing sensitive configuration like API keys outside of version control
.env files (used with the dotenv gem) store sensitive credentials and environment-specific config that should not be committed to source control.
Question 6: What is the `rails credentials` system used for in modern Rails?
- Managing user login credentials in the database
- Securely storing encrypted application secrets like API keys (Correct answer)
- Defining database user permissions
- Storing SSL certificates
Correct answer: Securely storing encrypted application secrets like API keys
Rails credentials (config/credentials.yml.enc) stores encrypted secrets decrypted at runtime using a master key, replacing the old secrets.yml approach.
What is the Rails Asset Pipeline used for?