โโโ README.md /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Ruby on Rails Technical Interview Questions: 3 | - [Ruby on Rails Technical Interview Questions:](#ruby-on-rails-technical-interview-questions) 4 | - [Basic](#basic) 5 | - [1. What is MVC?](#1-what-is-mvc) 6 | - [Example:](#example) 7 | - [2. What is ActiveRecord?](#2-what-is-activerecord) 8 | - [3. What are callbacks in Rails?](#3-what-are-callbacks-in-rails) 9 | - [4. What is mass assignment?](#4-what-is-mass-assignment) 10 | - [5. What is CSRF?](#5-what-is-csrf) 11 | - [6. How do you handle database migrations in Rails?](#6-how-do-you-handle-database-migrations-in-rails) 12 | - [7. What is a scope?](#7-what-is-a-scope) 13 | - [8. What is the difference between has\_one and belongs\_to?](#8-what-is-the-difference-between-has_one-and-belongs_to) 14 | - [9. What is Rails Console, and how do you use it?](#9-what-is-rails-console-and-how-do-you-use-it) 15 | - [10. What are before\_action, after\_action, and skip\_before\_action?](#10-what-are-before_action-after_action-and-skip_before_action) 16 | - [11. What are Strong Parameters? Why are they needed?](#11-what-are-strong-parameters-why-are-they-needed) 17 | - [12. How do you define routes in Rails?](#12-how-do-you-define-routes-in-rails) 18 | - [13. How do you generate a model, controller, and migration in Rails?](#13-how-do-you-generate-a-model-controller-and-migration-in-rails) 19 | - [14. What is the config/routes.rb file used for?](#14-what-is-the-configroutesrb-file-used-for) 20 | - [15. What is flash in Rails? How is it different from session?](#15-what-is-flash-in-rails-how-is-it-different-from-session) 21 | - [16. How does Rails handle sessions and cookies?](#16-how-does-rails-handle-sessions-and-cookies) 22 | - [17. What is link\_to in Rails views?](#17-what-is-link_to-in-rails-views) 23 | - [18. What is form\_with, and how does it work?](#18-what-is-form_with-and-how-does-it-work) 24 | - [19. What is partial in Rails views?](#19-what-is-partial-in-rails-views) 25 | - [20. What is link\_to in Rails views?](#20-what-is-link_to-in-rails-views) 26 | - [21. What is form\_with, and how does it work?](#21-what-is-form_with-and-how-does-it-work) 27 | - [22. What is a partial in Rails views?](#22-what-is-a-partial-in-rails-views) 28 | - [23. What is layout in Rails, and how do you use it?](#23-what-is-layout-in-rails-and-how-do-you-use-it) 29 | - [24. What is yield, and how does it work in Rails layouts?](#24-what-is-yield-and-how-does-it-work-in-rails-layouts) 30 | - [25. What are helpers in Rails?](#25-what-are-helpers-in-rails) 31 | - [26. What is params in Rails, and how does it work?](#26-what-is-params-in-rails-and-how-does-it-work) 32 | - [27. What is the difference between GET, POST, PUT, and DELETE requests in Rails?](#27-what-is-the-difference-between-get-post-put-and-delete-requests-in-rails) 33 | - [28. What is rails routes, and how do you use it?](#28-what-is-rails-routes-and-how-do-you-use-it) 34 | - [29. What is has\_many :through, and when do you use it?](#29-what-is-has_many-through-and-when-do-you-use-it) 35 | - [30. What is validates in Rails models?](#30-what-is-validates-in-rails-models) 36 | - [31. What is rescue\_from, and how does it work?](#31-what-is-rescue_from-and-how-does-it-work) 37 | - [32. What is rake, and how does it work in Rails?](#32-what-is-rake-and-how-does-it-work-in-rails) 38 | - [๐ 1. Handling N+1 Queries (Optimization)](#-1-handling-n1-queries-optimization) 39 | - [๐ 2. Implementing Caching in Rails](#-2-implementing-caching-in-rails) 40 | - [5. When to Use Proc vs. Lambda](#5-when-to-use-proc-vs-lambda) 41 | - [6. Real-World Use Cases](#6-real-world-use-cases) 42 | - [Summary](#summary) 43 | - [Explain Sharding ?](#explain-sharding-) 44 | - [Why Use Sharding?](#why-use-sharding) 45 | - [โ Benefits of Sharding](#-benefits-of-sharding) 46 | - [How Does Sharding Work in Rails?](#how-does-sharding-work-in-rails) 47 | - [๐น Implementing Sharding in Rails](#-implementing-sharding-in-rails) 48 | - [When to Use Sharding?](#when-to-use-sharding) 49 | - [๐ Core Rails Questions](#-core-rails-questions) 50 | - [How does Rails handle database connection pooling?](#how-does-rails-handle-database-connection-pooling) 51 | - [Explain the difference between joins, includes, preload, and eager\_load.](#explain-the-difference-between-joins-includes-preload-and-eager_load) 52 | - [How does Railsโ autoloading work? What changed in Zeitwerk?](#how-does-rails-autoloading-work-what-changed-in-zeitwerk) 53 | - [What are ActiveRecord callbacks? When should you avoid them?](#what-are-activerecord-callbacks-when-should-you-avoid-them) 54 | - [What are ActiveSupport Concerns? How do they differ from modules?](#what-are-activesupport-concerns-how-do-they-differ-from-modules) 55 | - [What is the purpose of Rails engines? When would you use one?](#what-is-the-purpose-of-rails-engines-when-would-you-use-one) 56 | - [How does Rails handle has\_many :through vs. has\_and\_belongs\_to\_many?](#how-does-rails-handle-has_many-through-vs-has_and_belongs_to_many) 57 | - [Whatโs the difference between belongs\_to and has\_one?](#whats-the-difference-between-belongs_to-and-has_one) 58 | - [What are Rails observers, and why are they deprecated?](#what-are-rails-observers-and-why-are-they-deprecated) 59 | - [How does the Rails asset pipeline work?](#how-does-the-rails-asset-pipeline-work) 60 | - [What are different ways to manage configurations in Rails (secrets.yml, credentials.yml.enc, ENV variables)?](#what-are-different-ways-to-manage-configurations-in-rails-secretsyml-credentialsymlenc-env-variables) 61 | - [What is the difference between dependent: :destroy, dependent: :delete\_all, and dependent: :nullify?](#what-is-the-difference-between-dependent-destroy-dependent-delete_all-and-dependent-nullify) 62 | - [How do you implement state machines in Rails (e.g., AASM, workflow gem)?](#how-do-you-implement-state-machines-in-rails-eg-aasm-workflow-gem) 63 | - [Whatโs the difference between rake and rails commands?](#whats-the-difference-between-rake-and-rails-commands) 64 | - [What are concerns, and when should they be used?](#what-are-concerns-and-when-should-they-be-used) 65 | - [โก Performance \& Scalability](#-performance--scalability) 66 | - [What techniques do you use to prevent N+1 queries?](#what-techniques-do-you-use-to-prevent-n1-queries) 67 | - [What is database sharding? How does Rails support it?](#what-is-database-sharding-how-does-rails-support-it) 68 | - [How do you analyze slow database queries in Rails?](#how-do-you-analyze-slow-database-queries-in-rails) 69 | - [What is caching in Rails? How does fragment caching work?](#what-is-caching-in-rails-how-does-fragment-caching-work) 70 | - [How do you handle background jobs at scale in Rails?](#how-do-you-handle-background-jobs-at-scale-in-rails) 71 | - [What are the advantages and disadvantages of Sidekiq vs. Delayed Job vs. Resque?](#what-are-the-advantages-and-disadvantages-of-sidekiq-vs-delayed-job-vs-resque) 72 | - [What is a Rails middleware? How do you add a custom middleware?](#what-is-a-rails-middleware-how-do-you-add-a-custom-middleware) 73 | - [How do you scale a Rails application to handle high traffic?](#how-do-you-scale-a-rails-application-to-handle-high-traffic) 74 | - [What are different types of caching available in Rails?](#what-are-different-types-of-caching-available-in-rails) 75 | - [What is Puma? How does it improve Rails performance?](#what-is-puma-how-does-it-improve-rails-performance) 76 | - [How does Rails handle HTTP/2 and WebSockets?](#how-does-rails-handle-http2-and-websockets) 77 | - [What are the best practices for optimizing ActiveRecord queries?](#what-are-the-best-practices-for-optimizing-activerecord-queries) 78 | - [Whatโs the difference between connection\_pool and database.yml settings?](#whats-the-difference-between-connection_pool-and-databaseyml-settings) 79 | - [How do you handle large file uploads in Rails?](#how-do-you-handle-large-file-uploads-in-rails) 80 | - [Whatโs the difference between synchronous and asynchronous processing in Rails?](#whats-the-difference-between-synchronous-and-asynchronous-processing-in-rails) 81 | - [๐ก๏ธ Security \& Best Practices](#๏ธ-security--best-practices) 82 | - [What is CSRF, and how does Rails prevent it?](#what-is-csrf-and-how-does-rails-prevent-it) 83 | - [What is SQL injection? How does Rails prevent it?](#what-is-sql-injection-how-does-rails-prevent-it) 84 | - [How does Rails handle Cross-Site Scripting (XSS) vulnerabilities?](#how-does-rails-handle-cross-site-scripting-xss-vulnerabilities) 85 | - [What is mass assignment, and how can it be prevented?](#what-is-mass-assignment-and-how-can-it-be-prevented) 86 | - [What is the difference between strong\_parameters and attr\_accessible?](#what-is-the-difference-between-strong_parameters-and-attr_accessible) 87 | - [What is session fixation, and how does Rails mitigate it?](#what-is-session-fixation-and-how-does-rails-mitigate-it) 88 | - [What is secure\_compare and why is it important?](#what-is-secure_compare-and-why-is-it-important) 89 | - [How do you prevent brute-force attacks in Rails authentication?](#how-do-you-prevent-brute-force-attacks-in-rails-authentication) 90 | - [How does Devise handle authentication and security?](#how-does-devise-handle-authentication-and-security) 91 | - [What are Rails' default security mechanisms (e.g., Secure Headers, HTTP-only cookies)?](#what-are-rails-default-security-mechanisms-eg-secure-headers-http-only-cookies) 92 | - [How do you enforce password policies in Rails apps?](#how-do-you-enforce-password-policies-in-rails-apps) 93 | - [What is parameter tampering, and how does Rails prevent it?](#what-is-parameter-tampering-and-how-does-rails-prevent-it) 94 | - [How do you secure Rails APIs (rate limiting, JWT, OAuth)?](#how-do-you-secure-rails-apis-rate-limiting-jwt-oauth) 95 | - [What is the difference between session\_store and cookie\_store?](#what-is-the-difference-between-session_store-and-cookie_store) 96 | - [What is CORS, and how does Rails handle it?](#what-is-cors-and-how-does-rails-handle-it) 97 | - [What is permanent\_signed vs. signed cookies in Rails?](#what-is-permanent_signed-vs-signed-cookies-in-rails) 98 | - [How do you handle authorization (Pundit vs. CanCanCan)?](#how-do-you-handle-authorization-pundit-vs-cancancan) 99 | - [How do you prevent replay attacks in Rails?](#how-do-you-prevent-replay-attacks-in-rails) 100 | - [What is rails-ujs, and how does it help with security?](#what-is-rails-ujs-and-how-does-it-help-with-security) 101 | - [How do you enforce HTTPS in a Rails application?](#how-do-you-enforce-https-in-a-rails-application) 102 | - [๐ System Design \& Architecture](#-system-design--architecture) 103 | - [What is REST, and how does Rails enforce RESTful design?](#what-is-rest-and-how-does-rails-enforce-restful-design) 104 | - [How do you implement API versioning in Rails?](#how-do-you-implement-api-versioning-in-rails) 105 | - [What are the key differences between REST and GraphQL?](#what-are-the-key-differences-between-rest-and-graphql) 106 | - [How would you design a multi-tenant Rails application?](#how-would-you-design-a-multi-tenant-rails-application) 107 | - [How does Rails handle WebSockets and real-time features?](#how-does-rails-handle-websockets-and-real-time-features) 108 | - [How do you design a microservices-based architecture with Rails?](#how-do-you-design-a-microservices-based-architecture-with-rails) 109 | - [What are the trade-offs of monolithic vs. microservices architecture in Rails?](#what-are-the-trade-offs-of-monolithic-vs-microservices-architecture-in-rails) 110 | - [What are design considerations for building a large-scale Rails API?](#what-are-design-considerations-for-building-a-large-scale-rails-api) 111 | - [How do you handle background jobs in a multi-server environment?](#how-do-you-handle-background-jobs-in-a-multi-server-environment) 112 | - [How do you handle file storage in Rails (ActiveStorage, Shrine, Paperclip)?](#how-do-you-handle-file-storage-in-rails-activestorage-shrine-paperclip) 113 | - [What is CQRS, and how can it be applied in Rails applications?](#what-is-cqrs-and-how-can-it-be-applied-in-rails-applications) 114 | - [How do you handle rate-limiting in Rails APIs?](#how-do-you-handle-rate-limiting-in-rails-apis) 115 | - [What are the challenges of running Rails in a containerized environment (Docker, Kubernetes)?](#what-are-the-challenges-of-running-rails-in-a-containerized-environment-docker-kubernetes) 116 | - [How would you handle real-time notifications in Rails?](#how-would-you-handle-real-time-notifications-in-rails) 117 | - [How do you implement event-driven architecture in Rails?](#how-do-you-implement-event-driven-architecture-in-rails) 118 | - [What are the key performance bottlenecks in a Rails application?](#what-are-the-key-performance-bottlenecks-in-a-rails-application) 119 | - [What are the key differences between Rails and other frameworks like Django or Laravel?](#what-are-the-key-differences-between-rails-and-other-frameworks-like-django-or-laravel) 120 | - [How do you handle service-to-service authentication in a Rails microservices setup?](#how-do-you-handle-service-to-service-authentication-in-a-rails-microservices-setup) 121 | - [How do you optimize database indexes for large-scale Rails applications?](#how-do-you-optimize-database-indexes-for-large-scale-rails-applications) 122 | - [How would you design a rate-limiting system in Rails?๐ System Design \& Architecture](#how-would-you-design-a-rate-limiting-system-in-rails-system-design--architecture) 123 | - [What is REST, and how does Rails enforce RESTful design?](#what-is-rest-and-how-does-rails-enforce-restful-design-1) 124 | - [How do you implement API versioning in Rails?](#how-do-you-implement-api-versioning-in-rails-1) 125 | - [What are the key differences between REST and GraphQL?](#what-are-the-key-differences-between-rest-and-graphql-1) 126 | - [How would you design a multi-tenant Rails application?](#how-would-you-design-a-multi-tenant-rails-application-1) 127 | - [How does Rails handle WebSockets and real-time features?](#how-does-rails-handle-websockets-and-real-time-features-1) 128 | - [How do you design a microservices-based architecture with Rails?](#how-do-you-design-a-microservices-based-architecture-with-rails-1) 129 | - [What are the trade-offs of monolithic vs. microservices architecture in Rails?](#what-are-the-trade-offs-of-monolithic-vs-microservices-architecture-in-rails-1) 130 | - [What are design considerations for building a large-scale Rails API?](#what-are-design-considerations-for-building-a-large-scale-rails-api-1) 131 | - [How do you handle background jobs in a multi-server environment?](#how-do-you-handle-background-jobs-in-a-multi-server-environment-1) 132 | - [How do you handle file storage in Rails (ActiveStorage, Shrine, Paperclip)?](#how-do-you-handle-file-storage-in-rails-activestorage-shrine-paperclip-1) 133 | - [What is CQRS, and how can it be applied in Rails applications?](#what-is-cqrs-and-how-can-it-be-applied-in-rails-applications-1) 134 | - [How do you handle rate-limiting in Rails APIs?](#how-do-you-handle-rate-limiting-in-rails-apis-1) 135 | - [What are the challenges of running Rails in a containerized environment (Docker, Kubernetes)?](#what-are-the-challenges-of-running-rails-in-a-containerized-environment-docker-kubernetes-1) 136 | - [How would you handle real-time notifications in Rails?](#how-would-you-handle-real-time-notifications-in-rails-1) 137 | - [How do you implement event-driven architecture in Rails?](#how-do-you-implement-event-driven-architecture-in-rails-1) 138 | - [What are the key performance bottlenecks in a Rails application?](#what-are-the-key-performance-bottlenecks-in-a-rails-application-1) 139 | - [What are the key differences between Rails and other frameworks like Django or Laravel?](#what-are-the-key-differences-between-rails-and-other-frameworks-like-django-or-laravel-1) 140 | - [How do you handle service-to-service authentication in a Rails microservices setup?](#how-do-you-handle-service-to-service-authentication-in-a-rails-microservices-setup-1) 141 | - [How do you optimize database indexes for large-scale Rails applications?](#how-do-you-optimize-database-indexes-for-large-scale-rails-applications-1) 142 | - [How would you design a rate-limiting system in Rails?](#how-would-you-design-a-rate-limiting-system-in-rails) 143 | - [๐ Advanced Ruby Questions](#-advanced-ruby-questions) 144 | - [What is the difference between Proc and Lambda?](#what-is-the-difference-between-proc-and-lambda) 145 | - [What is the difference between include, extend, and prepend?](#what-is-the-difference-between-include-extend-and-prepend) 146 | - [How does Ruby garbage collection (GC) work?](#how-does-ruby-garbage-collection-gc-work) 147 | - [What is the difference between Thread and Fiber?](#what-is-the-difference-between-thread-and-fiber) 148 | - [What are Ruby metaprogramming techniques?](#what-are-ruby-metaprogramming-techniques) 149 | - [What are method\_missing and respond\_to\_missing?](#what-are-method_missing-and-respond_to_missing) 150 | - [What are singleton classes and eigenclasses in Ruby?](#what-are-singleton-classes-and-eigenclasses-in-ruby) 151 | - [What is duck typing in Ruby?](#what-is-duck-typing-in-ruby) 152 | - [How does Ruby handle method lookup and method resolution order (MRO)?](#how-does-ruby-handle-method-lookup-and-method-resolution-order-mro) 153 | - [How does module\_function work in Ruby?](#how-does-module_function-work-in-ruby) 154 | - [What is the difference between public, private, and protected methods?](#what-is-the-difference-between-public-private-and-protected-methods) 155 | - [What is the difference between class\_variable, instance\_variable, and global\_variable?](#what-is-the-difference-between-class_variable-instance_variable-and-global_variable) 156 | - [What is monkey patching, and when should you avoid it?](#what-is-monkey-patching-and-when-should-you-avoid-it) 157 | - [What are refinements in Ruby?](#what-are-refinements-in-ruby) 158 | - [How do you implement multiple inheritance in Ruby?](#how-do-you-implement-multiple-inheritance-in-ruby) 159 | - [What is the difference between super and self?](#what-is-the-difference-between-super-and-self) 160 | - [How does define\_method work in Ruby?](#how-does-define_method-work-in-ruby) 161 | - [What is method\_missing, and how can it be useful?](#what-is-method_missing-and-how-can-it-be-useful) 162 | - [What is a Ruby block, and how is it different from a Proc?](#what-is-a-ruby-block-and-how-is-it-different-from-a-proc) 163 | - [What is the difference between tap, yield\_self, and then in Ruby?](#what-is-the-difference-between-tap-yield_self-and-then-in-ruby) 164 | - [Core Ruby Questions](#core-ruby-questions) 165 | - [How is memory management handled in Ruby?](#how-is-memory-management-handled-in-ruby) 166 | - [Whatโs the difference between dup and clone in Ruby?](#whats-the-difference-between-dup-and-clone-in-ruby) 167 | - [Explain the concept of object immutability in Ruby.](#explain-the-concept-of-object-immutability-in-ruby) 168 | - [What is the difference between super and super()?](#what-is-the-difference-between-super-and-super) 169 | - [How does Rubyโs case statement work internally? Does it use == or ===?](#how-does-rubys-case-statement-work-internally-does-it-use--or-) 170 | - [๐งฉ OOP and Design Questions](#-oop-and-design-questions) 171 | - [What are the SOLID principles? Can you demonstrate one using Ruby?](#what-are-the-solid-principles-can-you-demonstrate-one-using-ruby) 172 | - [Whatโs the difference between a class variable and a class instance variable?](#whats-the-difference-between-a-class-variable-and-a-class-instance-variable) 173 | - [When would you use method\_missing vs define\_method?](#when-would-you-use-method_missing-vs-define_method) 174 | - [How do modules affect the method lookup chain in Ruby?](#how-do-modules-affect-the-method-lookup-chain-in-ruby) 175 | - [What is a mixin and when would you use it over inheritance?](#what-is-a-mixin-and-when-would-you-use-it-over-inheritance) 176 | - [๐งช Testing and Tooling](#-testing-and-tooling) 177 | - [How would you test private methods in Ruby? Should you?](#how-would-you-test-private-methods-in-ruby-should-you) 178 | - [Explain how RSpec matchers work and how to write custom matchers.](#explain-how-rspec-matchers-work-and-how-to-write-custom-matchers) 179 | - [Whatโs the difference between mocking and stubbing in tests?](#whats-the-difference-between-mocking-and-stubbing-in-tests) 180 | - [How do you test a class that uses metaprogramming or dynamic behavior?](#how-do-you-test-a-class-that-uses-metaprogramming-or-dynamic-behavior) 181 | - [๐ Enumerable and Functional Patterns](#-enumerable-and-functional-patterns) 182 | - [Whatโs the difference between map, collect, each\_with\_object, and reduce?](#whats-the-difference-between-map-collect-each_with_object-and-reduce) 183 | - [How would you reverse a linked list using only Ruby's Enumerable methods?](#how-would-you-reverse-a-linked-list-using-only-rubys-enumerable-methods) 184 | - [Explain lazy evaluation in Ruby with an example.](#explain-lazy-evaluation-in-ruby-with-an-example) 185 | - [How would you implement your own version of zip or group\_by?](#how-would-you-implement-your-own-version-of-zip-or-group_by) 186 | - [๐งฌ Metaprogramming \& DSLs](#-metaprogramming--dsls) 187 | - [What are the risks of using eval in Ruby?](#what-are-the-risks-of-using-eval-in-ruby) 188 | - [Can you write a DSL for a pizza builder? (e.g., Pizza.new.size(:large).toppings(:olives, :cheese))](#can-you-write-a-dsl-for-a-pizza-builder-eg-pizzanewsizelargetoppingsolives-cheese) 189 | - [How does method\_missing affect performance and debuggability?](#how-does-method_missing-affect-performance-and-debuggability) 190 | - [When would you use class\_eval vs define\_singleton\_method?](#when-would-you-use-class_eval-vs-define_singleton_method) 191 | - [Can you override send or respond\_to?? When might you do that?](#can-you-override-send-or-respond_to-when-might-you-do-that) 192 | - [๐น Concurrency and System Design](#-concurrency-and-system-design) 193 | - [How would you handle thread safety in Ruby for shared data structures?](#how-would-you-handle-thread-safety-in-ruby-for-shared-data-structures) 194 | - [What are Fibers and how are they different from Threads?](#what-are-fibers-and-how-are-they-different-from-threads) 195 | - [Have you used Ractor in Ruby 3.x? How does it enable true parallelism?](#have-you-used-ractor-in-ruby-3x-how-does-it-enable-true-parallelism) 196 | - [Design an in-memory rate limiter in Ruby (e.g., max 10 requests per minute per user).](#design-an-in-memory-rate-limiter-in-ruby-eg-max-10-requests-per-minute-per-user) 197 | - [๐ก Debugging and Performance](#-debugging-and-performance) 198 | - [How do you profile memory or CPU usage in a Ruby script?](#how-do-you-profile-memory-or-cpu-usage-in-a-ruby-script) 199 | - [Explain the concept of memoization. How would you implement it manually?](#explain-the-concept-of-memoization-how-would-you-implement-it-manually) 200 | - [How do you reduce object allocation in a large loop?](#how-do-you-reduce-object-allocation-in-a-large-loop) 201 | - [When and why would you freeze an object in Ruby?](#when-and-why-would-you-freeze-an-object-in-ruby) 202 | - [๐ Trick Questions / Gotchas](#-trick-questions--gotchas) 203 | - [What will this return and why?](#what-will-this-return-and-why) 204 | - [Whatโs the difference between ||= and or=?](#whats-the-difference-between--and-or) 205 | - [Why might using Hash.new(\[\]) cause unexpected behavior?](#why-might-using-hashnew-cause-unexpected-behavior) 206 | - [โ Basic Ruby Questions](#-basic-ruby-questions) 207 | - [What are symbols in Ruby? How are they different from strings?](#what-are-symbols-in-ruby-how-are-they-different-from-strings) 208 | - [What are the different types of variables in Ruby (local, instance, class, global)?](#what-are-the-different-types-of-variables-in-ruby-local-instance-class-global) 209 | - [What is the difference between ==, eql?, and equal??](#what-is-the-difference-between--eql-and-equal) 210 | - [Explain the difference between puts, print, and p.](#explain-the-difference-between-puts-print-and-p) 211 | - [What is a block, and how is it different from a Proc or a lambda?](#what-is-a-block-and-how-is-it-different-from-a-proc-or-a-lambda) 212 | - [What is the use of the self keyword in Ruby?](#what-is-the-use-of-the-self-keyword-in-ruby) 213 | - [What is the difference between include and extend in modules?](#what-is-the-difference-between-include-and-extend-in-modules) 214 | - [How does garbage collection work in Ruby?](#how-does-garbage-collection-work-in-ruby) 215 | - [Whatโs the difference between nil, false, and undefined variable in Ruby?](#whats-the-difference-between-nil-false-and-undefined-variable-in-ruby) 216 | - [๐ Intermediate Ruby Questions](#-intermediate-ruby-questions) 217 | - [Explain how Ruby handles method overloading or default arguments.](#explain-how-ruby-handles-method-overloading-or-default-arguments) 218 | - [What is duck typing in Ruby? Give an example.](#what-is-duck-typing-in-ruby-give-an-example) 219 | - [How does Ruby handle inheritance and method resolution?](#how-does-ruby-handle-inheritance-and-method-resolution) 220 | - [What are singleton methods? When would you use them?](#what-are-singleton-methods-when-would-you-use-them) 221 | - [Whatโs the difference between Proc.new, lambda, and the -\> syntax?](#whats-the-difference-between-procnew-lambda-and-the---syntax) 222 | - [What are refinements in Ruby? Why would you use them instead of monkey-patching?](#what-are-refinements-in-ruby-why-would-you-use-them-instead-of-monkey-patching) 223 | - [What are the scopes of constants in Ruby (e.g., ::, nesting)?](#what-are-the-scopes-of-constants-in-ruby-eg--nesting) 224 | - [Explain what mixins are. How are they implemented in Ruby?](#explain-what-mixins-are-how-are-they-implemented-in-ruby) 225 | - [How do you define and use custom enumerators in Ruby?](#how-do-you-define-and-use-custom-enumerators-in-ruby) 226 | - [๐ฌ Advanced Ruby Questions](#-advanced-ruby-questions-1) 227 | - [How would you implement your own version of each, map, or select without using Ruby's built-in methods?](#how-would-you-implement-your-own-version-of-each-map-or-select-without-using-rubys-built-in-methods) 228 | - [What are some metaprogramming techniques in Ruby? Show an example using define\_method or method\_missing.](#what-are-some-metaprogramming-techniques-in-ruby-show-an-example-using-define_method-or-method_missing) 229 | - [What is the difference between class variables (@@) and class instance variables (@ on the class)?](#what-is-the-difference-between-class-variables--and-class-instance-variables--on-the-class) 230 | - [How does Rubyโs method\_missing work, and what are the risks?](#how-does-rubys-method_missing-work-and-what-are-the-risks) 231 | - [Whatโs the difference between eager and lazy enumerators in Ruby?](#whats-the-difference-between-eager-and-lazy-enumerators-in-ruby) 232 | - [How do fibers work in Ruby? What are they useful for?](#how-do-fibers-work-in-ruby-what-are-they-useful-for) 233 | - [How would you optimize memory usage in a Ruby app that processes millions of records?](#how-would-you-optimize-memory-usage-in-a-ruby-app-that-processes-millions-of-records) 234 | - [What is the Global Interpreter Lock (GIL) in Ruby MRI? How does it affect threading?](#what-is-the-global-interpreter-lock-gil-in-ruby-mri-how-does-it-affect-threading) 235 | - [How would you implement a Domain-Specific Language (DSL) in Ruby?](#how-would-you-implement-a-domain-specific-language-dsl-in-ruby) 236 | - [๐ Live Coding Challenge Questions](#-live-coding-challenge-questions) 237 | - [Implement a caching mechanism in Rails without using built-in Rails caching.](#implement-a-caching-mechanism-in-rails-without-using-built-in-rails-caching) 238 | - [Optimize a slow SQL query in a Rails application.](#optimize-a-slow-sql-query-in-a-rails-application) 239 | - [Write a background job that sends scheduled emails using Sidekiq.](#write-a-background-job-that-sends-scheduled-emails-using-sidekiq) 240 | - [Write a Rails service object that processes and validates a CSV file upload.](#write-a-rails-service-object-that-processes-and-validates-a-csv-file-upload) 241 | - [Refactor a Rails controller that has too many instance variables.](#refactor-a-rails-controller-that-has-too-many-instance-variables) 242 | - [Write a Rails middleware that logs request details before passing it to the controller.](#write-a-rails-middleware-that-logs-request-details-before-passing-it-to-the-controller) 243 | - [Write a method that finds all duplicate users based on their email in ActiveRecord.](#write-a-method-that-finds-all-duplicate-users-based-on-their-email-in-activerecord) 244 | - [Design a system to throttle API requests in Rails without using third-party gems.](#design-a-system-to-throttle-api-requests-in-rails-without-using-third-party-gems) 245 | - [Implement an authentication system without Devise in Rails.](#implement-an-authentication-system-without-devise-in-rails) 246 | - [Write a custom ActiveRecord scope that returns all users who havenโt logged in for 30 days.](#write-a-custom-activerecord-scope-that-returns-all-users-who-havent-logged-in-for-30-days) 247 | - [๐๐ป๐๐ฒ๐ฟ๐บ๐ฒ๐ฑ๐ถ๐ฎ๐๐ฒ ๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐ -:](#๐๐ป๐๐ฒ๐ฟ๐บ๐ฒ๐ฑ๐ถ๐ฎ๐๐ฒ-๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐--) 248 | - [1. How do you handle exceptions and errors in Rails? What strategies do you use for logging and notification?](#1-how-do-you-handle-exceptions-and-errors-in-rails-what-strategies-do-you-use-for-logging-and-notification) 249 | - [2. How do you approach database modeling in Rails? What considerations do you take for efficient data retrieval and storage?](#2-how-do-you-approach-database-modeling-in-rails-what-considerations-do-you-take-for-efficient-data-retrieval-and-storage) 250 | - [3. How do you use Rails migrations to manage database schema changes? What are some best practices for writing migrations?](#3-how-do-you-use-rails-migrations-to-manage-database-schema-changes-what-are-some-best-practices-for-writing-migrations) 251 | - [4. What caching mechanisms does Rails offer (fragment, action, and page caching), and when would you use each?](#4-what-caching-mechanisms-does-rails-offer-fragment-action-and-page-caching-and-when-would-you-use-each) 252 | - [5. How do you design RESTful APIs in Rails? What considerations do you take for API versioning and security?](#5-how-do-you-design-restful-apis-in-rails-what-considerations-do-you-take-for-api-versioning-and-security) 253 | - [6. How do you use service objects to encapsulate business logic in Rails? What benefits do they offer?](#6-how-do-you-use-service-objects-to-encapsulate-business-logic-in-rails-what-benefits-do-they-offer) 254 | - [7. How do you define nested routes in Rails? What are some advanced routing techniques such as shallow routes?](#7-how-do-you-define-nested-routes-in-rails-what-are-some-advanced-routing-techniques-such-as-shallow-routes) 255 | - [8. Explain polymorphic associations in Rails. When would you choose them over standard associations?](#8-explain-polymorphic-associations-in-rails-when-would-you-choose-them-over-standard-associations) 256 | - [๐๐ฑ๐๐ฎ๐ป๐ฐ๐ฒ๐ฑ ๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐ -:](#๐๐ฑ๐๐ฎ๐ป๐ฐ๐ฒ๐ฑ-๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐--) 257 | - [9. How do you tackle the N+1 query problem in Rails? What tools or techniques do you use to optimize queries?](#9-how-do-you-tackle-the-n1-query-problem-in-rails-what-tools-or-techniques-do-you-use-to-optimize-queries) 258 | - [10. How do you handle database transactions in Rails? What steps do you take to optimize database performance through indexing and query tuning?](#10-how-do-you-handle-database-transactions-in-rails-what-steps-do-you-take-to-optimize-database-performance-through-indexing-and-query-tuning) 259 | - [11. How would you manage caching in a high-traffic, distributed Rails environment? Discuss the use of fragment, action, and page caching.](#11-how-would-you-manage-caching-in-a-high-traffic-distributed-rails-environment-discuss-the-use-of-fragment-action-and-page-caching) 260 | - [12. Discuss Railsโ built-in security features. How do you mitigate risks like CSRF, XSS, and SQL injection?](#12-discuss-rails-built-in-security-features-how-do-you-mitigate-risks-like-csrf-xss-and-sql-injection) 261 | - [13. How do you design, secure, and version API endpoints in Rails? What are your thoughts on REST vs. GraphQL?](#13-how-do-you-design-secure-and-version-api-endpoints-in-rails-what-are-your-thoughts-on-rest-vs-graphql) 262 | - [14. What architectural patterns have you implemented to ensure a Rails application scales? Discuss multi-tenancy or micro-services if applicable.](#14-what-architectural-patterns-have-you-implemented-to-ensure-a-rails-application-scales-discuss-multi-tenancy-or-micro-services-if-applicable) 263 | - [15. How do you address concurrency in Rails? Have you encountered and solved challenges with multi-threading?](#15-how-do-you-address-concurrency-in-rails-have-you-encountered-and-solved-challenges-with-multi-threading) 264 | - [16. What is sharding, and how can it be implemented in Rails to optimise data access for large datasets?](#16-what-is-sharding-and-how-can-it-be-implemented-in-rails-to-optimise-data-access-for-large-datasets) 265 | - [17. What testing frameworks and strategies (unit, integration, performance) do you rely on in Rails? How do you ensure comprehensive test coverage?](#17-what-testing-frameworks-and-strategies-unit-integration-performance-do-you-rely-on-in-rails-how-do-you-ensure-comprehensive-test-coverage) 266 | - [18. Describe your experience implementing real-time features using Action Cable. What challenges did you encounter?](#18-describe-your-experience-implementing-real-time-features-using-action-cable-what-challenges-did-you-encounter) 267 | - [19. How do you approach refactoring a large, legacy Rails codebase without causing disruptions? What tools or methodologies do you use?](#19-how-do-you-approach-refactoring-a-large-legacy-rails-codebase-without-causing-disruptions-what-tools-or-methodologies-do-you-use) 268 | - [20. Have you worked with Rails 6/7 features such as ActionMailbox, ActionText, or Hotwire? How have they influenced your development process?](#20-have-you-worked-with-rails-67-features-such-as-actionmailbox-actiontext-or-hotwire-how-have-they-influenced-your-development-process) 269 | - [21. How do you use service objects or decorators to encapsulate business logic? Share your experiences with Rubyโs meta-programming capabilities.](#21-how-do-you-use-service-objects-or-decorators-to-encapsulate-business-logic-share-your-experiences-with-rubys-meta-programming-capabilities) 270 | - [22. What role does Rack play in Rails? Have you ever built custom middleware? If so, how?](#22-what-role-does-rack-play-in-rails-have-you-ever-built-custom-middleware-if-so-how) 271 | - [23. How do you analyze and optimize database queries in Rails? What tools do you use to identify performance bottlenecks?](#23-how-do-you-analyze-and-optimize-database-queries-in-rails-what-tools-do-you-use-to-identify-performance-bottlenecks) 272 | - [How does Rails handle database connection pooling?](#how-does-rails-handle-database-connection-pooling-1) 273 | - [Explain the difference between joins, includes, preload, and eager\_load.](#explain-the-difference-between-joins-includes-preload-and-eager_load-1) 274 | - [How does Railsโ autoloading work? What changed in Zeitwerk?](#how-does-rails-autoloading-work-what-changed-in-zeitwerk-1) 275 | - [What are ActiveRecord callbacks? When should you avoid them?](#what-are-activerecord-callbacks-when-should-you-avoid-them-1) 276 | - [What are ActiveSupport Concerns? How do they differ from modules?](#what-are-activesupport-concerns-how-do-they-differ-from-modules-1) 277 | - [What is the purpose of Rails engines? When would you use one?](#what-is-the-purpose-of-rails-engines-when-would-you-use-one-1) 278 | - [How does Rails handle has\_many :through vs. has\_and\_belongs\_to\_many?](#how-does-rails-handle-has_many-through-vs-has_and_belongs_to_many-1) 279 | - [Whatโs the difference between belongs\_to and has\_one?](#whats-the-difference-between-belongs_to-and-has_one-1) 280 | - [What are Rails observers, and why are they deprecated?](#what-are-rails-observers-and-why-are-they-deprecated-1) 281 | - [How does the Rails asset pipeline work?](#how-does-the-rails-asset-pipeline-work-1) 282 | - [What are different ways to manage configurations in Rails (secrets.yml, credentials.yml.enc, ENV variables)?](#what-are-different-ways-to-manage-configurations-in-rails-secretsyml-credentialsymlenc-env-variables-1) 283 | - [What is the difference between dependent: :destroy, dependent: :delete\_all, and dependent: :nullify?](#what-is-the-difference-between-dependent-destroy-dependent-delete_all-and-dependent-nullify-1) 284 | - [How do you implement state machines in Rails (e.g., AASM, workflow gem)?](#how-do-you-implement-state-machines-in-rails-eg-aasm-workflow-gem-1) 285 | - [Whatโs the difference between rake and rails commands?](#whats-the-difference-between-rake-and-rails-commands-1) 286 | - [What are concerns, and when should they be used?](#what-are-concerns-and-when-should-they-be-used-1) 287 | - [๐ง Problem 1: Dynamic Method Generation (Metaprogramming)](#-problem-1-dynamic-method-generation-metaprogramming) 288 | - [๐ง Problem 2: Lazy Prime Generator (Enumerators)](#-problem-2-lazy-prime-generator-enumerators) 289 | - [๐ง Problem 3: Safe Concurrency with Threads](#-problem-3-safe-concurrency-with-threads) 290 | - [๐ Intermediate Rails Questions](#-intermediate-rails-questions) 291 | - [1. Handling Exceptions \& Logging](#1-handling-exceptions--logging) 292 | - [2. Database Modeling Considerations](#2-database-modeling-considerations) 293 | - [3. Managing Migrations](#3-managing-migrations) 294 | - [4. Caching Mechanisms](#4-caching-mechanisms) 295 | - [5. RESTful API Design](#5-restful-api-design) 296 | - [6. Service Objects for Business Logic](#6-service-objects-for-business-logic) 297 | - [7. Nested Routes \& Advanced Routing](#7-nested-routes--advanced-routing) 298 | - [9. N+1 Query Problem \& Optimization](#9-n1-query-problem--optimization) 299 | - [11. Caching in a Distributed Rails App](#11-caching-in-a-distributed-rails-app) 300 | - [12. Rails Security](#12-rails-security) 301 | - [14. Scaling Rails](#14-scaling-rails) 302 | - [15. Handling Concurrency](#15-handling-concurrency) 303 | - [16. Sharding in Rails](#16-sharding-in-rails) 304 | - [17. Rails Testing](#17-rails-testing) 305 | - [18. Real-Time Features (ActionCable)](#18-real-time-features-actioncable) 306 | - [19. Refactoring Legacy Rails Code](#19-refactoring-legacy-rails-code) 307 | - [20. Rails 6/7 Features](#20-rails-67-features) 308 | - [Ruby-Specific Questions](#ruby-specific-questions) 309 | - [1. Rack \& Middleware](#1-rack--middleware) 310 | - [2. N+1 Query](#2-n1-query) 311 | - [3. Concerns in Rails](#3-concerns-in-rails) 312 | - [4. HABTM vs HMT](#4-habtm-vs-hmt) 313 | - [5. Class vs. Instance Variables](#5-class-vs-instance-variables) 314 | - [6. Mutable vs. Immutable in Ruby](#6-mutable-vs-immutable-in-ruby) 315 | - [7. Ruby GC (Garbage Collection)](#7-ruby-gc-garbage-collection) 316 | - [8. include vs extend](#8-include-vs-extend) 317 | - [9. Threads vs. Fibers](#9-threads-vs-fibers) 318 | - [10. Proc vs. Lambda](#10-proc-vs-lambda) 319 | - [Final Questions](#final-questions) 320 | - [Mass Assignment \& Protection:](#mass-assignment--protection) 321 | - [Please share the type of associations in rails and how they are formed?](#please-share-the-type-of-associations-in-rails-and-how-they-are-formed) 322 | - [2. has\_one Association](#2-has_one-association) 323 | - [3. has\_many Association](#3-has_many-association) 324 | - [4. has\_many :through Association](#4-has_many-through-association) 325 | - [5. has\_and\_belongs\_to\_many (HABTM)](#5-has_and_belongs_to_many-habtm) 326 | - [6. polymorphic Association](#6-polymorphic-association) 327 | - [7. self-join (Recursive Association)](#7-self-join-recursive-association) 328 | - [Summary Table](#summary-table) 329 | 330 | 331 | ## Basic 332 | #### 1. What is MVC? 333 | MVC stands for **Model-View-Controller**. It is a design pattern used in Rails to separate concerns in an application: 334 | 335 | - **Model**: Represents the data and business logic of the application. It interacts with the database to retrieve and store information. 336 | - **View**: The presentation layer that displays the data to the user. It is typically HTML or JSON for web apps. 337 | - **Controller**: Acts as an intermediary between the Model and View. It processes user input, calls the necessary model methods, and renders the appropriate view. 338 | 339 | #### Example: 340 | ``` 341 | # Model 342 | class Post < ApplicationRecord 343 | validates :title, presence: true 344 | end 345 | 346 | # Controller 347 | class PostsController < ApplicationController 348 | def show 349 | @post = Post.find(params[:id]) 350 | end 351 | end 352 | 353 | # View (show.html.erb) 354 |
<%= @post.body %>
356 | 357 | ``` 358 | #### 2. What is ActiveRecord? 359 | ActiveRecord is the Object-Relational Mapping (ORM) layer in Rails that facilitates communication between the application and the database. It maps database tables to Ruby classes, allowing you to interact with the database using Ruby objects. 360 | 361 | ActiveRecord automatically handles CRUD operations. 362 | It allows you to query, insert, update, and delete database records without needing to write raw SQL. 363 | Example: 364 | ``` 365 | # Finding a record 366 | user = User.find(1) 367 | 368 | # Creating a new record 369 | user = User.create(name: "John", email: "john@example.com") 370 | 371 | # Updating a record 372 | user.update(name: "John Doe") 373 | 374 | # Deleting a record 375 | user.destroy 376 | ``` 377 | #### 3. What are callbacks in Rails? 378 | Callbacks in Rails are methods that get called at certain points of an object's lifecycle. They allow you to hook into and modify the behavior of ActiveRecord objects before or after certain events, such as saving, updating, or destroying records. 379 | 380 | Common Callbacks: 381 | before_save, after_save 382 | before_create, after_create 383 | before_update, after_update 384 | before_destroy, after_destroy 385 | Example: 386 | ``` 387 | 388 | class Post < ApplicationRecord 389 | before_save :set_default_title 390 | 391 | private 392 | 393 | def set_default_title 394 | self.title = "Untitled" if title.blank? 395 | end 396 | end 397 | ``` 398 | #### 4. What is mass assignment? 399 | Mass assignment occurs when you assign values to multiple attributes of an object at once, typically using the update or create methods. This is a feature in Rails that lets you assign values to several attributes in a single step. 400 | 401 | Mass assignment vulnerability occurs when an attacker can update attributes that they shouldn't be allowed to, such as sensitive fields. 402 | 403 | Example of mass assignment: 404 | ``` 405 | # Allowed attributes: name, email 406 | user = User.new(name: "John", email: "john@example.com", admin: true) # admin should not be assignable! 407 | Follow-up: How do you protect your app against it? 408 | You can prevent mass assignment vulnerabilities by using strong parameters in Rails, which explicitly define which attributes are allowed to be mass-assigned. 409 | 410 | 411 | 412 | class UsersController < ApplicationController 413 | def user_params 414 | params.require(:user).permit(:name, :email) # Only allow name and email 415 | end 416 | end 417 | ``` 418 | 419 | 420 | #### 5. What is CSRF? 421 | Cross-Site Request Forgery (CSRF) is an attack where a malicious website can send unauthorized requests to a web application where the user is already authenticated. It tricks the user into performing an unintended action. 422 | 423 | Follow-up: How is it handled in Rails? 424 | Rails protects against CSRF by using a CSRF token. This token is generated on each form and ensures that the request came from your site and not from an external source. 425 | 426 | Rails includes the token in every form by default, and itโs checked on form submissions. 427 | 428 | Example: 429 | ``` 430 | <%= form_with(url: posts_path, method: :post) do %> 431 | <%= text_field_tag :title %> 432 | <%= submit_tag "Create Post" %> 433 | <% end %> 434 | ``` 435 | Rails automatically includes a hidden CSRF token in forms generated by form_with. 436 | 437 | #### 6. How do you handle database migrations in Rails? 438 | Database migrations in Rails are used to manage changes to the database schema over time. They allow you to version-control your database structure, making it easy to roll back or apply changes. 439 | 440 | Migrations are stored in files in the db/migrate directory. 441 | They can be run using rails db:migrate. 442 | Example: 443 | ``` 444 | # Migration to add a title column to the posts table 445 | class AddTitleToPosts < ActiveRecord::Migration[6.0] 446 | def change 447 | add_column :posts, :title, :string 448 | end 449 | end 450 | Run the migration: 451 | 452 | rails db:migrate 453 | ``` 454 | #### 7. What is a scope? 455 | A scope in Rails is a way to define commonly-used queries that can be reused throughout the application. Itโs defined within the model and is typically used to simplify querying the database. 456 | 457 | Example: 458 | ``` 459 | class Post < ApplicationRecord 460 | scope :published, -> { where(published: true) } 461 | scope :recent, -> { order(created_at: :desc).limit(5) } 462 | end 463 | 464 | # Usage 465 | Post.published.recent 466 | ``` 467 | #### 8. What is the difference between has_one and belongs_to? 468 | has_one: This association indicates that one object can have one related object. It is typically used on the "one" side of a relationship. 469 | belongs_to: This association indicates that an object belongs to another object. It is used on the "many" side of the relationship. 470 | Example: 471 | ``` 472 | class Author < ApplicationRecord 473 | has_one :profile # Author has one profile 474 | end 475 | 476 | class Profile < ApplicationRecord 477 | belongs_to :author # Profile belongs to an author 478 | end 479 | 480 | In this case, an Author has one Profile, and a Profile belongs to an Author. 481 | ``` 482 | #### 9. What is Rails Console, and how do you use it? 483 | The Rails Console (rails console or rails c) is an interactive REPL (Read-Eval-Print Loop) that allows developers to run Ruby and Rails commands inside an applicationโs environment. 484 | 485 | Usage: 486 | 487 | ``` 488 | rails console # Start console in default (development) mode 489 | rails console --sandbox # Run console with changes rolled back after exit 490 | rails console production # Start console in production environment 491 | Example: 492 | 493 | # Create a new user 494 | user = User.create(name: "Alice", email: "alice@example.com") 495 | 496 | # Find a user 497 | user = User.find_by(email: "alice@example.com") 498 | 499 | # Update a user 500 | user.update(name: "Alice Doe") 501 | 502 | # Delete a user 503 | user.destroy 504 | 505 | etc 506 | ``` 507 | #### 10. What are before_action, after_action, and skip_before_action? 508 | These controller filters in Rails run specific code before or after an action. 509 | ``` 510 | before_action 511 | Runs before the controller action. 512 | 513 | class ArticlesController < ApplicationController 514 | before_action :authenticate_user 515 | 516 | def index 517 | @articles = Article.all 518 | end 519 | 520 | private 521 | 522 | def authenticate_user 523 | redirect_to login_path unless current_user 524 | end 525 | end 526 | after_action 527 | Runs after the action is executed. 528 | 529 | 530 | class ArticlesController < ApplicationController 531 | after_action :log_activity 532 | 533 | def show 534 | @article = Article.find(params[:id]) 535 | end 536 | 537 | private 538 | 539 | def log_activity 540 | Rails.logger.info("Article viewed at #{Time.now}") 541 | end 542 | end 543 | skip_before_action 544 | Skips the execution of a before_action for certain actions. 545 | 546 | class ArticlesController < ApplicationController 547 | before_action :authenticate_user 548 | skip_before_action :authenticate_user, only: [:index, :show] 549 | 550 | def index 551 | @articles = Article.all 552 | end 553 | end 554 | ``` 555 | #### 11. What are Strong Parameters? Why are they needed? 556 | Strong parameters prevent mass assignment vulnerabilities by requiring attributes to be explicitly permitted. 557 | 558 | Unsafe (Vulnerable to Mass Assignment Attack) 559 | 560 | ``` 561 | user = User.new(params[:user]) # An attacker can set `admin: true` 562 | Safe Approach (Strong Parameters) 563 | 564 | class UsersController < ApplicationController 565 | def create 566 | @user = User.new(user_params) 567 | @user.save 568 | end 569 | 570 | private 571 | 572 | def user_params 573 | params.require(:user).permit(:name, :email) 574 | end 575 | end 576 | ``` 577 | 578 | #### 12. How do you define routes in Rails? 579 | Routes define URL patterns and corresponding controller actions. 580 | ``` 581 | Basic Routes (config/routes.rb): 582 | Rails.application.routes.draw do 583 | get "/articles", to: "articles#index" 584 | post "/articles", to: "articles#create" 585 | get "/articles/:id", to: "articles#show", as: "article" 586 | end 587 | Follow-up: What is the difference between resources and resource? 588 | Method Routes Generated Example 589 | resources :users Creates 7 RESTful routes (index, show, new, create, , update, destroy) GET /users/:id/ 590 | resource :profile Creates only one route per action (no index route) GET /profile/ 591 | ``` 592 | 593 | #### 13. How do you generate a model, controller, and migration in Rails? 594 | Model: 595 | ``` 596 | rails generate model User name:string email:string 597 | Creates: 598 | 599 | app/models/user.rb 600 | db/migrate/xxxx_create_users.rb 601 | Controller: 602 | 603 | rails generate controller Users index show 604 | Creates: 605 | 606 | app/controllers/users_controller.rb 607 | app/views/users/index.html.erb 608 | app/views/users/show.html.erb 609 | Migration: 610 | 611 | 612 | rails generate migration AddAgeToUsers age:integer 613 | rails db:migrate 614 | 615 | ``` 616 | 617 | 618 | #### 14. What is the config/routes.rb file used for? 619 | This file defines all application routes that map URLs to controllers and actions. 620 | 621 | Example: 622 | 623 | ``` 624 | Rails.application.routes.draw do 625 | root "home#index" 626 | resources :articles 627 | end 628 | root "home#index" โ Homepage 629 | resources :articles โ Generates RESTful routes 630 | 631 | ``` 632 | What is the difference between render, redirect_to, and respond_to in controllers? 633 | ``` 634 | Method Purpose Example 635 | render Renders a template render "show" 636 | redirect_to Redirects to another URL redirect_to articles_path 637 | respond_to Responds with different formats (HTML, JSON) `respond_to { 638 | ``` 639 | 640 | 641 | #### 15. What is flash in Rails? How is it different from session? 642 | Flash Stores temporary messages that last one request. 643 | Commonly used for notifications. 644 | 645 | ``` 646 | flash[:notice] = "Article saved!" 647 | redirect_to articles_path 648 | Session 649 | Stores data across multiple requests. 650 | Used for user authentication. 651 | session[:user_id] = @user.id 652 | ``` 653 | 654 | #### 16. How does Rails handle sessions and cookies? 655 | Session stores data server-side (e.g., in cookies or Redis). 656 | Cookies store small amounts of client-side data. 657 | ``` 658 | Example (Using Sessions): 659 | session[:user_id] = @user.id 660 | Example (Using Cookies): 661 | 662 | cookies[:user_id] = { value: @user.id, expires: 1.week.from_now } 663 | ``` 664 | #### 17. What is link_to in Rails views? 665 | Used to generate HTML tags dynamically. 666 | 667 | ``` 668 | <%= link_to "Home", root_path %> 669 | Follow-up: How can you make link_to submit a form? 670 | <%= link_to "Delete", article_path(@article), method: :delete, data: { confirm: "Are you sure?" } %> 671 | ``` 672 | #### 18. What is form_with, and how does it work? 673 | Used to generate forms dynamically in Rails. 674 | 675 | ``` 676 | <%= form_with model: @article, local: true do |f| %> 677 | <%= f.text_field :title %> 678 | <%= f.submit "Save" %> 679 | <% end %> 680 | ``` 681 | #### 19. What is partial in Rails views? 682 | A partial is a reusable view component. 683 | 684 | Usage: 685 | 686 | ``` 687 | <%= render "shared/header" %> 688 | Follow-up: How do you pass local variables to a partial? 689 | 690 | <%= render "article", article: @article %> 691 | Partial _article.html.erb: 692 | 693 | 694 |<%= article.content %>
742 |Published on <%= formatted_date(@article.created_at) %>
803 | ``` 804 | Follow-up: When should you use a helper vs. a partial? 805 | 806 | Use Case Helper Partial 807 | Formatting data โ Yes โ No 808 | Repeating view elements โ No โ Yes 809 | 810 | #### 26. What is params in Rails, and how does it work? 811 | params stores request data (e.g., form inputs, URL parameters). 812 | 813 | Example Controller: 814 | ``` 815 | class ArticlesController < ApplicationController 816 | def show 817 | @article = Article.find(params[:id]) # Fetch from URL 818 | end 819 | 820 | def create 821 | @article = Article.new(params.require(:article).permit(:title, :content)) # Form Data 822 | end 823 | end 824 | ``` 825 | 826 | #### 27. What is the difference between GET, POST, PUT, and DELETE requests in Rails? 827 | HTTP Method Purpose Example Usage 828 | GET Read data GET /articles/1 829 | POST Create data POST /articles 830 | PUT Update entire record PUT /articles/1 831 | DELETE Delete a record DELETE /articles/1 832 | 833 | 834 | #### 28. What is rails routes, and how do you use it? 835 | Lists all available routes in a Rails app. 836 | ``` 837 | rails routes 838 | Example Output: 839 | 840 | articles GET /articles(.:format) articles#index 841 | ``` 842 | 843 | #### 29. What is has_many :through, and when do you use it? 844 | It sets up a many-to-many relationship via a join table. 845 | ``` 846 | class User < ApplicationRecord 847 | has_many :user_projects 848 | has_many :projects, through: :user_projects 849 | end 850 | 851 | class UserProject < ApplicationRecord 852 | belongs_to :user 853 | belongs_to :project 854 | end 855 | 856 | class Project < ApplicationRecord 857 | has_many :user_projects 858 | has_many :users, through: :user_projects 859 | end 860 | ``` 861 | 862 | #### 30. What is validates in Rails models? 863 | validates ensures data integrity before saving records. 864 | ``` 865 | class User < ApplicationRecord 866 | validates :name, presence: true, length: { minimum: 3 } 867 | validates :email, uniqueness: true 868 | end 869 | Follow-up: What are some common validation options? 870 | Validation Example 871 | presence: true Ensures value is present 872 | uniqueness: true Ensures unique values 873 | length: { minimum: x } Min character length 874 | format: { with: /regex/ } Custom regex validation 875 | ``` 876 | 877 | #### 31. What is rescue_from, and how does it work? 878 | rescue_from handles exceptions globally in controllers. 879 | ``` 880 | class ApplicationController < ActionController::Base 881 | rescue_from ActiveRecord::RecordNotFound, with: :not_found 882 | 883 | private 884 | 885 | def not_found 886 | render plain: "404 Not Found", status: :not_found 887 | end 888 | end 889 | ``` 890 | 891 | #### 32. What is rake, and how does it work in Rails? 892 | Rake (Ruby Make) automates tasks like migrations and seeding. 893 | ``` 894 | rake db:migrate 895 | rake db:seed 896 | Follow-up: What is the difference between rake and rails commands? 897 | Command Purpose 898 | rake Runs tasks (e.g., migrations) 899 | rails Runs commands (e.g., server, console) 900 | ``` 901 | 902 | #### ๐ 1. Handling N+1 Queries (Optimization) 903 | To handle N+1 queries in Rails, We typically use eager loading with `includes`, `preload`, or `eager_load`. This ensures that associated records are fetched in a single query rather than one per record. 904 | โ Problem: 905 | ``` 906 | # N+1 Issue 907 | Post.all.each do |post| 908 | puts post.comments.count 909 | end 910 | users = User.all 911 | users.each do |user| 912 | puts user.posts.count 913 | end 914 | ``` 915 | This results in one query per user, leading to an N+1 query issue. 916 | 917 | โ Solution: Use includes for Eager Loading 918 | ``` 919 | users = User.includes(:posts) # Fetch users & posts in 1 query 920 | users.each do |user| 921 | puts user.posts.count # Does not make extra queries 922 | end 923 | 924 | # Optimized with eager loading 925 | Post.includes(:comments).each do |post| 926 | puts post.comments.count 927 | end 928 | ``` 929 | ๐ includes loads the associated records efficiently. 930 | `preload`: 931 | 932 | Use when: You want to load the associations in a separate query (good for simple display, not for SQL conditions on joined tables). 933 | 934 | ``` 935 | # This will run two queries: 936 | # 1. SELECT * FROM posts 937 | # 2. SELECT * FROM comments WHERE post_id IN (...) 938 | 939 | posts = Post.preload(:comments) 940 | posts.each do |post| 941 | post.comments.each do |comment| 942 | puts comment.body 943 | end 944 | end 945 | ``` 946 | `eager_load`: 947 | Use when: You want to avoid N+1 and also filter or sort based on associated table columns using a single SQL query with a JOIN. 948 | ``` 949 | # This performs a LEFT OUTER JOIN in one SQL query 950 | posts = Post.eager_load(:comments).where("comments.created_at > ?", 1.week.ago) 951 | 952 | posts.each do |post| 953 | post.comments.each do |comment| 954 | puts comment.body 955 | end 956 | end 957 | ``` 958 | This is helpful when the query involves conditions on the joined table (comments), and Rails handles the LEFT OUTER JOIN automatically. 959 | ``` 960 | Summary: 961 | Method Type of Query Use Case 962 | includes Smartly chooses join/preload Safe default for most use cases 963 | preload Separate queries Display data without filtering/sorting on join 964 | eager_load Single joined query Needed when filtering/sorting using joined table 965 | ``` 966 | 967 | #### ๐ 2. Implementing Caching in Rails 968 | ๐น Fragment Caching 969 | 970 | Use case: You want to cache a specific section of the view, like a post card or sidebar, to avoid rendering it again and again. 971 | 972 | How it works: 973 | 974 | Rails generates a cache key for the object (like views/posts/123-20250422113000) based on its class, ID, and updated_at timestamp. If the key exists in the cache store, it reuses the HTML output instead of rerendering. 975 | 976 | Cache key tip: 977 | 978 | Rails automatically uses cache_key_with_version (e.g., posts/123-20250422120000) so you donโt need to manually manage invalidation unless you have custom logic. 979 | ``` 980 | - cache @post do 981 | .post 982 | %h2= @post.title 983 | %p= @post.body 984 | 985 | Best practices: 986 | Use meaningful keys if you're caching non-record-based content: 987 | 988 | 989 | - cache ['sidebar', current_user.role] do 990 | = render 'shared/sidebar' 991 | 992 | ``` 993 | ๐น Russian Doll Caching: 994 | 995 | Use case: 996 | 997 | Your view has multiple nested partials (e.g., posts with comments), and you want to cache each layer separately to avoid cache invalidation of the entire block. 998 | 999 | Why it's powerful: 1000 | 1001 | If a comment changes, only the comment block cache is invalidated, not the entire post. Rails handles this efficiently using cache keys with timestamps. 1002 | ``` 1003 | - cache @post do 1004 | .post 1005 | %h2= @post.title 1006 | %p= @post.body 1007 | 1008 | - cache @post.comments do 1009 | .comments 1010 | = render @post.comments 1011 | 1012 | In the above example: 1013 | 1014 | If @post.updated_at changes โ outer cache invalidated. 1015 | 1016 | If a comment changes โ only @post.comments cache is invalidated. 1017 | 1018 | 1019 | ``` 1020 | ๐ Caches the HTML output of the article block. 1021 | 1022 | ๐น Low-Level Caching 1023 | 1024 | Use case: When you want to cache arbitrary data โ like a set of records, a computed value, or external API results โ at the controller or model level. 1025 | 1026 | How it works: 1027 | 1028 | You manually define a cache key and use Rails.cache.fetch to store and retrieve data. If the key is not present in the cache, the block is executed and the result is cached. 1029 | 1030 | Example โ Top Posts: 1031 | ``` 1032 | # In controller or service object 1033 | def top_posts 1034 | Rails.cache.fetch("top_posts", expires_in: 12.hours) do 1035 | Post.order(views: :desc).limit(10).to_a 1036 | end 1037 | end 1038 | - This avoids hitting the DB every time users visit the homepage or dashboard. 1039 | 1040 | You can add user-specific or context-specific info to the key: 1041 | 1042 | Rails.cache.fetch(["top_posts", current_user.role], expires_in: 6.hours) do 1043 | Post.visible_to(current_user).order(created_at: :desc).limit(10) 1044 | end 1045 | 1046 | Rails.cache.fetch("recent_articles", expires_in: 10.minutes) do 1047 | Article.order(created_at: :desc).limit(5) 1048 | end 1049 | ๐ Caches query results for 10 minutes. 1050 | 1051 | ``` 1052 | ๐น HTTP Caching 1053 | 1054 | Use case: When you want to reduce bandwidth and avoid unnecessary re-rendering by allowing browsers or CDNs to use cached versions of your content. 1055 | 1056 | Rails provides built-in helpers like `fresh_when` and `stale?` to implement this based on the recordโs `updated_at` timestamp and `cache_key`. 1057 | 1058 | Example using fresh_when: 1059 | ``` 1060 | def show 1061 | @article = Article.find(params[:id]) 1062 | fresh_when(@article) # Sets ETag and Last-Modified headers 1063 | end 1064 | If the content hasnโt changed since the last request, Rails will respond with 304 Not Modified, skipping the view rendering. 1065 | ``` 1066 | Example using stale?: 1067 | ``` 1068 | def show 1069 | @article = Article.find(params[:id]) 1070 | if stale?(@article) 1071 | render :show 1072 | end 1073 | end 1074 | stale? checks if the content is outdated and only renders if necessary. 1075 | ``` 1076 | Production Cache Store 1077 | In production, I typically configure a high-performance cache backend: 1078 | 1079 | Redis: Great for both caching and session storage. It supports advanced features like key expiry, namespaces, etc. 1080 | 1081 | Memcached: Lightweight and super-fast, good for ephemeral cache use cases. 1082 | 1083 | Example in config/environments/production.rb: 1084 | ``` 1085 | config.cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] } 1086 | ``` 1087 | 1088 | Pro Tips: 1089 | Enable config.action_controller.perform_caching = true in development to test this. 1090 | 1091 | Use tools like rack-mini-profiler or fragment-cacher to inspect which fragments are being hit or missed. 1092 | 1093 | Keep cache blocks small and specificโavoid putting entire pages inside one cache block unless absolutely necessary. 1094 | 1095 | 1096 | ๐ ๐๐ฒ๐๐ฒ๐น ๐จ๐ฝ ๐ฌ๐ผ๐๐ฟ ๐ฅ๐ฎ๐ถ๐น๐ ๐๐ป๐ผ๐๐น๐ฒ๐ฑ๐ด๐ฒ ๐๐ถ๐๐ต ๐ง๐ต๐ฒ๐๐ฒ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐ ๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐ ๐ 1097 | 1098 | #### 5. When to Use Proc vs. Lambda 1099 | Feature Proc Lambda 1100 | Arity Check Allows missing arguments (defaults to nil). Strictly enforces the number of arguments. 1101 | Return Behavior Exits the method immediately. Returns control to the method. 1102 | Use Case Flexible argument handling, quick inline logic. Function-like behavior with strict argument handling. 1103 | 1104 | #### 6. Real-World Use Cases 1105 | ``` 1106 | Using Proc in Dynamic Method Execution 1107 | 1108 | def perform_action(action) 1109 | actions = { 1110 | greet: Proc.new { puts "Hello!" }, 1111 | farewell: Proc.new { puts "Goodbye!" } 1112 | } 1113 | actions[action].call if actions[action] 1114 | end 1115 | 1116 | perform_action(:greet) # Output: "Hello!" 1117 | perform_action(:farewell) # Output: "Goodbye!" 1118 | ``` 1119 | Using Lambda for Strict Validations 1120 | ``` 1121 | validate_input = ->(name, age) { 1122 | raise "Invalid name" if name.nil? || name.empty? 1123 | raise "Invalid age" if age < 18 1124 | "Welcome, #{name}!" 1125 | } 1126 | 1127 | puts validate_input.call("Alice", 20) # โ Output: "Welcome, Alice!" 1128 | puts validate_input.call("", 25) # โ Raises error "Invalid name" 1129 | ``` 1130 | 1131 | #### Summary 1132 | ``` 1133 | Feature Proc (Proc.new) Lambda (-> {}) 1134 | Arity (Arguments Handling) Doesn't enforce argument count (missing args = nil). Strict argument checking (errors if missing). 1135 | Return Behavior Exits the calling method immediately. Returns control to the calling method. 1136 | Use Case When flexibility is needed. When strict function-like behavior is required. 1137 | ``` 1138 | 1139 | ๐ก TL;DR 1140 | Use Procs when you want loose argument handling and early exit behavior. 1141 | 1142 | Use Lambdas when you want strict function-like execution. 1143 | 1144 | 1145 | #### Explain Sharding ? 1146 | Sharding is a database partitioning technique that distributes data across multiple databases or servers to improve performance, scalability, and availability. Instead of storing all records in a single database, data is split (sharded) into multiple databases based on a specific key (e.g., user ID, region, tenant). 1147 | 1148 | #### Why Use Sharding? 1149 | #### โ Benefits of Sharding 1150 | Scalability โ Distributes load across multiple database instances. 1151 | 1152 | Performance โ Reduces query time by limiting the data each query scans. 1153 | 1154 | Fault Tolerance โ Failure in one shard doesnโt affect others. 1155 | 1156 | Multi-tenancy Support โ Different customers (tenants) can be stored in separate databases. 1157 | 1158 | 1159 | #### How Does Sharding Work in Rails? 1160 | Rails 6+ provides built-in support for database sharding using the multiple databases feature (config/database.yml). 1161 | 1162 | Example: User Data Sharded Across Multiple Databases 1163 | ``` 1164 | # config/database.yml 1165 | production: 1166 | primary: 1167 | adapter: postgresql 1168 | database: main_db 1169 | host: db1.example.com 1170 | shard_1: 1171 | adapter: postgresql 1172 | database: shard1_db 1173 | host: db2.example.com 1174 | shard_2: 1175 | adapter: postgresql 1176 | database: shard2_db 1177 | host: db3.example.com 1178 | Each database (shard_1, shard_2) contains a subset of the total records. 1179 | ``` 1180 | #### ๐น Implementing Sharding in Rails 1181 | Step 1: Define Database Connections 1182 | Modify database.yml to add shard configurations. 1183 | 1184 | Step 2: Switch Between Shards in Models 1185 | Use connects_to in the model: 1186 | ``` 1187 | class User < ApplicationRecord 1188 | connects_to database: { writing: :shard_1, reading: :shard_1 } 1189 | end 1190 | ``` 1191 | Step 3: Manually Switch Shards in Queries 1192 | ``` 1193 | ActiveRecord::Base.connected_to(role: :writing, shard: :shard_1) do 1194 | User.create(name: "Alice") 1195 | end 1196 | ``` 1197 | Step 4: Auto-Route Requests Based on Shard Key 1198 | Example: Shard based on user region. 1199 | ``` 1200 | def set_shard 1201 | user_region = params[:region] # Example: "asia" 1202 | shard = "shard_#{user_region}" 1203 | ActiveRecord::Base.connected_to(role: :writing, shard: shard) do 1204 | yield 1205 | end 1206 | end 1207 | ``` 1208 | This method automatically connects to the appropriate shard. 1209 | 1210 | #### When to Use Sharding? 1211 | Use Case Should You Use Sharding? 1212 | Millions of rows per table โ Yes 1213 | Multi-tenancy (separate databases per customer) โ Yes 1214 | Geo-distributed applications โ Yes 1215 | Simple CRUD apps with low traffic โ No 1216 | Short-term performance issues (use indexing instead) โ No 1217 | 1218 | Alternatives to Sharding 1219 | Read Replicas โ Separate read and write databases (primary, replica). 1220 | 1221 | Partitioning โ Store different data segments in the same database (PostgreSQL table partitioning). 1222 | 1223 | TL;DR 1224 | Sharding splits data across multiple databases to improve performance and scalability. 1225 | 1226 | Rails 6+ supports multi-database configurations (connects_to, connected_to). 1227 | 1228 | Use sharding when dealing with high-volume, multi-tenant, or geographically distributed applications. 1229 | 1230 | 1231 | ### ๐ Core Rails Questions 1232 | #### How does Rails handle database connection pooling? 1233 | What is Database Connection Pooling? 1234 | 1235 | Database connection pooling is a technique where a fixed number of database connections are maintained and reused across requests. Instead of opening and closing a connection for each request (which is expensive), Rails maintains a "pool" of open connections to improve performance and reduce overhead. 1236 | 1237 | Rails uses ActiveRecordโs built-in connection pool, which is managed by ActiveRecord::ConnectionAdapters::ConnectionPool. Here's how it works under the hood: 1238 | 1239 | Pool Initialization: 1240 | 1241 | When the app boots, Rails reads the config/database.yml file and initializes a connection pool per environment (and per role/shard if you're using multi-DB). 1242 | 1243 | Per-thread: Checkout Each thread (e.g., Puma worker thread) checks out a connection from the pool when needed. The same thread reuses that connection throughout the request. 1244 | 1245 | Connection Checkout and Check-in: 1246 | 1247 | When a request begins โ Rails checks out a connection. 1248 | 1249 | When the request ends โ Rails checks it back into the pool. 1250 | 1251 | If all connections are in use, new threads will wait (up to a timeout) for a connection to free up. 1252 | 1253 | Connection Pool Settings (from database.yml) 1254 | ``` 1255 | production: 1256 | adapter: postgresql 1257 | database: myapp_production 1258 | pool: 15 # number of connections 1259 | timeout: 5000 # wait time (ms) before raising a timeout error 1260 | ``` 1261 | 1262 | 1263 | Common Issues 1264 | 1. Too Small Pool Size 1265 | 1266 | If your app handles many concurrent requests, and your pool size is too low, youโll see: 1267 | ``` 1268 | ActiveRecord::ConnectionTimeoutError: could not obtain a database connection within 5 seconds 1269 | ``` 1270 | 2. Too Large Pool Size 1271 | 1272 | Oversizing the pool can exhaust the database's max connections, especially if you scale horizontally. 1273 | 1274 | Summary: 1275 | 1276 | Rails maintains a per-thread connection pool using ActiveRecord. 1277 | 1278 | Connections are checked out at request start and checked in at the end. 1279 | 1280 | You configure the pool size and timeout in database.yml. 1281 | 1282 | Tuning the pool size is critical for performance and stability in production environments. 1283 | 1284 | 1285 | #### What are ActiveRecord callbacks? When should you avoid them? 1286 | ActiveRecord callbacks are lifecycle hooks in Rails that allow you to run code before or after certain events on a model โ such as create, update, save, or destroy. 1287 | 1288 | Theyโre used to encapsulate logic that is tightly coupled to a model's data lifecycle. 1289 | 1290 | Common Callbacks: 1291 | ``` 1292 | class Post < ApplicationRecord 1293 | before_save :generate_slug 1294 | after_create :send_notification 1295 | before_destroy :log_deletion 1296 | end 1297 | ``` 1298 | eg: 1299 | ``` 1300 | before_validation, after_save, after_create, before_update, before_destroy etc 1301 | ``` 1302 | 1303 | When to Use Them: 1304 | 1305 | Auto-generating fields (e.g., slugs, tokens) 1306 | 1307 | Logging/auditing changes 1308 | 1309 | Sending notifications or triggering side effects after save 1310 | 1311 | Enforcing business rules closely tied to the modelโs lifecycle 1312 | 1313 | When to Avoid Callbacks (Best Practices): 1314 | 1315 | Complex Business Logic: 1316 | 1317 | โค Move logic into service objects or jobs. 1318 | 1319 | Callbacks can make models "do too much" and harder to test/debug. 1320 | 1321 | 1322 | #### What are ActiveSupport Concerns? How do they differ from modules? 1323 | What are ActiveSupport::Concerns? 1324 | ActiveSupport::Concern is a Rails helper module that provides a clean and structured way to write reusable code (usually shared logic) and include it into models, controllers, or other classes. 1325 | 1326 | It builds on Rubyโs native Module but adds a few Rails-specific conveniences for: 1327 | 1328 | Organizing code more cleanly 1329 | 1330 | Hooking into lifecycle methods (included, class_methods) 1331 | 1332 | Avoiding tricky included do blocks and meta-programming 1333 | 1334 | Basic Structure of a Concern 1335 | ``` 1336 | module Archivable 1337 | extend ActiveSupport::Concern 1338 | 1339 | included do 1340 | scope :archived, -> { where(archived: true) } 1341 | end 1342 | 1343 | def archive! 1344 | update(archived: true) 1345 | end 1346 | 1347 | module ClassMethods 1348 | def recently_archived 1349 | where("archived_at >= ?", 1.week.ago) 1350 | end 1351 | end 1352 | end 1353 | ``` 1354 | ``` 1355 | How It Differs From a Plain Ruby Module: 1356 | Feature Module ActiveSupport::Concern 1357 | Basic inclusion โ Yes โ Yes 1358 | Clean included do syntax โ No โ Yes 1359 | Handles ClassMethods automatically โ No โ Yes 1360 | Designed for Rails (scopes, callbacks) โ No โ Yes 1361 | Explicit load order safety โ Risk of bugs โ Prevents common issues 1362 | ``` 1363 | 1364 | Example Use Case: Archivable Records 1365 | ``` 1366 | Imagine you have multiple models (like Post, Comment, Document) that need to support archiving โ a common behavior with archived: true/false. 1367 | 1368 | Weโll extract this logic into a reusable concern called Archivable. 1369 | Step 1: Create the Concern 1370 | 1371 | 1372 | # app/models/concerns/archivable.rb 1373 | module Archivable 1374 | extend ActiveSupport::Concern 1375 | 1376 | included do 1377 | scope :archived, -> { where(archived: true) } 1378 | scope :unarchived, -> { where(archived: false) } 1379 | end 1380 | 1381 | def archive! 1382 | update(archived: true) 1383 | end 1384 | 1385 | def unarchive! 1386 | update(archived: false) 1387 | end 1388 | 1389 | def archived? 1390 | archived 1391 | end 1392 | end 1393 | 1394 | Step 2: Include it in your model 1395 | 1396 | # app/models/post.rb 1397 | class Post < ApplicationRecord 1398 | include Archivable 1399 | 1400 | # other associations, validations, etc. 1401 | end 1402 | 1403 | # app/models/comment.rb 1404 | class Comment < ApplicationRecord 1405 | include Archivable 1406 | 1407 | # other logic 1408 | end 1409 | 1410 | Step 3: Use it in Your Application 1411 | 1412 | # Archive a post 1413 | post = Post.find(params[:id]) 1414 | post.archive! 1415 | 1416 | # List only archived posts 1417 | Post.archived 1418 | 1419 | # Check if a comment is archived 1420 | comment.archived? 1421 | 1422 | # Get all unarchived comments 1423 | Comment.unarchived 1424 | ``` 1425 | 1426 | 1427 | #### What is the purpose of Rails engines? When would you use one? 1428 | 1429 | #### How does Rails handle has_many :through vs. has_and_belongs_to_many? 1430 | Both are used to set up many-to-many relationships in Rails, but they differ in flexibility and use case. 1431 | 1432 | has_and_belongs_to_many (HABTM): 1433 | 1434 | Direct many-to-many association with no intermediate model. 1435 | 1436 | Uses a join table (e.g., students_courses) without a corresponding model. 1437 | ``` 1438 | # app/models/student.rb 1439 | class Student < ApplicationRecord 1440 | has_and_belongs_to_many :courses 1441 | end 1442 | 1443 | # app/models/course.rb 1444 | class Course < ApplicationRecord 1445 | has_and_belongs_to_many :students 1446 | end 1447 | ``` 1448 | Requires a join table migration: 1449 | ``` 1450 | create_join_table :students, :courses 1451 | ``` 1452 | Limitations: 1453 | 1454 | Cannot store additional data (e.g., enrollment date, grade) on the relationship. 1455 | 1456 | Less flexible for validations and callbacks. 1457 | 1458 | has_many :through 1459 | Uses an intermediate model to manage the relationship. 1460 | 1461 | Ideal when you need to store extra data or add logic to the join. 1462 | ``` 1463 | # app/models/student.rb 1464 | class Student < ApplicationRecord 1465 | has_many :enrollments 1466 | has_many :courses, through: :enrollments 1467 | end 1468 | 1469 | # app/models/enrollment.rb 1470 | class Enrollment < ApplicationRecord 1471 | belongs_to :student 1472 | belongs_to :course 1473 | 1474 | # extra fields: enrolled_at, grade, etc. 1475 | end 1476 | 1477 | # app/models/course.rb 1478 | class Course < ApplicationRecord 1479 | has_many :enrollments 1480 | has_many :students, through: :enrollments 1481 | end 1482 | ``` 1483 | Advantages: 1484 | 1485 | More powerful and flexible 1486 | 1487 | Allows custom validations, callbacks, and extra attributes on the join model 1488 | 1489 | Summary: 1490 | ``` 1491 | Feature has_and_belongs_to_many has_many :through 1492 | Join Table Yes (no model) Yes (with model) 1493 | Extra Attributes โ Not possible โ Yes 1494 | Validations/Callbacks โ No โ Yes 1495 | Preferred for Simple joins Complex logic, extra fields 1496 | ``` 1497 | 1498 | #### Whatโs the difference between belongs_to and has_one? 1499 | These are both one-to-one associations but from opposite directions: 1500 | 1501 | belongs_to 1502 | 1503 | Declares ownership from the child side. 1504 | 1505 | The table has the foreign key column. 1506 | 1507 | Used when the current model "belongs to" another. 1508 | 1509 | ``` 1510 | class Order < ApplicationRecord 1511 | belongs_to :user # foreign key: user_id 1512 | end 1513 | ``` 1514 | has_one: 1515 | 1516 | Declares ownership from the parent side. 1517 | 1518 | Points to a related record that exists only once. 1519 | 1520 | Often used when you want to access a related model from the owning model. 1521 | ``` 1522 | class User < ApplicationRecord 1523 | has_one :profile 1524 | end 1525 | ``` 1526 | ``` 1527 | โ Summary: 1528 | 1529 | Feature belongs_to has_one 1530 | Owns the FK โ Yes โ No 1531 | Declares on Child model Parent model 1532 | Association direction Inward Outward 1533 | Example Order โ belongs_to :user User โ has_one :profile 1534 | ``` 1535 | 1536 | #### What are different ways to manage configurations in Rails (secrets.yml, credentials.yml.enc, ENV variables)? 1537 | Rails provides several ways to manage sensitive data and environment-specific settings like API keys, database credentials, and secret tokens. 1538 | 1539 | 1. secrets.yml (Rails < 5.2) 1540 | Located in config/secrets.yml 1541 | 1542 | Used for storing application secrets per environment. 1543 | 1544 | Loaded via Rails.application.secrets[:your_key] 1545 | 1546 | Example: 1547 | ``` 1548 | production: 1549 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 1550 | stripe_secret: <%= ENV["STRIPE_SECRET"] %> 1551 | ``` 1552 | Deprecated in favor of credentials.yml.enc in Rails 5.2+ 1553 | 1554 | 2. credentials.yml.enc (Rails 5.2+) 1555 | Encrypted file managed by Rails for storing secrets. 1556 | 1557 | Decrypted using the master key (config/master.key) or ENV["RAILS_MASTER_KEY"]. 1558 | 1559 | Location: 1560 | 1561 | config/credentials.yml.enc 1562 | 1563 | Decrypted with: rails credentials:edit 1564 | 1565 | Example: 1566 | ``` 1567 | aws: 1568 | access_key_id: 123 1569 | secret_access_key: 456 1570 | 1571 | stripe: 1572 | secret_key: sk_test_123 1573 | ``` 1574 | Access: 1575 | ``` 1576 | Rails.application.credentials.aws[:access_key_id] 1577 | Rails.application.credentials[:stripe][:secret_key] 1578 | ``` 1579 | Recommended for most applications unless using multi-environment credentials (see below). 1580 | ``` 1581 | Use Case Recommended Approach 1582 | Small to medium app with default secrets credentials.yml.enc 1583 | Separate dev, staging, and prod credentials Multi-env credentials 1584 | Secrets managed externally (Heroku, AWS, Docker) ENV variables 1585 | Legacy apps (Rails < 5.2) secrets.yml (legacy only) 1586 | ``` 1587 | 1588 | #### What is the difference between dependent: :destroy, dependent: :delete_all, and dependent: :nullify? 1589 | #### How do you implement state machines in Rails (e.g., AASM, workflow gem)? 1590 | #### Whatโs the difference between rake and rails commands? 1591 | #### What are concerns, and when should they be used? 1592 | #### Explain the difference between joins, includes, preload, and eager_load. 1593 | #### How does Railsโ autoloading work? What changed in Zeitwerk? 1594 | #### What are Rails observers, and why are they deprecated? 1595 | #### How does the Rails asset pipeline work? 1596 | 1597 | 1598 | ### โก Performance & Scalability 1599 | 1600 | #### What techniques do you use to prevent N+1 queries? 1601 | #### What is database sharding? How does Rails support it? 1602 | #### How do you analyze slow database queries in Rails? 1603 | #### What is caching in Rails? How does fragment caching work? 1604 | #### How do you handle background jobs at scale in Rails? 1605 | #### What are the advantages and disadvantages of Sidekiq vs. Delayed Job vs. Resque? 1606 | #### What is a Rails middleware? How do you add a custom middleware? 1607 | #### How do you scale a Rails application to handle high traffic? 1608 | #### What are different types of caching available in Rails? 1609 | #### What is Puma? How does it improve Rails performance? 1610 | #### How does Rails handle HTTP/2 and WebSockets? 1611 | #### What are the best practices for optimizing ActiveRecord queries? 1612 | #### Whatโs the difference between connection_pool and database.yml settings? 1613 | #### How do you handle large file uploads in Rails? 1614 | #### Whatโs the difference between synchronous and asynchronous processing in Rails? 1615 | 1616 | ### ๐ก๏ธ Security & Best Practices 1617 | #### What is CSRF, and how does Rails prevent it? 1618 | #### What is SQL injection? How does Rails prevent it? 1619 | #### How does Rails handle Cross-Site Scripting (XSS) vulnerabilities? 1620 | #### What is mass assignment, and how can it be prevented? 1621 | #### What is the difference between strong_parameters and attr_accessible? 1622 | #### What is session fixation, and how does Rails mitigate it? 1623 | #### What is secure_compare and why is it important? 1624 | #### How do you prevent brute-force attacks in Rails authentication? 1625 | #### How does Devise handle authentication and security? 1626 | #### What are Rails' default security mechanisms (e.g., Secure Headers, HTTP-only cookies)? 1627 | #### How do you enforce password policies in Rails apps? 1628 | #### What is parameter tampering, and how does Rails prevent it? 1629 | #### How do you secure Rails APIs (rate limiting, JWT, OAuth)? 1630 | #### What is the difference between session_store and cookie_store? 1631 | #### What is CORS, and how does Rails handle it? 1632 | #### What is permanent_signed vs. signed cookies in Rails? 1633 | #### How do you handle authorization (Pundit vs. CanCanCan)? 1634 | #### How do you prevent replay attacks in Rails? 1635 | #### What is rails-ujs, and how does it help with security? 1636 | #### How do you enforce HTTPS in a Rails application? 1637 | 1638 | ### ๐ System Design & Architecture 1639 | #### What is REST, and how does Rails enforce RESTful design? 1640 | #### How do you implement API versioning in Rails? 1641 | #### What are the key differences between REST and GraphQL? 1642 | #### How would you design a multi-tenant Rails application? 1643 | #### How does Rails handle WebSockets and real-time features? 1644 | #### How do you design a microservices-based architecture with Rails? 1645 | #### What are the trade-offs of monolithic vs. microservices architecture in Rails? 1646 | #### What are design considerations for building a large-scale Rails API? 1647 | #### How do you handle background jobs in a multi-server environment? 1648 | #### How do you handle file storage in Rails (ActiveStorage, Shrine, Paperclip)? 1649 | #### What is CQRS, and how can it be applied in Rails applications? 1650 | #### How do you handle rate-limiting in Rails APIs? 1651 | #### What are the challenges of running Rails in a containerized environment (Docker, Kubernetes)? 1652 | #### How would you handle real-time notifications in Rails? 1653 | #### How do you implement event-driven architecture in Rails? 1654 | #### What are the key performance bottlenecks in a Rails application? 1655 | #### What are the key differences between Rails and other frameworks like Django or Laravel? 1656 | #### How do you handle service-to-service authentication in a Rails microservices setup? 1657 | #### How do you optimize database indexes for large-scale Rails applications? 1658 | #### How would you design a rate-limiting system in Rails?๐ System Design & Architecture 1659 | #### What is REST, and how does Rails enforce RESTful design? 1660 | #### How do you implement API versioning in Rails? 1661 | #### What are the key differences between REST and GraphQL? 1662 | #### How would you design a multi-tenant Rails application? 1663 | #### How does Rails handle WebSockets and real-time features? 1664 | #### How do you design a microservices-based architecture with Rails? 1665 | #### What are the trade-offs of monolithic vs. microservices architecture in Rails? 1666 | #### What are design considerations for building a large-scale Rails API? 1667 | #### How do you handle background jobs in a multi-server environment? 1668 | #### How do you handle file storage in Rails (ActiveStorage, Shrine, Paperclip)? 1669 | #### What is CQRS, and how can it be applied in Rails applications? 1670 | #### How do you handle rate-limiting in Rails APIs? 1671 | #### What are the challenges of running Rails in a containerized environment (Docker, Kubernetes)? 1672 | #### How would you handle real-time notifications in Rails? 1673 | #### How do you implement event-driven architecture in Rails? 1674 | #### What are the key performance bottlenecks in a Rails application? 1675 | #### What are the key differences between Rails and other frameworks like Django or Laravel? 1676 | #### How do you handle service-to-service authentication in a Rails microservices setup? 1677 | #### How do you optimize database indexes for large-scale Rails applications? 1678 | #### How would you design a rate-limiting system in Rails? 1679 | 1680 | ### ๐ Advanced Ruby Questions 1681 | #### What is the difference between Proc and Lambda? 1682 | #### What is the difference between include, extend, and prepend? 1683 | #### How does Ruby garbage collection (GC) work? 1684 | 1685 | How It Works (Conceptually) 1686 | 1687 | Rubyโs GC follows a "mark-and-sweep" algorithm, with enhancements in newer versions: 1688 | 1689 | Mark Phase 1690 | 1691 | Ruby walks through all "reachable" objects โ starting from root references (like global variables, method stacks, etc.). 1692 | 1693 | Marks them as "in use." 1694 | 1695 | Sweep Phase 1696 | 1697 | All objects that werenโt marked are considered unused and are freed from memory. 1698 | 1699 | #### What is the difference between Thread and Fiber? 1700 | #### What are Ruby metaprogramming techniques? 1701 | #### What are method_missing and respond_to_missing? 1702 | These are part of Rubyโs dynamic method handling. They allow objects to respond to method calls even if those methods are not explicitly defined โ a key part of Ruby's metaprogramming capabilities. 1703 | 1704 | method_missing: 1705 | 1706 | A special method you can override to intercept calls to undefined methods. 1707 | 1708 | Commonly used in dynamic proxies, DSLs, or delegators. 1709 | 1710 | respond_to_missing? 1711 | 1712 | Used in combination with method_missing to make respond_to? return true for dynamically handled methods. 1713 | 1714 | Helps tools like irb, introspection, and method lookup work correctly. 1715 | 1716 | #### What are singleton classes and eigenclasses in Ruby? 1717 | #### What is duck typing in Ruby? 1718 | In Ruby, an objectโs type doesnโt matter โ what matters is whether it responds to the methods you need. 1719 | 1720 | ``` 1721 | def make_sound(animal) 1722 | animal.sound 1723 | end 1724 | 1725 | class Dog 1726 | def sound 1727 | "Bark" 1728 | end 1729 | end 1730 | 1731 | class Cat 1732 | def sound 1733 | "Meow" 1734 | end 1735 | end 1736 | 1737 | make_sound(Dog.new) # => "Bark" 1738 | make_sound(Cat.new) # => "Meow" 1739 | ``` 1740 | make_sound doesnโt care whether the object is a Dog or Cat, as long as it responds to #sound. 1741 | 1742 | Benefits of Duck Typing: 1743 | 1744 | Flexible: No strict interfaces required 1745 | 1746 | Clean code: Less boilerplate 1747 | 1748 | Powerful metaprogramming 1749 | 1750 | #### How does Ruby handle method lookup and method resolution order (MRO)? 1751 | #### How does module_function work in Ruby? 1752 | #### What is the difference between public, private, and protected methods? 1753 | public (default): 1754 | 1755 | Methods are accessible from anywhere โ inside or outside the class. 1756 | 1757 | All instance methods are public by default unless specified otherwise. 1758 | 1759 | private: 1760 | 1761 | Can only be called within the context of self, and without an explicit receiver. 1762 | 1763 | Typically used for internal logic that shouldnโt be accessed externally. 1764 | 1765 | protected: 1766 | Can be called within the same class or its subclasses, even with an explicit receiver โ but only if the receiver is an instance of the same class. 1767 | 1768 | ``` 1769 | Summary: 1770 | 1771 | Modifier Access From Explicit Receiver Allowed? Use Case 1772 | public Anywhere โ Yes Normal API methods 1773 | private Within class โ No Internal helpers 1774 | protected Same class/subclass โ Yes (if same class) Comparisons, shared logic 1775 | ``` 1776 | #### What is the difference between class_variable, instance_variable, and global_variable? 1777 | 1778 | ``` 1779 | Summary: 1780 | Variable Type Prefix Scope Shared? Usage 1781 | Instance Variable @ Per object โ No Object state 1782 | Class Variable @@ Shared in class & subclasses โ Yes Global class-level count, config 1783 | Global Variable $ Everywhere in program โ Yes (global) Avoid unless absolutely necessary 1784 | ``` 1785 | #### What is monkey patching, and when should you avoid it? 1786 | #### What are refinements in Ruby? 1787 | #### How do you implement multiple inheritance in Ruby? 1788 | #### What is the difference between super and self? 1789 | #### How does define_method work in Ruby? 1790 | #### What is method_missing, and how can it be useful? 1791 | #### What is a Ruby block, and how is it different from a Proc? 1792 | #### What is the difference between tap, yield_self, and then in Ruby? 1793 | 1794 | ### Core Ruby Questions 1795 | #### How is memory management handled in Ruby? 1796 | #### Whatโs the difference between dup and clone in Ruby? 1797 | #### Explain the concept of object immutability in Ruby. 1798 | #### What is the difference between super and super()? 1799 | super: 1800 | 1801 | Passes all arguments that were passed to the current method to the superclass method automatically. 1802 | 1803 | If the superclass method accepts those arguments, it works as expected. 1804 | ``` 1805 | class Parent 1806 | def greet(name) 1807 | "Hello, #{name}" 1808 | end 1809 | end 1810 | 1811 | class Child < Parent 1812 | def greet(name) 1813 | super # passes `name` automatically 1814 | end 1815 | end 1816 | 1817 | Child.new.greet("Alice") # => "Hello, Alice" 1818 | ``` 1819 | 1820 | 1821 | super(): 1822 | 1823 | Passes no arguments at all to the superclass method. 1824 | 1825 | Use this when the superclass method does not expect arguments, or when you want to override without forwarding arguments. 1826 | ``` 1827 | class Parent 1828 | def greet 1829 | "Hello!" 1830 | end 1831 | end 1832 | 1833 | class Child < Parent 1834 | def greet(name) 1835 | super() + " I'm #{name}." 1836 | end 1837 | end 1838 | 1839 | Child.new.greet("Alice") # => "Hello! I'm Alice." 1840 | ``` 1841 | #### How does Rubyโs case statement work internally? Does it use == or ===? 1842 | 1843 | ### ๐งฉ OOP and Design Questions 1844 | #### What are the SOLID principles? Can you demonstrate one using Ruby? 1845 | #### Whatโs the difference between a class variable and a class instance variable? 1846 | #### When would you use method_missing vs define_method? 1847 | #### How do modules affect the method lookup chain in Ruby? 1848 | #### What is a mixin and when would you use it over inheritance? 1849 | 1850 | ### ๐งช Testing and Tooling 1851 | #### How would you test private methods in Ruby? Should you? 1852 | #### Explain how RSpec matchers work and how to write custom matchers. 1853 | #### Whatโs the difference between mocking and stubbing in tests? 1854 | #### How do you test a class that uses metaprogramming or dynamic behavior? 1855 | ### ๐ Enumerable and Functional Patterns 1856 | #### Whatโs the difference between map, collect, each_with_object, and reduce? 1857 | #### How would you reverse a linked list using only Ruby's Enumerable methods? 1858 | #### Explain lazy evaluation in Ruby with an example. 1859 | #### How would you implement your own version of zip or group_by? 1860 | 1861 | ### ๐งฌ Metaprogramming & DSLs 1862 | #### What are the risks of using eval in Ruby? 1863 | #### Can you write a DSL for a pizza builder? (e.g., Pizza.new.size(:large).toppings(:olives, :cheese)) 1864 | #### How does method_missing affect performance and debuggability? 1865 | #### When would you use class_eval vs define_singleton_method? 1866 | #### Can you override send or respond_to?? When might you do that? 1867 | 1868 | ### ๐น Concurrency and System Design 1869 | #### How would you handle thread safety in Ruby for shared data structures? 1870 | #### What are Fibers and how are they different from Threads? 1871 | #### Have you used Ractor in Ruby 3.x? How does it enable true parallelism? 1872 | #### Design an in-memory rate limiter in Ruby (e.g., max 10 requests per minute per user). 1873 | 1874 | ### ๐ก Debugging and Performance 1875 | #### How do you profile memory or CPU usage in a Ruby script? 1876 | #### Explain the concept of memoization. How would you implement it manually? 1877 | #### How do you reduce object allocation in a large loop? 1878 | #### When and why would you freeze an object in Ruby? 1879 | 1880 | ### ๐ Trick Questions / Gotchas 1881 | #### What will this return and why? 1882 | 1883 | ``` 1884 | def weird 1885 | begin 1886 | raise "Oops" 1887 | rescue 1888 | return "rescued" 1889 | ensure 1890 | return "ensured" 1891 | end 1892 | end 1893 | 1894 | puts weird # => ??? 1895 | ``` 1896 | Answer: "ensured" โ ensure always runs last and overrides the return. 1897 | 1898 | #### Whatโs the difference between ||= and or=? 1899 | #### Why might using Hash.new([]) cause unexpected behavior? 1900 | 1901 | ### โ Basic Ruby Questions 1902 | #### What are symbols in Ruby? How are they different from strings? 1903 | #### What are the different types of variables in Ruby (local, instance, class, global)? 1904 | #### What is the difference between ==, eql?, and equal?? 1905 | #### Explain the difference between puts, print, and p. 1906 | #### What is a block, and how is it different from a Proc or a lambda? 1907 | #### What is the use of the self keyword in Ruby? 1908 | #### What is the difference between include and extend in modules? 1909 | #### How does garbage collection work in Ruby? 1910 | #### Whatโs the difference between nil, false, and undefined variable in Ruby? 1911 | 1912 | ### ๐ Intermediate Ruby Questions 1913 | #### Explain how Ruby handles method overloading or default arguments. 1914 | #### What is duck typing in Ruby? Give an example. 1915 | #### How does Ruby handle inheritance and method resolution? 1916 | #### What are singleton methods? When would you use them? 1917 | #### Whatโs the difference between Proc.new, lambda, and the -> syntax? 1918 | #### What are refinements in Ruby? Why would you use them instead of monkey-patching? 1919 | #### What are the scopes of constants in Ruby (e.g., ::, nesting)? 1920 | #### Explain what mixins are. How are they implemented in Ruby? 1921 | #### How do you define and use custom enumerators in Ruby? 1922 | 1923 | ### ๐ฌ Advanced Ruby Questions 1924 | #### How would you implement your own version of each, map, or select without using Ruby's built-in methods? 1925 | #### What are some metaprogramming techniques in Ruby? Show an example using define_method or method_missing. 1926 | #### What is the difference between class variables (@@) and class instance variables (@ on the class)? 1927 | #### How does Rubyโs method_missing work, and what are the risks? 1928 | #### Whatโs the difference between eager and lazy enumerators in Ruby? 1929 | #### How do fibers work in Ruby? What are they useful for? 1930 | #### How would you optimize memory usage in a Ruby app that processes millions of records? 1931 | #### What is the Global Interpreter Lock (GIL) in Ruby MRI? How does it affect threading? 1932 | #### How would you implement a Domain-Specific Language (DSL) in Ruby? 1933 | 1934 | 1935 | ### ๐ Live Coding Challenge Questions 1936 | #### Implement a caching mechanism in Rails without using built-in Rails caching. 1937 | #### Optimize a slow SQL query in a Rails application. 1938 | #### Write a background job that sends scheduled emails using Sidekiq. 1939 | #### Write a Rails service object that processes and validates a CSV file upload. 1940 | #### Refactor a Rails controller that has too many instance variables. 1941 | #### Write a Rails middleware that logs request details before passing it to the controller. 1942 | #### Write a method that finds all duplicate users based on their email in ActiveRecord. 1943 | #### Design a system to throttle API requests in Rails without using third-party gems. 1944 | #### Implement an authentication system without Devise in Rails. 1945 | #### Write a custom ActiveRecord scope that returns all users who havenโt logged in for 30 days. 1946 | 1947 | 1948 | 1949 | ### ๐๐ป๐๐ฒ๐ฟ๐บ๐ฒ๐ฑ๐ถ๐ฎ๐๐ฒ ๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐ -: 1950 | #### 1. How do you handle exceptions and errors in Rails? What strategies do you use for logging and notification? 1951 | #### 2. How do you approach database modeling in Rails? What considerations do you take for efficient data retrieval and storage? 1952 | #### 3. How do you use Rails migrations to manage database schema changes? What are some best practices for writing migrations? 1953 | #### 4. What caching mechanisms does Rails offer (fragment, action, and page caching), and when would you use each? 1954 | #### 5. How do you design RESTful APIs in Rails? What considerations do you take for API versioning and security? 1955 | #### 6. How do you use service objects to encapsulate business logic in Rails? What benefits do they offer? 1956 | #### 7. How do you define nested routes in Rails? What are some advanced routing techniques such as shallow routes? 1957 | #### 8. Explain polymorphic associations in Rails. When would you choose them over standard associations? 1958 | 1959 | ### ๐๐ฑ๐๐ฎ๐ป๐ฐ๐ฒ๐ฑ ๐ค๐๐ฒ๐๐๐ถ๐ผ๐ป๐ -: 1960 | 1961 | #### 9. How do you tackle the N+1 query problem in Rails? What tools or techniques do you use to optimize queries? 1962 | #### 10. How do you handle database transactions in Rails? What steps do you take to optimize database performance through indexing and query tuning? 1963 | #### 11. How would you manage caching in a high-traffic, distributed Rails environment? Discuss the use of fragment, action, and page caching. 1964 | #### 12. Discuss Railsโ built-in security features. How do you mitigate risks like CSRF, XSS, and SQL injection? 1965 | #### 13. How do you design, secure, and version API endpoints in Rails? What are your thoughts on REST vs. GraphQL? 1966 | #### 14. What architectural patterns have you implemented to ensure a Rails application scales? Discuss multi-tenancy or micro-services if applicable. 1967 | #### 15. How do you address concurrency in Rails? Have you encountered and solved challenges with multi-threading? 1968 | #### 16. What is sharding, and how can it be implemented in Rails to optimise data access for large datasets? 1969 | #### 17. What testing frameworks and strategies (unit, integration, performance) do you rely on in Rails? How do you ensure comprehensive test coverage? 1970 | #### 18. Describe your experience implementing real-time features using Action Cable. What challenges did you encounter? 1971 | #### 19. How do you approach refactoring a large, legacy Rails codebase without causing disruptions? What tools or methodologies do you use? 1972 | #### 20. Have you worked with Rails 6/7 features such as ActionMailbox, ActionText, or Hotwire? How have they influenced your development process? 1973 | #### 21. How do you use service objects or decorators to encapsulate business logic? Share your experiences with Rubyโs meta-programming capabilities. 1974 | #### 22. What role does Rack play in Rails? Have you ever built custom middleware? If so, how? 1975 | #### 23. How do you analyze and optimize database queries in Rails? What tools do you use to identify performance bottlenecks? 1976 | 1977 | 1978 | #### How does Rails handle database connection pooling? 1979 | #### Explain the difference between joins, includes, preload, and eager_load. 1980 | #### How does Railsโ autoloading work? What changed in Zeitwerk? 1981 | #### What are ActiveRecord callbacks? When should you avoid them? 1982 | #### What are ActiveSupport Concerns? How do they differ from modules? 1983 | #### What is the purpose of Rails engines? When would you use one? 1984 | #### How does Rails handle has_many :through vs. has_and_belongs_to_many? 1985 | #### Whatโs the difference between belongs_to and has_one? 1986 | #### What are Rails observers, and why are they deprecated? 1987 | #### How does the Rails asset pipeline work? 1988 | #### What are different ways to manage configurations in Rails (secrets.yml, credentials.yml.enc, ENV variables)? 1989 | #### What is the difference between dependent: :destroy, dependent: :delete_all, and dependent: :nullify? 1990 | #### How do you implement state machines in Rails (e.g., AASM, workflow gem)? 1991 | #### Whatโs the difference between rake and rails commands? 1992 | #### What are concerns, and when should they be used? 1993 | 1994 | 1995 | 1996 | 1997 | 1998 | ### ๐ง Problem 1: Dynamic Method Generation (Metaprogramming) 1999 | Challenge: Write a class CurrencyConverter that dynamically defines methods like to_usd, to_eur, to_gbp, and converts from a base amount in cents (as integer) to those currencies using given exchange rates. 2000 | 2001 | ### ๐ง Problem 2: Lazy Prime Generator (Enumerators) 2002 | Challenge: Write a method lazy_primes(n) that lazily generates the first n prime numbers using Ruby's enumerators. 2003 | 2004 | ### ๐ง Problem 3: Safe Concurrency with Threads 2005 | Challenge: Create a counter that increments safely from multiple threads (simulate 100 threads incrementing a shared counter 1000 times each). Use a mutex to avoid race conditions. 2006 | 2007 | 2008 | ### ๐ Intermediate Rails Questions 2009 | #### 1. Handling Exceptions & Logging 2010 | Use rescue_from in controllers to handle specific exceptions: 2011 | ``` 2012 | class ApplicationController < ActionController::Base 2013 | rescue_from ActiveRecord::RecordNotFound, with: :not_found 2014 | rescue_from StandardError, with: :handle_error 2015 | 2016 | private 2017 | 2018 | def not_found 2019 | render json: { error: "Record not found" }, status: :not_found 2020 | end 2021 | 2022 | def handle_error(exception) 2023 | Rails.logger.error(exception.message) 2024 | render json: { error: "Something went wrong" }, status: :internal_server_error 2025 | end 2026 | end 2027 | ``` 2028 | Use Rollbar, Sentry, or Bugsnag for error notifications. 2029 | 2030 | #### 2. Database Modeling Considerations 2031 | Normalize data when needed (e.g., extract a tags table if storing repeated text). 2032 | Use indexes for faster lookups (add_index :users, :email, unique: true). 2033 | Optimize eager loading to avoid N+1 queries. 2034 | 2035 | #### 3. Managing Migrations 2036 | Keep migrations idempotent (avoid destructive changes in production). 2037 | 2038 | Use change method over up and down unless a complex rollback is needed. 2039 | Example: 2040 | ``` 2041 | class AddIndexToUsers < ActiveRecord::Migration[7.0] 2042 | def change 2043 | add_index :users, :email, unique: true 2044 | end 2045 | end 2046 | ``` 2047 | #### 4. Caching Mechanisms 2048 | Page Caching: Stores full HTML response (caches_page :index). 2049 | 2050 | Action Caching: Caches entire actions but checks authentication. 2051 | 2052 | Fragment Caching: Caches parts of a view: 2053 | ``` 2054 | <% cache @user do %> 2055 | <%= render @user.profile %> 2056 | <% end %> 2057 | ``` 2058 | SQL Query Caching: Enabled by default in Rails. 2059 | 2060 | #### 5. RESTful API Design 2061 | Versioning: /api/v1/users 2062 | Security Considerations: 2063 | Use JWT or OAuth2 for authentication. 2064 | 2065 | Add rate limiting with rack-attack. 2066 | 2067 | #### 6. Service Objects for Business Logic 2068 | Service objects keep controllers clean: 2069 | ``` 2070 | class UserCreator 2071 | def initialize(user_params) 2072 | @user_params = user_params 2073 | end 2074 | 2075 | def call 2076 | User.create(@user_params) 2077 | end 2078 | end 2079 | ``` 2080 | Benefits: Reusable, testable, and scalable. 2081 | 2082 | #### 7. Nested Routes & Advanced Routing 2083 | ``` 2084 | resources :authors do 2085 | resources :books, only: [:index, :show] 2086 | end 2087 | ``` 2088 | Use shallow routes to avoid deep nesting: 2089 | ``` 2090 | resources :books, shallow: true do 2091 | resources :reviews 2092 | end 2093 | ``` 2094 | 8. Polymorphic Associations 2095 | Use when a model can belong to multiple models: 2096 | ``` 2097 | class Comment < ApplicationRecord 2098 | belongs_to :commentable, polymorphic: true 2099 | end 2100 | Example: 2101 | 2102 | class Post < ApplicationRecord 2103 | has_many :comments, as: :commentable 2104 | end 2105 | 2106 | class Video < ApplicationRecord 2107 | has_many :comments, as: :commentable 2108 | end 2109 | ``` 2110 | 2111 | #### 9. N+1 Query Problem & Optimization 2112 | Use includes or preload: 2113 | ``` 2114 | Post.includes(:comments).each do |post| 2115 | puts post.comments.count 2116 | end 2117 | ``` 2118 | Use bullet gem to detect N+1. 2119 | 2120 | 10. Database Transactions & Performance 2121 | Wrap operations in transactions: 2122 | ``` 2123 | User.transaction do 2124 | user.update!(balance: user.balance - 100) 2125 | Payment.create!(user: user, amount: 100) 2126 | end 2127 | Indexing: 2128 | add_index :orders, :user_id 2129 | ``` 2130 | #### 11. Caching in a Distributed Rails App 2131 | Use Redis as a caching layer. 2132 | 2133 | Use low-level caching with Rails.cache.fetch. 2134 | 2135 | #### 12. Rails Security 2136 | CSRF Protection: protect_from_forgery with: :exception 2137 | 2138 | XSS Protection: Use sanitize for user input. 2139 | 2140 | SQL Injection Prevention: Always use ActiveRecordโs query methods: 2141 | 2142 | User.where("email = ?", params[:email]) 2143 | 13. REST vs. GraphQL 2144 | REST: Good for simple CRUD APIs. 2145 | 2146 | GraphQL: Good for complex frontends needing flexible data fetching. 2147 | 2148 | #### 14. Scaling Rails 2149 | Use read replicas and database sharding. 2150 | 2151 | Move long tasks to background jobs. 2152 | 2153 | #### 15. Handling Concurrency 2154 | Use Redis locks to prevent race conditions. 2155 | 2156 | #### 16. Sharding in Rails 2157 | Use octopus gem or Rails 6 multiple databases feature. 2158 | 2159 | #### 17. Rails Testing 2160 | Unit tests: RSpec or Minitest 2161 | 2162 | Integration tests: Capybara 2163 | 2164 | Performance testing: Benchmark 2165 | 2166 | #### 18. Real-Time Features (ActionCable) 2167 | ``` 2168 | class ChatChannel < ApplicationCable::Channel 2169 | def subscribed 2170 | stream_from "chat_#{params[:room]}" 2171 | end 2172 | end 2173 | ``` 2174 | Challenges: Scaling with Redis, handling connections. 2175 | 2176 | #### 19. Refactoring Legacy Rails Code 2177 | Use rubocop for code consistency. 2178 | 2179 | Gradually introduce service objects. 2180 | 2181 | #### 20. Rails 6/7 Features 2182 | Hotwire (Turbo & Stimulus) 2183 | 2184 | ActionText (Rich Text ing) 2185 | 2186 | ActionMailbox (Incoming Emails Handling) 2187 | 2188 | ### Ruby-Specific Questions 2189 | #### 1. Rack & Middleware 2190 | Rack is a lightweight interface between web servers and Ruby frameworks. 2191 | ``` 2192 | Custom Middleware: 2193 | 2194 | class LoggerMiddleware 2195 | def initialize(app) 2196 | @app = app 2197 | end 2198 | 2199 | def call(env) 2200 | Rails.logger.info "Request received: #{env['PATH_INFO']}" 2201 | @app.call(env) 2202 | end 2203 | end 2204 | ``` 2205 | #### 2. N+1 Query 2206 | Solved using includes, preload, or eager_load. 2207 | 2208 | #### 3. Concerns in Rails 2209 | Use concerns for shared logic: 2210 | ``` 2211 | module Taggable 2212 | extend ActiveSupport::Concern 2213 | 2214 | included do 2215 | has_many :tags 2216 | end 2217 | end 2218 | ``` 2219 | #### 4. HABTM vs HMT 2220 | HABTM: Direct many-to-many without extra fields. 2221 | 2222 | HMT: Uses a join model for additional attributes. 2223 | 2224 | #### 5. Class vs. Instance Variables 2225 | ``` 2226 | class User 2227 | @@class_var = "class var" 2228 | @instance_var = "instance var" 2229 | end 2230 | ``` 2231 | #### 6. Mutable vs. Immutable in Ruby 2232 | Strings are mutable, Numbers & Booleans are immutable. 2233 | 2234 | #### 7. Ruby GC (Garbage Collection) 2235 | Ruby uses Mark-and-Sweep Garbage Collection. 2236 | 2237 | #### 8. include vs extend 2238 | include adds instance methods. 2239 | 2240 | extend adds class methods. 2241 | 2242 | #### 9. Threads vs. Fibers 2243 | Threads: Pre-emptive (run in parallel). 2244 | 2245 | Fibers: Cooperative (manual yielding). 2246 | 2247 | #### 10. Proc vs. Lambda 2248 | Lambdas check arity (number of arguments), Procs donโt. 2249 | 2250 | ### Final Questions 2251 | #### Mass Assignment & Protection: 2252 | 2253 | 2254 | params.require(:user).permit(:name, :email) 2255 | CSRF Protection: 2256 | 2257 | 2258 | protect_from_forgery with: :exception 2259 | ActiveRecord Callbacks: before_save, after_commit, etc. 2260 | 2261 | Convention Over Configuration: Railsโ opinionated design. 2262 | 2263 | Difference Between save and save!: save! raises an exception on failure. 2264 | 2265 | Want Mock Interview Practice? ๐ฅ 2266 | I can generate Rails coding challenges or mock system design questions! ๐ 2267 | 2268 | 2269 | 2270 | 2271 | 2272 | 2273 | 2274 | #### Please share the type of associations in rails and how they are formed? 2275 | ๐ Associations in Rails and How They Are Formed 2276 | Associations in Rails define relationships between models, allowing efficient data retrieval and manipulation. 2277 | 2278 | 1. belongs_to Association 2279 | ``` 2280 | One-to-One or Many-to-One relationship 2281 | ``` 2282 | The child model holds the foreign key. 2283 | 2284 | Example: A Book belongs to an Author 2285 | ``` 2286 | class Book < ApplicationRecord 2287 | belongs_to :author 2288 | end 2289 | ``` 2290 | ``` 2291 | class Author < ApplicationRecord 2292 | has_many :books 2293 | end 2294 | ``` 2295 | The books table must have an author_id column. 2296 | 2297 | Foreign key: author_id in books. 2298 | 2299 | ``` 2300 | class AddAuthorToBooks < ActiveRecord::Migration[7.0] 2301 | def change 2302 | add_reference :books, :author, foreign_key: true 2303 | end 2304 | end 2305 | ``` 2306 | #### 2. has_one Association 2307 | One-to-One relationship 2308 | 2309 | The parent model has one associated record. 2310 | 2311 | Example: A User has one Profile 2312 | ``` 2313 | 2314 | class User < ApplicationRecord 2315 | has_one :profile 2316 | end 2317 | 2318 | class Profile < ApplicationRecord 2319 | belongs_to :user 2320 | end 2321 | Foreign key: user_id in profiles. 2322 | 2323 | 2324 | class AddUserToProfiles < ActiveRecord::Migration[7.0] 2325 | def change 2326 | add_reference :profiles, :user, foreign_key: true 2327 | end 2328 | end 2329 | ``` 2330 | 2331 | #### 3. has_many Association 2332 | One-to-Many relationship 2333 | 2334 | A record has many related records. 2335 | ``` 2336 | Example: An Author has many Books 2337 | 2338 | class Author < ApplicationRecord 2339 | has_many :books 2340 | end 2341 | 2342 | class Book < ApplicationRecord 2343 | belongs_to :author 2344 | end 2345 | Foreign key: author_id in books. 2346 | ``` 2347 | #### 4. has_many :through Association 2348 | Many-to-Many relationship with a join table containing additional attributes. 2349 | 2350 | Example: Doctor has many Patients through Appointments 2351 | ``` 2352 | class Doctor < ApplicationRecord 2353 | has_many :appointments 2354 | has_many :patients, through: :appointments 2355 | end 2356 | 2357 | class Patient < ApplicationRecord 2358 | has_many :appointments 2359 | has_many :doctors, through: :appointments 2360 | end 2361 | 2362 | class Appointment < ApplicationRecord 2363 | belongs_to :doctor 2364 | belongs_to :patient 2365 | end 2366 | Join table: appointments (with doctor_id and patient_id). 2367 | 2368 | class CreateAppointments < ActiveRecord::Migration[7.0] 2369 | def change 2370 | create_table :appointments do |t| 2371 | t.references :doctor, foreign_key: true 2372 | t.references :patient, foreign_key: true 2373 | t.datetime :appointment_date 2374 | t.timestamps 2375 | end 2376 | end 2377 | end 2378 | ``` 2379 | #### 5. has_and_belongs_to_many (HABTM) 2380 | Direct Many-to-Many relationship without additional attributes. 2381 | 2382 | Example: Students and Courses 2383 | ``` 2384 | class Student < ApplicationRecord 2385 | has_and_belongs_to_many :courses 2386 | end 2387 | 2388 | class Course < ApplicationRecord 2389 | has_and_belongs_to_many :students 2390 | end 2391 | Requires a join table (courses_students) with no extra columns. 2392 | 2393 | class CreateCoursesStudentsJoinTable < ActiveRecord::Migration[7.0] 2394 | def change 2395 | create_join_table :courses, :students do |t| 2396 | t.index :course_id 2397 | t.index :student_id 2398 | end 2399 | end 2400 | end 2401 | ``` 2402 | ๐ HABTM vs. has_many :through 2403 | 2404 | Use has_many :through if the join table needs extra columns (e.g., appointments.date). 2405 | 2406 | Use HABTM if the join table is purely relational. 2407 | 2408 | #### 6. polymorphic Association 2409 | A model can belong to multiple other models using a single association. 2410 | 2411 | Example: A Comment can belong to both Post and Video 2412 | ``` 2413 | class Comment < ApplicationRecord 2414 | belongs_to :commentable, polymorphic: true 2415 | end 2416 | 2417 | class Post < ApplicationRecord 2418 | has_many :comments, as: :commentable 2419 | end 2420 | 2421 | class Video < ApplicationRecord 2422 | has_many :comments, as: :commentable 2423 | end 2424 | ``` 2425 | The comments table has: 2426 | 2427 | commentable_type (stores "Post" or "Video") 2428 | 2429 | commentable_id (stores the related recordโs ID) 2430 | 2431 | ``` 2432 | class CreateComments < ActiveRecord::Migration[7.0] 2433 | def change 2434 | create_table :comments do |t| 2435 | t.text :body 2436 | t.references :commentable, polymorphic: true, index: true 2437 | t.timestamps 2438 | end 2439 | end 2440 | end 2441 | ``` 2442 | #### 7. self-join (Recursive Association) 2443 | A model associates with itself. 2444 | 2445 | Example: Employees reporting to a Manager 2446 | ``` 2447 | class Employee < ApplicationRecord 2448 | belongs_to :manager, class_name: "Employee", optional: true 2449 | has_many :subordinates, class_name: "Employee", foreign_key: "manager_id" 2450 | end 2451 | ``` 2452 | Foreign key: manager_id in employees. 2453 | ``` 2454 | class AddManagerToEmployees < ActiveRecord::Migration[7.0] 2455 | def change 2456 | add_reference :employees, :manager, foreign_key: { to_table: :employees } 2457 | end 2458 | end 2459 | ``` 2460 | #### Summary Table 2461 | ``` 2462 | Association Type Description Example 2463 | belongs_to Child model holds foreign key Book belongs_to Author 2464 | has_one One-to-one User has_one Profile 2465 | has_many One-to-many Author has_many Books 2466 | has_many :through Many-to-many with join model Doctor has_many Patients through Appointments 2467 | has_and_belongs_to_many (HABTM) Many-to-many without extra fields Students and Courses 2468 | polymorphic Model belongs to multiple types Comment belongs_to Post or Video 2469 | self-join Model relates to itself Employee belongs_to Manager 2470 | ``` 2471 | 2472 | 2473 | --------------------------------------------------------------------------------