Exciting 🔮 features of Ruby Programming Language

Ruby is a dynamic, object-oriented programming language designed for simplicity and productivity. Here are some of its most exciting features:

1. Everything is an Object

In Ruby, every value is an object, even primitive types like integers or nil. This allows you to call methods directly on literals.
Example:

5.times { puts "Ruby!" }      # 5 is an Integer object with a `times` method
3.14.floor                    # => 3 (Float object method)
true.to_s                     # => "true" (Boolean → String)
nil.nil?                      # => true (Method to check if object is nil)

2. Elegant and Readable Syntax

Ruby’s syntax prioritizes developer happiness. Parentheses and semicolons are often optional.
Example:

# A method to greet a user (parentheses optional)
def greet(name = "Guest")
  puts "Hello, #{name.capitalize}!"
end

greet "alice"  # Output: "Hello, Alice!"

3. Blocks and Iterators

Ruby uses blocks (anonymous functions) to create powerful iterators. Use {} for single-line blocks or do...end for multi-line.
Example:

# Multiply even numbers by 2
numbers = [1, 2, 3, 4]
result = numbers.select do |n|
  n.even?
end.map { |n| n * 2 }

puts result # => [4, 8]

4. Mixins via Modules

Modules let you share behavior across classes without inheritance.
Example:

module Loggable
  def log(message)
    puts "[LOG] #{message}"
  end
end

class User
  include Loggable  # Mix in the module
end

user = User.new
user.log("New user created!") # => [LOG] New user created!

5. Metaprogramming

Ruby can generate code at runtime. For example, dynamically define methods.
Example:

class Person
  # Define methods like name= and name dynamically
  attr_accessor :name, :age
end

person = Person.new
person.name = "Alice"
puts person.name # => "Alice"

6. Duck Typing

Focus on behavior, not type. If it “quacks like a duck,” treat it as a duck.
Example:

def print_length(obj)
  obj.length  # Works for strings, arrays, or any object with a `length` method
end

puts print_length("Hello")  # => 5
puts print_length([1, 2, 3]) # => 3

7. Symbols

Symbols (:symbol) are lightweight, immutable strings used as identifiers.
Example:

# Symbols as hash keys (faster than strings)
config = { :theme => "dark", :font => "Arial" }
puts config[:theme] # => "dark"

# Modern syntax (Ruby 2.0+):
config = { theme: "dark", font: "Arial" }

8. Ruby Set

A set is a Ruby class that helps you create a list of unique items. A set is a class that stores items like an array. But with some special attributes that make it 10x faster in specific situations! All the items in a set are guaranteed to be unique.

What’s the difference between a set & an array?
A set has no direct access to elements:

> seen[3]
(irb):19:in '<main>': undefined method '[]' for #<Set:0x000000012fc34058> (NoMethodError)

But a set can be converted into an array any time you need:

> seen.to_a
=> [4, 8, 9, 90]
> seen.to_a[3]
=> 90

Set: Fast lookup times (with include?)

If you need these then a set will give you a good performance boost, and you won’t have to be calling uniq on your array every time you want unique elements.
Reference: https://www.rubyguides.com/2018/08/ruby-set-class/

Superset & Subset

A superset is a set that contains all the elements of another set.

Set.new(10..40) >= Set.new(20..30)

subset is a set that is made from parts of another set:

Set.new(25..27) <= Set.new(20..30)


Example:

> seen = Set.new
=> #<Set: {}>
> seen.add(4)
=> #<Set: {4}>
> seen.add(4)
=> #<Set: {4}>
> seen.add(8)
=> #<Set: {4, 8}>
> seen.add(9)
=> #<Set: {4, 8, 9}>
> seen.add(90)
=> #<Set: {4, 8, 9, 90}>
> seen.add(4)
=> #<Set: {4, 8, 9, 90}>

> seen.to_a
=> [4, 8, 9, 90]
> seen.to_a[3]
=> 90
> seen | (1..10) # set union operator
=> #<Set: {4, 8, 9, 90, 1, 2, 3, 5, 6, 7, 10}>

> seen =  seen | (1..10)
=> #<Set: {4, 8, 9, 90, 1, 2, 3, 5, 6, 7, 10}>
> seen - (3..4)  # set difference operator
=> #<Set: {8, 9, 90, 1, 2, 5, 6, 7, 10}>

set1 = Set.new(1..5)
set2 = Set.new(4..8) 
> set1 & set2  # set intersection operator
=> #<Set: {4, 5}>

9. Rich Standard Library

Ruby’s Enumerable module adds powerful methods to collections.
Example:

# Group numbers by even/odd
numbers = [1, 2, 3, 4]
grouped = numbers.group_by { |n| n.even? ? :even : :odd }
puts grouped # => { :odd => [1, 3], :even => [2, 4] }

10. Convention over Configuration

Ruby minimizes boilerplate code with conventions.
Example:

class Book
  attr_accessor :title, :author  # Auto-generates getters/setters
  def initialize(title, author)
    @title = title
    @author = author
  end
end

book = Book.new("Ruby 101", "Alice")
puts book.title # => "Ruby 101"

11. Method Naming Conventions

Method suffixes clarify intent:

  • ? for boolean returns.
  • ! for dangerous/mutating methods.
    Example:
str = "ruby"
puts str.capitalize! # => "Ruby" (mutates the string)
puts str.empty?      # => false

12. Functional Programming Features

Ruby supports Procs (objects holding code) and lambdas.
Example:

# Lambda example
double = lambda { |x| x * 2 }
puts [1, 2, 3].map(&double) # => [2, 4, 6]

# Proc example
greet = Proc.new { |name| puts "Hello, #{name}!" }
greet.call("Bob") # => "Hello, Bob!"

13. IRB (Interactive Ruby)

Test code snippets instantly in the REPL:

$ irb
irb> [1, 2, 3].sum # => 6
irb> Time.now.year  # => 2023

14. Garbage Collection

Automatic memory management:

# No need to free memory manually
1000.times { String.new("temp") } # GC cleans up unused objects

15. Community and Ecosystem

RubyGems (packages) like:

  • Rails: Full-stack web framework.
  • RSpec: Testing framework.
  • Sinatra: Lightweight web server.

Install a gem:

gem install rails

16. Error Handling

Use begin/rescue for exceptions:

begin
  puts 10 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}" # => "Error: divided by 0"
end

17. Open Classes

Modify existing classes (use carefully!):

class String
  def reverse_and_upcase
    self.reverse.upcase
  end
end

puts "hello".reverse_and_upcase # => "OLLEH"

18. Reflection

Inspect objects at runtime:

class Dog
  def bark
    puts "Woof!"
  end
end

dog = Dog.new
puts dog.respond_to?(:bark) # => true
puts Dog.instance_methods   # List all methods

Ruby’s design philosophy emphasizes developer productivity and joy. These features make it ideal for rapid prototyping, web development (with Rails), scripting, and more.

Enjoy Ruby! 🚀

Mastering 🎓 Ruby’s Core Concepts: A Deep Dive into Method Magic 🪄, Modules, Mixins and Meta-Programming

Introduction:

Ruby, with its elegant syntax and dynamic nature, empowers developers to write expressive and flexible code. But beneath its simplicity lie powerful—and sometimes misunderstood – concepts like modules, mixins, and meta-programming that define the language’s true potential. Whether you’re wrestling with method lookup order, curious about how method_missing enables magic-like behaviour, or want to leverage eigen classes to bend Ruby’s object model to your will, understanding these fundamentals is key to writing clean, efficient, and maintainable code.

In this guide, we’ll unravel Ruby 3.4’s threading model, its Global Interpreter Lock (GIL) nuances, and how Ruby on Rails 8 leverages concurrency for scalable web applications. We’ll unpack foundational concepts like the Comparable module, Hash collections, and functional programming constructs such as lambdas and Procs. Additionally, we’ll demystify Ruby’s interpreted nature, contrast compilers with interpreters, and highlight modern GC advancements that optimize memory management. Through practical examples, we’ll also examine Ruby’s exception handling, the purpose of respond_to?, Ruby’s core mechanics, from modules and classes to the secrets of the ancestor chain, equipping you with the knowledge to transform from a Ruby user to a Ruby architect. Let’s dive in! 🔍


Why Call It “Magic”?

  • Ruby lets you break conventional rules and invent your own behavior.
  • It feels like “sorcery” compared to statically-typed languages.
  • Frameworks like Rails rely heavily on this (e.g., has_manybefore_action).
  1. method_missing
    • Ruby’s way of saying, “If a method doesn’t exist, call this instead!”
    • Lets you handle undefined methods dynamically (e.g., building DSLs or proxies).
  2. Dynamic Method Creation (define_methodsend)
    • Define methods on the fly based on conditions or data.
    • Example: Automatically generating getters/setters without attr_accessor.
  3. Ghost Methods & respond_to_missing?
    • Methods that “don’t exist” syntactically but behave like they do.
    • Makes objects infinitely adaptable (e.g., Rails’ find_by_* methods).
  4. Singleton Methods (Eigenclass Wizardry)
    • Attaching methods to individual objects (even classes!) at runtime.
    • Example: Adding a custom method to just one string:
str = "hello"
def str.shout; upcase + "!"; end
str.shout # => "HELLO!"

5. Meta-Programming (Code that Writes Code)
* Using evalclass_eval, or instance_eval to modify behaviour dynamically.

Analogy:
If regular methods are “tools,” Ruby’s method magic is like a wand—you can conjure new tools out of thin air!

1. Modules, Classes, and Singleton Methods

  • Modules: Namespaces or mixins. Cannot be instantiated. Use include/extend to add methods.
  • Classes: Inherit via <, instantiated with new. Single inheritance only.
  • Singleton Methods: Methods defined on a single object (e.g., class methods are singleton methods of the class object).
  obj = "hello"
  def obj.custom_method; end # Singleton method for `obj`

2. include, extend, and prepend

  • include: Adds a module’s instance methods to a class as instance methods.
  module M; def foo; end; end
  class C; include M; end
  C.new.foo # => works
  • extend: Adds a module’s methods as class methods (or to an object’s singleton class).
  class C; extend M; end
  C.foo # => works
  • prepend: Inserts the module before the class in the method lookup chain, overriding class methods.
  class C; prepend M; end
  C.ancestors # => [M, C, ...]

3. Inheritance

  • Single inheritance: class Sub < Super.
  • Ancestor chain includes superclasses and modules (via include/prepend).
  class A; end
  class B < A; end
  B.ancestors # => [B, A, Object, ...]

4. Mixins

  • Ruby’s way of achieving multiple inheritance. Include modules to add instance methods.
  module Enumerable
    def map; ...; end # Requires `each` to be defined
  end
  class MyList
    include Enumerable
    def each; ...; end
  end

5. Meta-Programming with Variables

  • Instance Variables:
  obj.instance_variable_get(:@var)
  obj.instance_variable_set(:@var, 42)
  • Class Variables:
  MyClass.class_variable_set(:@@count, 0)
  MyClass.class_variable_get(:@@count)
  • Use define_method or eval for dynamic method creation:
  class MyClass
    [:a, :b].each { |m| define_method(m) { ... } }
  end

6. Eigenclass (Singleton Class)

  • Hidden class where singleton methods live. Accessed via singleton_class or class << obj.
  obj = Object.new
  eigenclass = class << obj; self; end
  eigenclass.define_method(:foo) { ... }
  • Class methods are stored in the class’s eigenclass.

7. Ancestors (Method Lookup)

  • Order: Eigenclass → prepended modules → class → included modules → superclass.
  class C; include M; prepend P; end
  C.ancestors # => [P, C, M, Object, ...]

8. method_missing

  • Called when a method is not found. Override for dynamic behavior.
  class Proxy
    def method_missing(method, *args)
      # Handle unknown methods here
    end
  end

9. String Interpolation

  • Embed code in #{} within double-quoted strings or symbols:
  name = "Alice"
  puts "Hello, #{name.upcase}!" # => "Hello, ALICE!"
  • Single quotes ('') disable interpolation.

10. Threading in Ruby 3.4 and Ruby on Rails 8

Does Ruby 3.4 support threads?
Yes, Ruby 3.4 supports threads via its native Thread class. However, due to the Global Interpreter Lock (GIL) in MRI (Matz’s Ruby Interpreter), Ruby threads are concurrent but not parallel for CPU-bound tasks. I/O-bound tasks (e.g., HTTP requests, file operations) can still benefit from threading as the GIL is released during I/O waits.

How to do threading in Ruby:

threads = []
3.times do |i|
  threads << Thread.new { puts "Thread #{i} running" }
end
threads.each(&:join) # Wait for all threads to finish

In Ruby on Rails 8:

  • Use threading for background tasks, API calls, or parallel processing.
  • Ensure thread safety: Avoid shared mutable state; use mutexes or thread-safe data structures.
  • Rails automatically manages database connection pools for threads.
  • Example in a controller:
  def parallel_requests
    threads = [fetch_data, process_images]
    results = threads.map(&:value)
    render json: results
  end

  private

  def fetch_data
    Thread.new { ExternalService.get_data }
  end

11. The Comparable Module

Mix in Comparable to add comparison methods (<, >, <=, >=, ==, between?) to a class. Define <=> (spaceship operator) to compare instances:

class Person
  include Comparable
  attr_reader :age

  def initialize(age)
    @age = age
  end

  def <=>(other)
    age <=> other.age
  end
end

alice = Person.new(30)
bob = Person.new(25)
alice > bob # => true

12. Why Ruby is interpreted?

Compiler vs. Interpreter
CompilerInterpreter
Translates entire code upfront.Translates and executes line-by-line.
Faster execution.Slower execution.
Harder to debug.Easier to debug.
Examples: C++, Rust.Examples: Python, Ruby.

Why Ruby is interpreted?
Ruby prioritizes developer productivity and dynamic features (e.g., metaprogramming). MRI uses an interpreter, but JRuby (JVM) and TruffleRuby use JIT compilation.

Which is better?

  • Compiler: Better for performance-critical applications.
  • Interpreter: Better for rapid development and scripting.

13. respond_to? in Ruby

Checks if an object can respond to a method:

str = "hello"
str.respond_to?(:upcase) # => true

Other Languages:

  • Python: hasattr(obj, 'method')
  • JavaScript: 'method' in obj
  • Java/C#: No direct equivalent (static typing avoids runtime checks).

14. Ruby Hash

A key-value collection:

user = { name: "Alice", age: 30 }

Advantages:

  • Fast O(1) average lookup.
  • Flexible keys (symbols, strings, objects).
  • Ordered in Ruby 1.9+.

Use Cases:

  • Configuration settings.
  • Caching (e.g., Rails.cache).
  • Grouping data (e.g., group_by).

15. Lambdas and Procs

Lambda (strict argument check, returns from itself):

lambda = ->(x, y) { x + y }
lambda.call(2, 3) # => 5

Proc (flexible arguments, returns from enclosing method):

def test
  proc = Proc.new { return "Exiting" }
  proc.call
  "Never reached"
end
test # => "Exiting"

Use Cases:

  • Passing behavior to methods (e.g., map(&:method)).
  • Callbacks and event handling.

16. Ruby 3.4 Garbage Collector (GC)

Improvements:

  • Generational GC: Separates objects into young (short-lived) and old (long-lived) generations for faster collection.
  • Incremental GC: Reduces pause times by interleaving GC with program execution.
  • Compaction: Reduces memory fragmentation (introduced in Ruby 2.7).

How It Works:

  1. Mark Phase: Traces reachable objects.
  2. Sweep Phase: Frees memory of unmarked objects.
  3. Compaction: Rearranges objects to optimize memory usage.

17. Exception Handling in Ruby

begin
  # Risky code
  File.open("file.txt") { |f| puts f.read }
rescue Errno::ENOENT => e
  # Handle file not found
  puts "File missing: #{e.message}"
rescue StandardError => e
  # General error handling
  puts "Error: #{e}"
ensure
  # Always execute (e.g., cleanup)
  puts "Execution completed."
end
  • rescue: Catches exceptions.
  • else: Runs if no exception.
  • ensure: Runs regardless of success/failure.

Summary

  • Mixins: Use include (instance methods), extend (class methods), or prepend.
  • Singletons: Methods on individual objects (e.g., def obj.method).
  • Meta-Programming: Dynamically define methods/variables with instance_variable_get, define_method, etc.
  • Lookup: Follows the ancestors chain, including modules and eigenclasses.
  • Eigenclasses: The hidden class behind every object for singleton methods.

Happy Ruby Coding! 🚀

Regular Expressions 🎰 in Ruby: A Step-by-Step Guide

Regular expressions (regex) are powerful tools for pattern matching and text manipulation. In Ruby, they’re implemented through the Regexp class. Let’s start with the basics and gradually build up to more complex patterns.

1. Basic Matching

Literal Characters

The simplest regex matches exact text:

"hello".match(/hello/)  #=> #<MatchData "hello">

Special Characters

Some characters have special meaning and need escaping with \:

# Matching a literal dot
"file.txt".match(/file\.txt/)  #=> #<MatchData "file.txt">

2. Character Classes

Simple Character Sets

Match any one character from a set:

# Match either 'a', 'b', or 'c'
"bat".match(/[abc]/)  #=> #<MatchData "b">

Ranges

Match any character in a range:

# Match any lowercase letter
"hello".match(/[a-z]/)  #=> #<MatchData "h">

# Match any digit
"Room 101".match(/[0-9]/)  #=> #<MatchData "1">

Negated Character Sets

Match any character NOT in the set:

# Match any character that's not a vowel
"hello".match(/[^aeiou]/)  #=> #<MatchData "h">

3. Shorthand Character Classes

Ruby provides shortcuts for common character classes:

\d  # Any digit (0-9)
\D  # Any non-digit
\w  # Word character (letter, digit, underscore)
\W  # Non-word character
\s  # Whitespace (space, tab, newline)
\S  # Non-whitespace

Examples:

"Price: $100".match(/\d+/)  #=> #<MatchData "100">
"hello_world".match(/\w+/)  #=> #<MatchData "hello_world">

4. Quantifiers

Control how many times a pattern should match:

?     # 0 or 1 times
*     # 0 or more times
+     # 1 or more times
{n}   # Exactly n times
{n,}  # n or more times
{n,m} # Between n and m times

Examples:

# Match between 3 and 5 digits
"12345".match(/\d{3,5}/)  #=> #<MatchData "12345">

# Match 'color' or 'colour'
"colour".match(/colou?r/)  #=> #<MatchData "colour">

5. Anchors

Match positions rather than characters:

^  # Start of line
$  # End of line
\A # Start of string
\Z # End of string
\b # Word boundary

Examples:

# Check if string starts with 'Hello'
"Hello world".match(/^Hello/)  #=> #<MatchData "Hello">

# Check if string ends with 'world'
"Hello world".match(/world$/)  #=> #<MatchData "world">

6. Grouping and Capturing

Parentheses create groups and capture matches:

# Capture date components
match = "2023-05-18".match(/(\d{4})-(\d{2})-(\d{2})/)
match[1]  #=> "2023" (year)
match[2]  #=> "05"   (month)
match[3]  #=> "18"   (day)

7. Alternation

The pipe | acts like an OR operator:

# Match 'cat' or 'dog'
"dog".match(/cat|dog/)  #=> #<MatchData "dog">

8. Modifiers

Change how the regex works:

i  # Case insensitive
m  # Multiline mode (dot matches newline)
x  # Ignore whitespace (for readability)

Examples:

# Case insensitive match
"HELLO".match(/hello/i)  #=> #<MatchData "HELLO">

9. Lookarounds

Assert that a pattern is or isn’t ahead/behind:

(?=pattern)  # Positive lookahead
(?!pattern)  # Negative lookahead
(?<=pattern) # Positive lookbehind
(?<!pattern) # Negative lookbehind

Example:

# Match 'q' not followed by 'u'
"qat".match(/q(?!u)/)  #=> #<MatchData "q">

10. Ruby-Specific Features

Named Captures

match = "2023-05-18".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
match[:year]  #=> "2023"

%r Notation

Alternative syntax for regex literals:

%r{http://example\.com}  # Same as /http:\/\/example\.com/

String Methods Using Regex

Ruby strings have many regex methods:

"hello".gsub(/[aeiou]/, '*')  #=> "h*ll*"
"a,b,c".split(/,/)            #=> ["a", "b", "c"]
"hello".scan(/./)             #=> ["h", "e", "l", "l", "o"]

Practical Examples

  1. Email Validation:
email_regex = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
"test@example.com".match?(email_regex)  #=> true
  1. Extracting Phone Numbers:
text = "Call me at 555-1234 or (555) 987-6543"
text.scan(/(\(\d{3}\) \d{3}-\d{4}|\d{3}-\d{4})/)  #=> ["555-1234", "(555) 987-6543"]
  1. HTML Tag Extraction:
html = "<p>Hello</p><div>World</div>"
html.scan(/<(\w+)>(.*?)<\/\1>/)  #=> [["p", "Hello"], ["div", "World"]]

Tips for Effective Regex in Ruby

  1. Use Regexp.escape when matching literal strings:

Returns a new string that escapes any characters that have special meaning in a regular expression:

s = Regexp.escape('\*?{}.')      # => "\\\\\\*\\?\\{\\}\\."
   Regexp.escape("file.txt")  #=> "file\\.txt"
  1. For complex patterns, use the x modifier for readability:
   regex = /
     \A             # Start of string
     [\w+\-.]+      # Local part
     @              # @ symbol
     [a-z\d\-]+     # Domain
     (\.[a-z]+)*    # Subdomains
     \.[a-z]+\z     # TLD
   /xi
  1. Consider using Rubular (https://rubular.com/) for testing your Ruby regular expressions.

Regular expressions can become complex, but starting with these fundamentals will give you a solid foundation for text processing in Ruby.

Happy Ruby Coding! 🚀

Useful Ruby 💎 Methods: A Short Guide – Scan, Inject With Performance Analysis

#scan Method

Finds all occurrences of a pattern in a string and returns them as an array.

The scan method in Ruby is a powerful string method that allows you to find all occurrences of a pattern in a string. It returns an array of matches, making it extremely useful for text processing and data extraction tasks.

Basic Syntax

string.scan(pattern) → array
string.scan(pattern) { |match| block } → string

Examples

Simple Word matching:

text = "hello world hello ruby"
matches = text.scan(/hello/)
puts matches.inspect
# Output: ["hello", "hello"]

Matching Multiple Patterns

text = "The quick brown fox jumps over the lazy dog"
matches = text.scan(/\b\w{3}\b/)  # Find all 3-letter words
puts matches.inspect
# Output: ["The", "fox", "the", "dog"]

1. Find All Matches

"hello world".scan(/\w+/) # => ["hello", "world"]  

2. Extract Numbers

"Age: 25, Price: $50".scan(/\d+/) # => ["25", "50"]  

3. Matching All Characters

"hello".scan(/./) { |c| puts c }
# Output:
# h
# e
# l
# l
# o

3. Capture Groups (Returns Arrays)

"Name: Alice, Age: 30".scan(/(\w+): (\w+)/)  
# => [["Name", "Alice"], ["Age", "30"]]  

When you use parentheses in your regex, scan returns arrays of captures:

text = "John: 30, Jane: 25, Alex: 40"
matches = text.scan(/(\w+): (\d+)/)
puts matches.inspect
# Output: [["John", "30"], ["Jane", "25"], ["Alex", "40"]]

4. Iterate with a Block

"a1 b2 c3".scan(/(\w)(\d)/) { |letter, num| puts "#{letter} -> #{num}" }  
# Output:  
# a -> 1  
# b -> 2  
# c -> 3  
text = "Prices: $10, $20, $30"
total = 0
text.scan(/\$(\d+)/) { |match| total += match[0].to_i }
puts total
# Output: 60

5. Case-Insensitive Search

"Ruby is COOL!".scan(/cool/i) # => ["COOL"]  

6. Extract Email Addresses

"Email me at test@mail.com".scan(/\S+@\S+/) # => ["test@mail.com"]  
text = "Contact us at support@example.com or sales@company.org"
emails = text.scan(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/)
puts emails.inspect
# Output: ["support@example.com", "sales@company.org"]

Performance Characteristics: Ruby’s #scan Method

The #scan method is generally efficient for most common string processing tasks, but its performance depends on several factors:

  1. String length – Larger strings take longer to process
  2. Pattern complexity – Simple patterns are faster than complex regex
  3. Number of matches – More matches mean more memory allocation

Performance Considerations

1. Time Complexity 🧮

  • Best case: O(n) where n is string length
  • Worst case: O(n*m) for complex regex patterns (with backtracking)

2. Memory Usage 🧠

  • Creates an array with all matches
  • Each match is a new string object (memory intensive for large results)

Benchmark 📈 Examples

require 'benchmark'

large_text = "Lorem ipsum " * 10_000

# Simple word matching
Benchmark.bm do |x|
  x.report("simple scan:") { large_text.scan(/\w+/) }
  x.report("complex scan:") { large_text.scan(/(?:^|\s)(\w+)(?=\s|$)/) }
end

Typical results:

              user     system      total        real
simple scan:  0.020000   0.000000   0.020000 (  0.018123)
complex scan: 0.050000   0.010000   0.060000 (  0.054678)

Optimization Tips 💡

  1. Use simpler patterns when possible:
   # Slower
   text.scan(/(?:^|\s)(\w+)(?=\s|$)/)

   # Faster equivalent
   text.scan(/\b\w+\b/)
  1. Avoid capture groups if you don’t need them:
   # Slower (creates match groups)
   text.scan(/(\w+)/)

   # Faster
   text.scan(/\w+/)
  1. Use blocks to avoid large arrays:
   # Stores all matches in memory
   matches = text.scan(pattern)

   # Processes matches without storing
   text.scan(pattern) { |m| process(m) }
  1. Consider alternatives for very large strings:
   # For simple splits, String#split might be faster
   words = text.split

   # For streaming processing, use StringIO

When to Be Cautious ⚠️

  • Processing multi-megabyte strings
  • Using highly complex regular expressions
  • When you only need the first few matches (consider #match instead)

The #scan method is optimized for most common cases, but for performance-critical applications with large inputs, consider benchmarking alternatives.


#inject Method (aka #reduce)

Enumerable#inject takes two arguments: a base case and a block.

Each item of the Enumerable is passed to the block, and the result of the block is fed into the block again and iterate next item.

In a way the inject function injects the function between the elements of the enumerable. inject is aliased as reduce. You use it when you want to reduce a collection to a single value.

For example:

    product = [ 2, 3, 4 ].inject(1) do |result, next_value|
      result * next_value
    end
    product #=> 24

Purpose

  • Accumulates values by applying an operation to each element in a collection
  • Can produce a single aggregated result or a compound value

Basic Syntax

collection.inject(initial) { |memo, element| block } → object
collection.inject { |memo, element| block } → object
collection.inject(symbol) → object
collection.inject(initial, symbol) → object

Key Features

  1. Takes an optional initial value
  2. The block receives the memo (accumulator) and current element
  3. Returns the final value of the memo

👉 Examples

1. Summing Numbers

[1, 2, 3].inject(0) { |sum, n| sum + n } # => 6

2. Finding Maximum Value

[4, 2, 7, 1].inject { |max, n| max > n ? max : n } # => 7

3. Building a Hash

[:a, :b, :c].inject({}) { |h, k| h[k] = k.to_s; h }
# => {:a=>"a", :b=>""b"", :c=>"c"}

4. Symbol Shorthand (Ruby 1.9+)

[1, 2, 3].inject(:+) # => 6 (same as sum)
[1, 2, 3].inject(2, :*) # => 12 (2 * 1 * 2 * 3)

5. String Concatenation

%w[r u b y].inject("") { |s, c| s + c.upcase } # => "RUBY"

6. Counting Occurrences

words = %w[apple banana apple cherry apple]
words.inject(Hash.new(0)) { |h, w| h[w] += 1; h }
# => {"apple"=>3, "banana"=>1, "cherry"=>1}

Performance Characteristics: Ruby’s #inject Method

  1. Time Complexity: O(n) – processes each element exactly once
  2. Memory Usage:
  • Generally creates only one accumulator object
  • Avoids intermediate arrays (unlike chained map + reduce)

Benchmark 📈 Examples

require 'benchmark'

large_array = (1..1_000_000).to_a

Benchmark.bm do |x|
  x.report("inject:") { large_array.inject(0, :+) }
  x.report("each + var:") do
    sum = 0
    large_array.each { |n| sum += n }
    sum
  end
end

Typical results show inject is slightly slower than explicit iteration but more concise:

              user     system      total        real
inject:      0.040000   0.000000   0.040000 (  0.042317)
each + var:  0.030000   0.000000   0.030000 (  0.037894)

Optimization Tips 💡

  1. Use symbol shorthand when possible (faster than blocks):
   # Faster
   array.inject(:+)

   # Slower
   array.inject { |sum, n| sum + n }
  1. Preallocate mutable objects when building structures:
   # Good for hashes
   items.inject({}) { |h, (k,v)| h[k] = v; h }

   # Better for arrays
   items.inject([]) { |a, e| a << e.transform; a }
  1. Avoid unnecessary object creation in blocks:
   # Bad - creates new string each time
   strings.inject("") { |s, x| s + x.upcase }

   # Good - mutates original string
   strings.inject("") { |s, x| s << x.upcase }
  1. Consider alternatives for simple cases:
   # For simple sums
   array.sum # (Ruby 2.4+) is faster than inject(:+)

   # For concatenation
   array.join is faster than inject(:+)

When to Be Cautious ⚠️

  • With extremely large collections where memory matters
  • When the block operations are very simple (explicit loop may be faster)
  • When building complex nested structures (consider each_with_object)

The inject method provides excellent readability with generally good performance for most use cases.


Ruby MiniTest 🔬- Minimal replacement for test-unit

Minitest provides a complete suite of testing facilities supporting TDD, BDD, mocking, and benchmarking.

minitest/test is a small and incredibly fast unit testing framework. It provides a rich set of assertions to make your tests clean and readable.

minitest/spec is a functionally complete spec engine. It hooks onto minitest/test and seamlessly bridges test assertions over to spec expectations.

minitest/benchmark is an awesome way to assert the performance of your algorithms in a repeatable manner. Now you can assert that your newb co-worker doesn’t replace your linear algorithm with an exponential one!

minitest/mock by Steven Baker, is a beautifully tiny mock (and stub) object framework.

minitest/pride shows pride in testing and adds coloring to your test output

minitest/test_task – a full-featured and clean rake task generator.
– Minitest Github

♦️ Incredibly small and fast runner, but no bells and whistles.

Let’s take the given example in the doc, we’d like to test the following class:

class Meme
  def i_can_has_cheezburger?
    "OHAI!"
  end

  def will_it_blend?
    "YES!"
  end
end

🧪 Unit tests

Define your tests as methods beginning with test_.

require "minitest/autorun"

class TestMeme < Minitest::Test
  def setup
    @meme = Meme.new
  end

  def test_that_kitty_can_eat
    assert_equal "OHAI!", @meme.i_can_has_cheezburger?
  end

  def test_that_it_will_not_blend
    refute_match /^no/i, @meme.will_it_blend?
  end

  def test_that_will_be_skipped
    skip "test this later"
  end
end

setup ()

# File lib/minitest/test.rb, line 153
def setup; end

♦️ Runs before every test. Use this to set up before each test run.

The terms “unit test” and “spec” are often used in software testing, and while they can overlap, they have some key differences:

🧪 Unit Test vs 📋 Spec: Key Differences

🔬Unit Test

  • Purpose: Tests a single unit of code (typically a method, function, or class) in isolation
  • Scope: Very focused and narrow – tests one specific piece of functionality
  • Style: Usually follows a more traditional testing approach with setup, execution, and assertion
  • Framework examples: Minitest (like in your Ruby file), JUnit, pytest
  • Structure: Often uses test_ prefix or Test classes with assertion methods

📝 Spec (Specification)

  • Purpose: Describes the behavior and requirements of the system in a more readable, documentation-like format
  • Scope: Can cover unit-level, integration, or acceptance testing
  • Style: Uses natural language descriptions that read like specifications
  • Framework examples: RSpec, Jasmine, Mocha, Jest
  • Structure: Uses descriptive blocks like describe, it, should

⚖️ Key Differences

1. ✍️ Writing Style:

  • Unit Test
    def test_array_is_empty with assertions
  • Spec
    describe "when array is empty" do
    it "should return error message"

2. 👁️ Readability:

  • Unit Test: More code-focused, technical
  • Spec: More human-readable, business-focused

3. 🎯 Philosophy:

  • Unit Test: Test the implementation
  • Spec: Specify the behavior (BDD – Behavior Driven Development)

📊 Example Comparison

🏷️ Our current Minitest code:

def array_is_an_empty_array
  assert_equal 'Provide an array with length 2 or more', two_sum([], 9)
end

🎨 RSpec equivalent (spec style):

describe "two_sum" do
  context "when array is empty" do
    it "returns an error message" do
      expect(two_sum([], 9)).to eq('Provide an array with length 2 or more')
    end
  end
end

Both test the same functionality, but specs emphasize describing behavior in natural language, making them easier for non-technical stakeholders to understand. 🎉

🔬 Mini-test equivalent:

# frozen_string_literal: true

require 'minitest/spec'
require_relative 'two_sum'

describe "TwoSum" do
  describe "when array is empty" do
    it "returns an error message" do
      _(two_sum([], 9)).must_equal 'Provide an array with length 2 or more'
    end
  end
end

The underscore _() in Minitest spec style is a wrapper method that converts the value into an expectation object.

Here’s why it’s used:

🔍 Why the Underscore _()?
🎯 Purpose:

The _() method wraps your actual value and returns a special expectation object that has assertion methods like must_equal, must_be, etc.

⚙️ How it works:
# This:
_(two_sum([], 9)).must_equal 'Provide an array with length 2 or more'

# Is equivalent to:
# 1. two_sum([], 9) returns some value
# 2. _() wraps that value into an expectation object
# 3. .must_equal() is called on that expectation object
🔄 Alternative Syntaxes
1. 📝 Using expect() (more readable):
expect(two_sum([], 9)).must_equal 'Provide an array with length 2 or more'
2. 🔧 Using value() (explicit):
value(two_sum([], 9)).must_equal 'Provide an array with length 2 or more'
3. 🏷️ Traditional unit test style (no wrapper needed):
assert_equal 'Provide an array with length 2 or more', two_sum([], 9)
💡 Why underscore specifically?
  • Minimal syntax: _() is short and doesn’t clutter the code
  • Ruby convention: Underscore often indicates “throwaway” or “utility” variables
  • Non-conflicting: Unlikely to conflict with your method names
  • Chainable: Creates a fluent interface for assertions
🎨 Complete comparison:
# Spec style with underscore
_(result).must_equal expected

# Spec style with expect (more readable)
expect(result).must_equal expected

# Unit test style (no wrapper)
assert_equal expected, result

The expect() version is often preferred because it’s more self-documenting!

🎨 Alternative Spec Style with Expectation Syntax:

# frozen_string_literal: true

require 'minitest/spec'
require_relative 'two_sum'

describe "TwoSum" do
  describe "when array is empty" do
    it "returns an error message" do
      expect(two_sum([], 9)).must_equal 'Provide an array with length 2 or more'
    end
  end
end

⚖️ Key Differences in Minitest

🔧 Setup Required:
  • Unit Test: require 'minitest/test'
  • Spec: require 'minitest/spec'
✍️ Assertion Style:
  • Unit Test: assert_equal expected, actual
  • Spec: _(actual).must_equal expected or expect(actual).must_equal expected
🏗️ Structure:
  • Unit Test: Classes with test_ methods
  • Spec: describe blocks with it blocks
🎯 Readability:

Both styles work with Minitest, but the spec style reads more like natural language documentation, making it easier to understand the intended behavior! 

Excellent question! Let me clarify the relationship between TDD/BDD (methodologies) and RSpec/Minitest (testing frameworks):

Happy Testing!

A Complete Guide to Ruby on Rails Security Measures 🛡️

Ruby on Rails is known for its developer-friendly conventions, but it’s also built with security in mind. While the framework provides many features to guard against common threats, it’s up to developers to understand and apply them correctly.

In this post, we’ll walk through essential Rails security measures, tackle real-world threats, and share best practices – with examples for both API-only and full-stack Rails applications.

🚨 Common Web Threats Rails Helps Mitigate

  1. SQL Injection
  2. Cross-Site Scripting (XSS)
  3. Cross-Site Request Forgery (CSRF)
  4. Mass Assignment
  5. Session Hijacking
  6. Insecure Deserialization
  7. Insecure File Uploads
  8. Authentication & Authorization flaws

Let’s explore how Rails addresses these and what you can do to reinforce your app.


1. 🧱 SQL Injection

🛡️ Rails Protection:

Threat: Attackers inject malicious SQL through user inputs to read, modify, or delete database records

Rails uses Active Record with prepared statements to prevent SQL injection by default.

Arel: Build complex queries without string interpolation.

# Safe - uses bound parameters
User.where(email: params[:email])

# ❌ Dangerous - interpolates input directly
User.where("email = '#{params[:email]}'")

# Safe: Parameterized query
User.where("role = ? AND created_at > ?", params[:role], 7.days.ago)

# Using Arel for dynamic conditions
users = User.arel_table
def recent_admins
  User.where(users[:role].eq('admin').and(users[:created_at].gt(7.days.ago)))
end

Tip: Never use string interpolation to build SQL queries. Use .where, .find_by, or Arel methods.

Additional Measures

  • Whitelist Columns: Pass only known column names to dynamic ordering or filtering.
  • Gem: activerecord-security to raise errors on unsafe query methods.

2. 🧼 Cross-Site Scripting (XSS)

Threat: Injection of malicious JavaScript via user inputs, compromising other users’ sessions.

🛡️ Rails Protection

Content Security Policy (CSP): Limit sources of executable scripts.

# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
  policy.default_src :self
  policy.script_src  :self, :https
  policy.style_src   :self, :https
end

Auto-Escaping: <%= %> escapes HTML; <%== %> and raw do not.

Rails auto-escapes output in views.

<!-- Safe: Escaped -->
<%= user.bio %>

<!-- Unsafe: Unescaped (only use if trusted) -->
<%= raw user.bio %>

In API-only apps: Always sanitize any input returned in JSON if used in web contexts later.

Use gems:

  • sanitize gem to strip malicious HTML
  • loofah for more control (Loofah for robust HTML5 handling and scrubbers.)
# In models or controllers
clean_bio = Loofah.fragment(params[:bio]).scrub!(:prune).to_s

3. 🔐 Cross-Site Request Forgery (CSRF)

🔍 How CSRF Works (Example)

1.Victim logs in to bank.example.com, receiving a session cookie.

2. Attacker crafts a hidden form on attacker.com:

<form action="https://bank.example.com/transfer" method="POST">
  <input type="hidden" name="amount" value="1000">
  <input type="hidden" name="to_account" value="attacker_account">
</form>
<script>document.forms[0].submit();</script>

3. Victim visits attacker.com while still logged into the bank.

4. Browser auto-sends the bank session cookie with the forged POST—and the transfer goes through, because the bank sees a “legitimate” logged-in request.

🛡️ Rails’ CSRF Protection

Rails ships with built-in defenses against CSRF by embedding an unguessable token in forms and verifying it on each non-GET request.

1.protect_from_forgery

In ApplicationController, Rails by default includes:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

This causes Rails to raise an exception if the token is missing or invalid.

Refer: https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

2. Authenticity Token in Forms

All Rails form-builders (form_with, form_for, form_tag) automatically insert:

<input type="hidden" name="authenticity_token" value="…secure random…">

3.Meta Tag for AJAX

Rails also inserts in <head>:

<%= csrf_meta_tags %>

Which renders:

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="…secure random…" />

Rails UJS or Turbo JS will read these and include the token on XHR/fetch requests.

4.Server-Side Verification

On each POST/PUT/PATCH/DELETE, Rails:

  • Extracts the token (from form param, header X-CSRF-Token, or query string).
  • Compares it to the session-stored token.
  • Rejects the request if they don’t match.

API-only apps:

CSRF is less relevant for stateless APIs using tokens, but if you use session-based authentication, enable CSRF protection:

# application_controller.rb
protect_from_forgery with: :exception

Thought for a couple of seconds

Cross-Site Request Forgery (CSRF) is an attack that tricks a user’s browser into submitting a request (e.g. form submission, link click) to your application without the user’s intention, leveraging the fact that the browser automatically includes credentials (cookies, basic auth headers, etc.) with each request.

🔧 Disabling or Customizing CSRF

♦️ Disable for APIs (stateless JSON endpoints):

class Api::BaseController < ActionController::API skip_before_action :verify_authenticity_token end

♦️ Use Null Session (allowing some API use without exception):

protect_from_forgery with: :null_session

✅ Key Takeaways

  • CSRF exploits the browser’s automatic credential sending.
  • Rails guards by inserting and validating an unguessable token.
  • Always keep protect_from_forgery with: :exception in your base controller for full-stack Rails apps.

4. 🛑 Mass Assignment Vulnerability

Threat: Attackers pass unexpected parameters to update sensitive attributes (e.g., admin=true).

Before Rails 4, mass assignment was a common issue. Now, strong parameters protect against it.

✅ Use Strong Parameters:

# ✅ Safe
def user_params
  params.require(:user).permit(:name, :email)
end

User.create(user_params)

# ❌ Unsafe
User.create(params[:user])

Pro tip: Don’t over-permit, especially with admin or role-based attributes.

Real-World Gotcha

  • Before permitting arrays or nested attributes, validate length and content.
params.require(:order).permit(:total, items: [:product_id, :quantity])

5. 🔒 Secure Authentication

Built-In: has_secure_password

Provides authenticate method.

Uses BCrypt with configurable cost.

# user.rb
class User < ApplicationRecord
  has_secure_password
  # optional: validates length, complexity
  validates :password, length: { minimum: 12 }, format: { with: /(?=.*\d)(?=.*[A-Z])/ }
end

Make sure you have a password_digest column. This uses bcrypt under the hood.

Using Devise

JWT: integrate with devise-jwt for stateless APIs.

Modules: Database Authenticatable, Confirmable, Lockable, Timeoutable, Trackable.

Devise gives you:

  • Password encryption
  • Lockable accounts
  • Timeoutable sessions
  • Token-based authentication for APIs (with devise-jwt)
# config/initializers/devise.rb
Devise.setup do |config|
  config.jwt do |jwt|
    jwt.secret = Rails.application.credentials.devise_jwt_secret
    jwt.dispatch_requests = [['POST', %r{^/login$}]]
    jwt.revocation_requests = [['DELETE', %r{^/logout$}]]
  end
end

6. 🧾 Authorization

Threat: Users access or modify resources beyond their permissions.

Never trust the frontend. Always check permissions server-side.

# ❌ Dangerous
redirect_to dashboard_path if current_user.admin?

# ✅ Use Pundit or CanCanCan
authorize @order

Gems:

  • pundit – lean policy-based authorization
  • cancancan – rule-based authorization

Pundit Example

# app/policies/article_policy.rb
class ArticlePolicy
  attr_reader :user, :article

  def initialize(user, article)
    @user = user
    @article = article
  end

  def update?
    user.admin? || article.author_id == user.id
  end
end

# In controller
def update
  @article = Article.find(params[:id])
  authorize @article
  @article.update!(article_params)
end

Use Existing Auditing Libraries

To track user actions including access, use:

For Rails 8 check the post for Rails own Authentication: https://railsdrop.com/2025/05/07/rails-8-implement-users-authentication-orders-order-items/

7. 🗃️ Secure File Uploads

Threat: Attackers upload malicious files (e.g., scripts, executables).

Use Active Storage securely:

<%= image_tag url_for(user.avatar) %>

Active Storage Best Practices

Validation:

class Photo < ApplicationRecord
  has_one_attached :image
  validate :image_type, :image_size

  private
  def image_type
    return unless image.attached?
    acceptable = ['image/jpeg', 'image/png']
    errors.add(:image, 'must be JPEG or PNG') unless acceptable.include?(image.content_type)
  end

  def image_size
    return unless image.attached?
    errors.add(:image, 'is too big') if image.byte_size > 5.megabytes
  end
end
  • Validate content type:
validates :avatar, content_type: ['image/png', 'image/jpg', 'image/jpeg']

  • Restrict file size.
  • Store uploads in private S3 buckets for sensitive data.
  • Private URLs for sensitive documents (e.g., contracts).
  • Virus Scanning: hook into after_upload to scan with ClamAV (or VirusTotal API).

8. 🧾 HTTP Headers & SSL

Rails helps with secure headers via secure_headers gem (https://github.com/github/secure_headers).

# config/initializers/secure_headers.rb
SecureHeaders::Configuration.default do |config|
  config.hsts = "max-age=31536000; includeSubDomains"
  config.x_frame_options = "DENY"
  config.x_content_type_options = "nosniff"
  config.x_xss_protection = "1; mode=block"
end

SSL/TLS Force HTTPS:

# config/environments/production.rb
config.force_ssl = true

Ensure HSTS is enabled:
# config/initializers/secure_headers.rb
Rails.application.config.middleware.insert_before 0, SecureHeaders::Middleware
SecureHeaders::Configuration.default do |config|
  config.hsts = "max-age=63072000; includeSubDomains; preload"
end

Key Headers

  • X-Frame-Options: DENY to prevent clickjacking.
  • X-Content-Type-Options: nosniff.
  • Referrer-Policy: strict-origin-when-cross-origin.

9. 🧪 Security Testing

  • Use brakeman to detect common vulnerabilities.
bundle exec brakeman

  • Add bundler-audit to scan for insecure gems.
bundle exec bundler-audit check --update

Check the post for more details: https://railsdrop.com/2025/05/05/rails-8-setup-simplecov-brakeman-for-test-coverage-security/

  • Fuzz & Pen Testing: Use tools like ZAP Proxy, OWASP ZAP.
  • Use RSpec tests for role restrictions, parameter whitelisting, and CSRF.
describe "Admin access" do
  it "forbids non-admins from deleting users" do
    delete admin_user_path(user)
    expect(response).to redirect_to(root_path)
  end
end

  • Continuous Integration – Integrate scans in CI pipeline (GitHub Actions example):
jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Brakeman
        run: bundle exec brakeman -o brakeman-report.html
      - name: Bundler Audit
        run: bundle exec bundler-audit check --update

Read the post: Setup 🛠 Rails 8 App – Part 15: Set Up CI/CD ⚙️ with GitHub Actions for Rails 8

10. 🔑 API Security (Extra Measures)

  • Use JWT or OAuth2 for stateless token authentication.
  • Set appropriate CORS headers.

Gem: `rack-cors` (https://github.com/cyu/rack-cors)

Add in your Gemfile:

gem 'rack-cors'
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'your-frontend.com'
    resource '*',
      headers: :any,
      expose: ['Authorization'],
      methods: [:get, :post, :patch, :put, :delete, :options]
  end
end

  • Rate-limit endpoints with Rack::Attack

Include the Gem rack-attack (https://github.com/rack/rack-attack) to your Gemfile.

# In your Gemfile
gem 'rack-attack'
# config/initializers/rack_attack.rb

Rack::Attack.throttle('req/ip', limit: 60, period: 1.minute) do |req|
  req.ip
end

in Rails 8 we can use rate_limit for Controller actions like:

  rate_limit to: 10, within: 1.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." }

  • Pagination & Filtering: Prevent large payloads to avoid DoS.

📝 Summary: Best Practices Checklist

✅ Use Strong Parameters
✅ Escape output (no raw unless absolutely trusted)
✅ Sanitize user content
✅ Use Devise or Sorcery for auth
✅ Authorize every resource with Pundit or CanCanCan
✅ Store files safely and validate uploads
✅ Enforce HTTPS in production
✅ Regularly run Brakeman and bundler-audit
✅ Rate-limit APIs with Rack::Attack
✅ Keep dependencies up to date

🔐 Final Thought

Rails does a lot to keep you safe — but security is your responsibility. Follow these practices and treat every external input as potentially dangerous. Security is not a one-time setup — it’s an ongoing process.


Happy and secure coding! 🚀

Guide: Integrating React.js ⚛️ into a Rails 8 Application | Node.js | ESBuild | Virtual DOM- Part 1

1. Introduction and Motivation

Why React?

  • Declarative UI: build complex interfaces by composing small, reusable components.
  • Virtual DOM: efficient updates, smoother user experience.
  • Rich ecosystem: hooks, context, testing tools, and libraries like Redux.
  • Easy to learn once you grasp JSX and component lifecycle.

Why use React in Rails?

  • Leverage Rails’ backend power (ActiveRecord, routing, authentication) with React’s frontend flexibility.
  • Build single-page-app-like interactions within a Rails monolith or progressively enhance ERB views.

2. Prerequisites

  • Ruby 3.4.x installed (recommend using rbenv or RVM or Mise).
  • Rails 8.x (we’ll install below).
  • Node.js (>= 16) and npm or Yarn.
  • Code editor (VS Code, RubyMine, etc.).

Why Node.js is Required for React

React’s ecosystem relies on a JavaScript runtime and package manager:

  • Build tools (ESBuild, Webpack, Babel) run as Node.js scripts to transpile JSX/ES6 and bundle assets.
  • npm/Yarn fetch and manage React and its dependencies from the npm registry.
  • Script execution: Rails generators and custom npm scripts (e.g. rails javascript:install:react, npm run build) need Node.js to execute.

Without Node.js, you cannot install packages or run the build pipeline necessary to compile and serve React components.

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime built on Chrome’s V8 engine. It enables JavaScript to be executed on the server (outside the browser) and provides:

  • Server-side scripting: build web servers, APIs, and backend services entirely in JavaScript.
  • Command-line tools: run scripts for tasks like building, testing, or deploying applications.
  • npm ecosystem: access to hundreds of thousands of packages for virtually any functionality, from utility libraries to full frameworks.
  • Event-driven, non-blocking I/O: efficient handling of concurrent operations, making it suitable for real-time applications.

Node.js is the backbone that powers React’s tooling, package management, and build processes.

3. Installing Ruby 3.4 and Rails 8

1. Install Ruby 3.4.0 (example using rbenv):

# install rbenv and ruby-build if not yet installed
brew install rbenv ruby-build
rbenv install 3.4.0
rbenv global 3.4.0
ruby -v   # => ruby 3.4.0p0

Check the post for using Mise as version manager: https://railsdrop.com/2025/02/11/installing-and-setup-ruby-3-rails-8-vscode-ide-on-macos-in-2025/

2. Install Rails 8:

gem install rails -v "~> 8.0"
rails -v   # => Rails 8.0.x

4. Generating a New Rails 8 App

We’ll scaffold a fresh project using ESBuild for JavaScript bundling, which integrates seamlessly with React.

rails new design_studio_react \
  --database=postgresql \
  -j esbuild
cd design_studio_react
  • --database=postgresql: sets PostgreSQL as the database adapter.
  • -j esbuild: configures ESBuild for JS bundling (preferred for React in Rails 8).

4.1 About ESBuild

ESBuild is a next-generation JavaScript bundler and minifier written in Go. Rails 8 adopted ESBuild by default for JavaScript bundling due to its remarkable speed and modern feature set:

  • Blazing-fast builds: ESBuild performs parallel compilation and leverages Go’s concurrency, often completing bundling in milliseconds even for large codebases.
  • Built‑in transpilation: it supports JSX and TypeScript out of the box, so you don’t need separate tools like Babel unless you have highly custom transforms.
  • Tree shaking: ESBuild analyzes import/export usage to eliminate dead code, producing smaller bundles.
  • Plugin system: you can extend ESBuild with plugins for asset handling, CSS bundling, or custom file types.
  • Simplicity: configuration is minimal—Rails’ -j esbuild flag generates sensible defaults, and you can tweak options in package.json or a separate esbuild.config.js.

How Rails Integrates ESBuild

When you run:

rails new design_studio_react --database=postgresql -j esbuild

Rails will:

1. Install the esbuild npm package alongside react dependencies.

2. Generate build scripts in package.json, e.g.:

"scripts": { 
"build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds", 
"build:watch": "esbuild app/javascript/*.* --bundle --sourcemap --watch --outdir=app/assets/builds" 
}

3. Add a default app/assets/builds output directory and ensure Rails’ asset pipeline picks up the compiled files.

Customizing ESBuild

If you need to tweak ESBuild settings:

Add an esbuild.config.js at your project root:

const esbuild = require('esbuild')

esbuild.build({
  entryPoints: ['app/javascript/application.js'],
  bundle: true,
  sourcemap: true,
  outdir: 'app/assets/builds',
  loader: { '.js': 'jsx', '.png': 'file' },
  define: { 'process.env.NODE_ENV': '"production"' },
}).catch(() => process.exit(1))

Update package.json scripts to use this config:

"scripts": {
  "build": "node esbuild.config.js",
  "build:watch": "node esbuild.config.js --watch"
}

Why ESBuild Matters for React in Rails

  • Developer experience: near-instant rebuilds let you see JSX changes live without delay.
  • Production readiness: built‑in minification and tree shaking keep your asset sizes small.
  • Future-proof: the plugin ecosystem grows, and Rails can adopt newer bundlers (like SWC or Vite) with a similar pattern.

With ESBuild, your React components compile quickly, your development loop tightens, and your production assets stay optimized—making it the perfect companion for a modern Rails 8 + React stack.

5. What is Virtual DOM

The Virtual DOM is one of React’s most important concepts. Let me explain it clearly with examples.

🎯 What is the Virtual DOM?

The Virtual DOM is a JavaScript representation (copy) of the actual DOM that React keeps in memory. It’s a lightweight JavaScript object that describes what the UI should look like.

📚 Real DOM vs Virtual DOM

Real DOM (What the browser uses):
<!-- This is the actual DOM in the browser -->
<div id="todo-app">
  <h1>My Todo List</h1>
  <ul>
    <li>React List</li>
    <li>Build a todo app</li>
  </ul>
</div>
Virtual DOM (React’s JavaScript representation):
// This is React's Virtual DOM representation
{
  type: 'div',
  props: {
    id: 'todo-app',
    children: [
      {
        type: 'h1',
        props: {
          children: 'My Todo List'
        }
      },
      {
        type: 'ul',
        props: {
          children: [
            {
              type: 'li',
              props: {
                children: 'React List'
              }
            },
            {
              type: 'li',
              props: {
                children: 'Build a todo app'
              }
            }
          ]
        }
      }
    ]
  }
}

🔄 How Virtual DOM Works – The Process

Step 1: Initial Render
// Your JSX
const App = () => {
  return (
    <div>
      <h1>My Todo List</h1>
      <ul>
        <li>React List</li>
      </ul>
    </div>
  );
};
// React creates Virtual DOM
const virtualDOM = {
  type: 'div',
  props: {
    children: [
      { type: 'h1', props: { children: 'My Todo List' } },
      { 
        type: 'ul', 
        props: { 
          children: [
            { type: 'li', props: { children: 'React List' } }
          ]
        }
      }
    ]
  }
};
Step 2: State Changes
// When you add a new todo
const App = () => {
  const [todos, setTodos] = useState(['React List']);

  const addTodo = () => {
    setTodos(['React List', 'Build Todo App']); // State change!
  };

  return (
    <div>
      <h1>My Todo List</h1>
      <ul>
        {todos.map(todo => <li key={todo}>{todo}</li>)}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
};
Step 3: New Virtual DOM is Created
// React creates NEW Virtual DOM
const newVirtualDOM = {
  type: 'div',
  props: {
    children: [
      { type: 'h1', props: { children: 'My Todo List' } },
      { 
        type: 'ul', 
        props: { 
          children: [
            { type: 'li', props: { children: 'React List' } },
            { type: 'li', props: { children: 'Build Todo App' } } // NEW!
          ]
        }
      },
      { type: 'button', props: { children: 'Add Todo' } }
    ]
  }
};
Step 4: Diffing Algorithm
// React compares old vs new Virtual DOM
const differences = [
  {
    type: 'ADD',
    location: 'ul.children',
    element: { type: 'li', props: { children: 'Build Todo App' } }
  }
];
Step 5: Reconciliation (Updating Real DOM)
// React updates ONLY what changed in the real DOM
const ul = document.querySelector('ul');
const newLi = document.createElement('li');
newLi.textContent = 'Build Todo App';
ul.appendChild(newLi); // Only this line runs!

🚀 Why Virtual DOM is Fast

Without Virtual DOM (Traditional approach):
// Traditional DOM manipulation
function updateTodoList(todos) {
  const ul = document.querySelector('ul');
  ul.innerHTML = ''; // Clear everything!

  todos.forEach(todo => {
    const li = document.createElement('li');
    li.textContent = todo;
    ul.appendChild(li); // Recreate everything!
  });
}
With Virtual DOM (React approach):
// React's approach
function updateTodoList(oldTodos, newTodos) {
  const differences = findDifferences(oldTodos, newTodos);

  differences.forEach(diff => {
    if (diff.type === 'ADD') {
      // Only add the new item
      const li = document.createElement('li');
      li.textContent = diff.todo;
      ul.appendChild(li);
    }
  });
}

🎭 Real Example with Our Todo App

Let’s trace through what happens when you add a todo:

Before Adding Todo:
// Current state
const [todos, setTodos] = useState([
  { id: 1, text: 'React List', completed: false },
  { id: 2, text: 'Build Todo App', completed: false }
]);

// Virtual DOM representation
{
  type: 'ul',
  props: {
    children: [
      { type: 'li', key: 1, props: { children: 'React List ⏳' } },
      { type: 'li', key: 2, props: { children: 'Build Todo App ⏳' } }
    ]
  }
}
After Adding Todo:
// New state
const [todos, setTodos] = useState([
  { id: 1, text: 'React List', completed: false },
  { id: 2, text: 'Build Todo App', completed: false },
  { id: 3, text: 'Master React Hooks', completed: false } // NEW!
]);

// New Virtual DOM
{
  type: 'ul',
  props: {
    children: [
      { type: 'li', key: 1, props: { children: 'React List ⏳' } },
      { type: 'li', key: 2, props: { children: 'Build Todo App ⏳' } },
      { type: 'li', key: 3, props: { children: 'Master React Hooks ⏳' } } // NEW!
    ]
  }
}
React’s Diffing Process:
// React compares and finds:
const changes = [
  {
    type: 'INSERT',
    location: 'ul',
    element: { type: 'li', key: 3, props: { children: 'Master React Hooks ⏳' } }
  }
];

// React updates ONLY what changed:
const ul = document.querySelector('ul');
const newLi = document.createElement('li');
newLi.textContent = 'Master React Hooks ⏳';
ul.appendChild(newLi); // Only this operation!

🎯 Key Benefits of Virtual DOM

1. Performance:
// Without Virtual DOM: Updates entire list
document.querySelector('ul').innerHTML = generateEntireList(todos);

// With Virtual DOM: Updates only what changed
document.querySelector('ul').appendChild(newTodoElement);
2. Predictability:
// You write declarative code
const TodoList = ({ todos }) => (
  <ul>
    {todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
  </ul>
);

// React handles the imperative updates
// You don't need to manually add/remove DOM elements
3. Batching:
// Multiple state updates in one event
const handleButtonClick = () => {
  setTodos([...todos, newTodo]);     // Change 1
  setInputValue('');                 // Change 2
  setCount(count + 1);              // Change 3
};

// React batches these into one DOM update!

🔧 Virtual DOM in Action – Debug Example

You can actually see the Virtual DOM in action:

import React, { useState } from 'react';

const App = () => {
  const [todos, setTodos] = useState(['React List']);

  const addTodo = () => {
    console.log('Before update:', todos);
    setTodos([...todos, 'New Todo']);
    console.log('After update:', todos); // Still old value!
  };

  console.log('Rendering with todos:', todos);

  return (
    <div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
};

🎭 Common Misconceptions

❌ “Virtual DOM is always faster”
// For simple apps, Virtual DOM has overhead
// Direct DOM manipulation can be faster for simple operations
document.getElementById('counter').textContent = count;
❌ “Virtual DOM prevents all DOM operations”
// React still manipulates the real DOM
// Virtual DOM just makes it smarter about WHEN and HOW
✅ “Virtual DOM optimizes complex updates”
// When you have many components and complex state changes
// Virtual DOM's diffing algorithm is much more efficient

🧠 Does React show Virtual DOM to the user?

No. The user only ever sees the real DOM.
The Virtual DOM (VDOM) is never shown directly. It’s just an internal tool used by React to optimize how and when the real DOM gets updated.

🧩 What is Virtual DOM exactly?

  • A JavaScript-based, lightweight copy of the real DOM.
  • Stored in memory.
  • React uses it to figure out what changed after state/props updates.

👀 What the user sees:

  • The real, visible HTML rendered to the browser — built from React components.
  • This is called the Real DOM.

🔁 So why use Virtual DOM at all?

✅ Because manipulating the real DOM is slow.

React uses VDOM to:

  1. Build a new virtual DOM after every change.
  2. Compare (diff) it with the previous one.
  3. Figure out the minimum real DOM updates required.
  4. Apply only those changes to the real DOM.

This process is called reconciliation.

🖼️ Visual Analogy

Imagine the Virtual DOM as a sketchpad.
React draws the new state on it, compares it with the old sketch, and only updates what actually changed in the real-world display (real DOM).

✅ TL;DR

QuestionAnswer
Does React show the virtual DOM to user?❌ No. Only the real DOM is ever visible to the user.
What is virtual DOM used for?🧠 It’s used internally to calculate DOM changes efficiently.
Is real DOM updated directly?✅ Yes, but only the minimal parts React determines from the VDOM diff.

🧪 Example Scenario

👤 The user is viewing a React app with a list of items and a button:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  ...
  <li>Item 10</li>
</ul>
<button>Read More</button>

When the user clicks “Read More”, the app adds 10 more items to the list.

🧠 Step-by-Step: What Happens Behind the Scenes

✅ 1. User Clicks “Read More” Button

<button onClick={loadMore}>Read More</button>

This triggers a React state update, e.g.:

function loadMore() {
  setItems([...items, ...next10Items]); // updates state
}

🔁 State change → React starts re-rendering

📦 2. React Creates a New Virtual DOM

  • React re-runs the component’s render function.
  • This generates a new Virtual DOM tree (just a JavaScript object structure).

Example of the new VDOM:

{
  type: "ul",
  children: [
    { type: "li", content: "Item 1" },
    ...
    { type: "li", content: "Item 20" } // 10 new items
  ]
}

🧮 3. React Diffs New Virtual DOM with Old One

  • Compares previous VDOM (10 <li> items) vs new VDOM (20 <li> items).
  • Finds that 10 new <li> nodes were added.

This is called the reconciliation process.

⚙️ 4. React Updates the Real DOM

  • React tells the browser:
    “Please insert 10 new <li> elements inside the <ul>.”

Only these 10 DOM operations happen.
❌ React does not recreate the entire <ul> or all 20 items.

🖼️ What the User Sees

On the screen (the real DOM):

<ul>
  <li>Item 1</li>
  ...
  <li>Item 20</li>
</ul>

The user never sees the Virtual DOM — they only see the real DOM updates that React decides are necessary.

🧠 Summary: Virtual DOM vs Real DOM

StepVirtual DOMReal DOM
Before click10 <li> nodes in memory10 items visible on screen
On clickNew VDOM generated with 20 <li> nodesReact calculates changes
DiffCompares new vs old VDOMDetermines: “Add 10 items”
CommitNo UI shown from VDOMOnly those 10 new items added to browser DOM

✅ Key Point

🧠 The Virtual DOM is a tool for React, not something the user sees.
👁️ The user only sees the final, optimized changes in the real DOM.


🎯 Summary

Virtual DOM is React’s:

  1. JavaScript representation of the real DOM
  2. Diffing algorithm that compares old vs new Virtual DOM
  3. Reconciliation process that updates only what changed
  4. Performance optimization for complex applications
  5. Abstraction layer that lets you write declarative code

Think of it as React’s smart assistant that:

  • Remembers what your UI looked like before
  • Compares it with what it should look like now
  • Makes only the necessary changes to the real DOM

This is why you can write simple, declarative code like {todos.map(todo => <li>{todo}</li>)} and React handles all the complex DOM updates efficiently!


🔄 After the Virtual DOM Diff, How React Updates the Real DOM

🧠 Step-by-Step:

  1. React creates a diff between the new and previous virtual DOM trees.
  2. React then creates a list of “instructions” called the update queue.
    • Examples:
      • “Insert <li>Item 11</li> at position 10″
      • “Remove <div> at index 3″
      • “Change text of button to ‘Read Less'”
  3. These changes are passed to React’s reconciliation engine.
  4. React uses the browser’s DOM APIs (document.createElement, appendChild, removeChild, etc.) to apply only the minimal changes.

✅ So instead of doing:

document.body.innerHTML = newHTML; // inefficient, replaces all

React does:

const newEl = document.createElement("li");
newEl.textContent = "Item 11";
ul.appendChild(newEl); // just this

❓ Why Didn’t Browsers Do This Earlier?

Excellent historical question. The short answer is: Browsers give us the tools, but React gave us the strategy.

⚠️ Why browsers didn’t do it automatically:

ReasonExplanation
🧱 Low-level APIsThe browser exposes DOM APIs (appendChild, setAttribute), but they’re imperative — devs must write the logic.
🤯 ComplexityManaging DOM efficiently across many updates (nested, reordered, conditional elements) is hard and bug-prone manually.
🔁 Manual state syncingBefore React, developers had to manually keep UI in sync with state. That logic got complex and messy fast.
📦 No built-in abstractionBrowsers don’t offer a built-in “virtual diff engine” or abstraction like React’s VDOM.

🤖 What React Added That Browsers Don’t

FeatureBrowser DOMReact (with VDOM)
Efficient diffing❌ No✅ Yes (reconciliation)
Declarative UI❌ No✅ Yes (return <UI />)
Component abstraction❌ No✅ Yes (function/class components)
State-driven rendering❌ Manual✅ Built-in
Minimal updates❌ Up to you✅ Automatic via VDOM

✅ TL;DR

  • React calculates exactly what changed via the virtual DOM diffing.
  • It then uses native DOM APIs to update only what’s necessary in the real DOM.
  • Browsers give you low-level control, but not an optimized strategy for updating UI based on state — React filled that gap beautifully.

Now Let’s break down how a React app starts after you run:

npx create-react-app my-app
cd my-app
npm start

What actually happens behind the scenes? Let’s unpack it step-by-step 👇

⚙️ Step 1: npx create-react-app — What It Does

This command:

  • Downloads and runs the latest version of the create-react-app tool (CRA).
  • Sets up a project with:
    • A preconfigured Webpack + Babel build system
    • Development server
    • Scripts and dependencies
  • Installs React, ReactDOM, and a bunch of tools inside node_modules.

Key folders/files created:

my-app/
├── node_modules/
├── public/
├── src/
│   └── index.js       👈 main entry point
├── package.json

Step 2: npm start — How the App Runs

When you run:

npm start

It’s actually running this line from package.json:

"scripts": {
  "start": "react-scripts start"
}

So it calls:

react-scripts start

🧠 What is react-scripts?

react-scripts is a package from Facebook that:

  • Runs a development server using Webpack Dev Server
  • Compiles JS/JSX using Babel
  • Watches your files for changes (HMR)
  • Starts a browser window at http://localhost:3000

It configures:

  • Webpack
  • Babel
  • ESLint
  • PostCSS
  • Source maps
    … all behind the scenes, so you don’t have to set up any configs manually.

📦 Libraries Involved

Tool / LibraryPurpose
ReactCore UI library (react)
ReactDOMRenders React into actual DOM (react-dom)
WebpackBundles your JS, CSS, images, etc.
BabelConverts modern JS/JSX to browser-friendly JS
Webpack Dev ServerStarts dev server with live reloading
react-scriptsRuns all the above with pre-made configs

🏗️ Step 3: Entry Point — src/index.js

The app starts here:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

  • ReactDOM.createRoot(...) finds the <div id="root"> in public/index.html.
  • Then renders the <App /> component into it.
  • The DOM inside the browser updates — and the user sees the UI.

✅ TL;DR

StepWhat Happens
npx create-react-appSets up a full React project with build tools
npm startCalls react-scripts start, which runs Webpack dev server
react-scriptsHandles build, hot reload, and environment setup
index.jsLoads React and renders your <App /> to the browser DOM
Browser OutputYou see your live React app at localhost:3000

6. Installing and Configuring React

Rails 8 provides a generator to bootstrap React + ESBuild.

  1. Run the React installer:
    rails javascript:install:react
    This will:
    • Install react and react-dom via npm.
    • Create an example app/javascript/components/HelloReact.jsx component.
    • Configure ESBuild to transpile JSX.
  2. Verify your application layout:
    In app/views/layouts/application.html.erb, ensure you have:
    <%= javascript_include_tag "application", type: "module", defer: true %>
  3. Mount the React component:
    Replace (or add) a div placeholder in an ERB view, e.g. app/views/home/index.html.erb:<div id="hello-react" data-props="{}"></div>
  4. Initialize mount point
    In app/javascript/application.js:
import "./components"

In app/javascript/components/index.js:

import React from "react"
import { createRoot } from "react-dom/client"
import HelloReact from "./HelloReact"

document.addEventListener("DOMContentLoaded", () => {
  const container = document.getElementById("hello-react")
  if (container) {
    const root = createRoot(container)
    const props = JSON.parse(container.dataset.props || "{}")
    root.render(<HelloReact {...props} />)
  }
})

Your React component will now render within the Rails view!

See you in Part 2 … 🚀

Setup 🛠 Rails 8 App – Part 16: Implementing Authentication, Users, Orders, and Order Items

Let’s now move onto create Authentication for our application.

Modern e‑commerce applications need robust user authentication, clear role‑based access, and an intuitive ordering system. In this post, we’ll walk through how to:

  1. Add Rails’ built‑in authentication via has_secure_password.
  2. Create a users table with roles for customers and admins.
  3. Build an orders table to capture overall transactions.
  4. Create order_items to track each product variant in an order.

Throughout, we’ll leverage PostgreSQL’s JSONB for flexible metadata, and we’ll use Rails 8 conventions for migrations and models.


Automatic Authentication For Rails 8 Apps

bin/rails generate authentication

This creates all the necessary files for users and sessions.

Create Authentication Manually

1. Create users table and user model

✗ rails g migration create_users

# users migration
class CreateUsers < ActiveRecord::Migration[8.0]
  def change
    create_table :users do |t|
      t.string   :email,           null: false, index: { unique: true }
      t.string   :password_digest, null: false
      t.string   :role,            null: false, default: "customer"
      t.string   :first_name
      t.string   :last_name
      t.jsonb    :metadata,        null: false, default: {}
      t.timestamps
    end

    # You can later set up an enum in the User model:
    # enum role: { customer: "customer", admin: "admin" }
  end
end

✗ rails g model user

# User model
class User < ApplicationRecord
  has_secure_password
  enum :role, {
    customer:  "customer",  
    admin:     "admin"      
  }
  has_many :orders
end

2. Authenticating with has_secure_password

Rails ships with bcrypt support out of the box. To enable it:

  1. Uncomment the following line in your Gemfile.
    # gem "bcrypt", "~> 3.1.7"
  2. Run bundle install.
  3. In your migration, create a password_digest column:
create_table :users do |t|
  t.string :email,           null: false, index: { unique: true }
  t.string :password_digest, null: false
  # ... other fields ...
end

  1. In app/models/user.rb, enable:
class User < ApplicationRecord
  has_secure_password
  # ...
end

This gives you user.authenticate(plain_text_password) and built‑in validation that a password is present on create.

3. Setting Up Users with Roles

We often need both customers and admins. Let’s create a role column with a default of "customer":

create_table :users do |t|
  t.string :role, null: false, default: "customer"
  # ...
end

In the User model you can then define an enum:

class User < ApplicationRecord
  ......
  enum :role, {
    customer:  "customer",  
    admin:     "admin"      
  }
end

This lets you call current_user.admin? or User.customers for scopes.

user.customer!   # sets role to "customer"
user.admin?      # => false

Rails built-in enum gives you a quick way to map a column to a fixed set of values, and it:

  1. Defines predicate and bang methods
  2. Adds query scopes
  3. Provides convenient helpers for serialization, validations, etc.

4. Building the Orders Table

Every purchase is represented by an Order. Key fields:

  • user_id (foreign key)
  • total_price (decimal with scale 2)
  • status (string; e.g. pending, paid, shipped)
  • shipping_address (JSONB): allows storing a full address object with flexible fields (street, city, postcode, country, and even geolocation) without altering your schema. You can index JSONB columns (GIN) to efficiently query nested fields, and you avoid creating a separate addresses table unless you need relationships or reuse.
  • placed_at (datetime, optional): records the exact moment the order was completed, independent of when the record was created. Making this optional lets you distinguish between draft/in-progress orders (no placed_at yet) and finalized purchases.
  • Timestamps
  • placed_at (datetime, optional): records the exact moment the order was completed, independent of when the record was created. Making this optional lets you distinguish between draft/in-progress orders (no placed_at yet) and finalized purchases.
  • Timestamps and an optional placed_at datetime
✗ rails g migration create_orders

# orders migration
class CreateOrders < ActiveRecord::Migration[8.0]
  def change
    create_table :orders do |t|
      t.references :user, null: false, foreign_key: true, index: true
      t.decimal    :total_price, precision: 12, scale: 2, null: false, default: 0.0
      t.string     :status,      null: false, default: "pending", index: true
      t.jsonb      :shipping_address, null: false, default: {}
      t.datetime   :placed_at
      t.timestamps
    end

    # Example statuses: pending, paid, shipped, cancelled
  end
end

In app/models/order.rb:

✗ rails g model order

class Order < ApplicationRecord
  belongs_to :user
  has_many   :order_items, dependent: :destroy
  has_many   :product_variants, through: :order_items

  STATUSES = %w[pending paid shipped cancelled]
  validates :status, inclusion: { in: STATUSES }
end

5. Capturing Each Item: order_items

To connect products to orders, we use an order_items join table. Each row stores:

  • order_id and product_variant_id as FKs
  • quantity, unit_price, and any discount_percent
  • Optional JSONB metadata for special instructions
✗ rails g migration create_order_items

# order_items migration
class CreateOrderItems < ActiveRecord::Migration[8.0]
  def change
    create_table :order_items do |t|
      t.references :order,           null: false, foreign_key: true, index: true
      t.references :product_variant, null: false, foreign_key: true, index: true
      t.integer    :quantity,        null: false, default: 1
      t.decimal    :unit_price,      precision: 10, scale: 2, null: false
      t.decimal    :discount_percent, precision: 5, scale: 2, default: 0.0
      t.jsonb      :metadata,        null: false, default: {}
      t.timestamps
    end

    # Composite unique index to prevent duplicate variant per order
    add_index :order_items, [:order_id, :product_variant_id], unique: true, name: "idx_order_items_on_order_and_variant"
  end

Model associations:

✗ rails g model order_item

class OrderItem < ApplicationRecord
  belongs_to :order
  belongs_to :product_variant

  validates :quantity, numericality: { greater_than: 0 }
end

6. Next Steps: Controllers & Authorization

  • Controllers: Scaffold UsersController, SessionsController (login/logout), OrdersController, and nested OrderItemsController under orders or use a service object to build carts.
  • Authorization: Once role is set, integrate Pundit or CanCanCan to restrict admin actions (creating products, managing variants) and customer actions (viewing own orders).
  • Views/Frontend: Tie it all together with forms for signup/login, a product catalog with “Add to Cart”, a checkout flow, and an admin dashboard for product management.

7. Scaffolding Controllers & Views (TailwindCSS Rails 4.2.3)

Generate Controllers & Routes

✗ rails generate controller Users new create index show edit update destroy --skip-routes
create  app/controllers/users_controller.rb
      invoke  tailwindcss
      create    app/views/users
      create    app/views/users/new.html.erb
      create    app/views/users/create.html.erb
      create    app/views/users/index.html.erb
      create    app/views/users/show.html.erb
      create    app/views/users/edit.html.erb
      create    app/views/users/update.html.erb
      create    app/views/users/destroy.html.erb
      invoke  test_unit
      create    test/controllers/users_controller_test.rb
      invoke  helper
      create    app/helpers/users_helper.rb
      invoke    test_unit
✗ rails generate controller Sessions new create destroy --skip-routes
create  app/controllers/sessions_controller.rb
      invoke  tailwindcss
      create    app/views/sessions
      create    app/views/sessions/new.html.erb
      create    app/views/sessions/create.html.erb
      create    app/views/sessions/destroy.html.erb
      invoke  test_unit
      create    test/controllers/sessions_controller_test.rb
      invoke  helper
      create    app/helpers/sessions_helper.rb
      invoke    test_unit
✗ rails generate controller Orders index show new create edit update destroy --skip-routes
      create  app/controllers/orders_controller.rb
      invoke  tailwindcss
      create    app/views/orders
      create    app/views/orders/index.html.erb
      create    app/views/orders/show.html.erb
      create    app/views/orders/new.html.erb
      create    app/views/orders/create.html.erb
      create    app/views/orders/edit.html.erb
      create    app/views/orders/update.html.erb
      create    app/views/orders/destroy.html.erb
      invoke  test_unit
      create    test/controllers/orders_controller_test.rb
      invoke  helper
      create    app/helpers/orders_helper.rb
      invoke    test_unit
 ✗ rails generate controller OrderItems create update destroy --skip-routes
      create  app/controllers/order_items_controller.rb
      invoke  tailwindcss
      create    app/views/order_items
      create    app/views/order_items/create.html.erb
      create    app/views/order_items/update.html.erb
      create    app/views/order_items/destroy.html.erb
      invoke  test_unit
      create    test/controllers/order_items_controller_test.rb
      invoke  helper
      create    app/helpers/order_items_helper.rb
      invoke    test_unit

In config/routes.rb, nest order_items under orders and add session routes:

Rails.application.routes.draw do
  resources :users
n
  resources :sessions, only: %i[new create destroy]
  get    '/login',  to: 'sessions#new'
  post   '/login',  to: 'sessions#create'
  delete '/logout', to: 'sessions#destroy'

  resources :orders do
    resources :order_items, only: %i[create update destroy]
  end

  root 'products#index'
end

By the end, you’ll have a fully functional e‑commerce back end: secure auth, order tracking, and clear user roles.


How to setup your First User🙍🏻‍♂️ in the system

The very first user you should set up is:

An admin user — to create/manage products, variants, and handle backend tasks.

Here’s the best approach:

Best Practice: Seed an Admin User

Instead of manually creating it through the UI (when no one can log in yet), the best and safest approach is to use db/seeds.rb to create an initial admin user.

Why?

  • You can reliably recreate it on any environment (local, staging, production).
  • You can script strong defaults (like setting a secure admin email/password).

🔒 Tip: Use ENV Variables

For production, never hardcode admin passwords directly in seeds.rb. Instead, do:

admin_password = ENV.fetch("ADMIN_PASSWORD")

and pass it as:

ADMIN_PASSWORD=SomeStrongPassword rails db:seed

This keeps credentials out of your Git history.

🛠 Option 1: Add Seed Data db/seeds.rb

Add a block in db/seeds.rb that checks for (or creates) an admin user:

# db/seeds.rb

email    = ENV.fetch("ADMIN_EMAIL") { abort "Set ADMIN_EMAIL" }
password = ENV.fetch("ADMIN_PASSWORD") { abort "Set ADMIN_PASSWORD" }

User.find_or_create_by!(email: admin_email) do |user|
  user.password              = admin_password
  user.password_confirmation = admin_password
  user.role                   = "admin"
  user.first_name             = "Site"
  user.last_name              = "Admin"
end

puts "→ Admin user: #{admin_email}"

Then run:

rails db:seed
  1. Pros:
    • Fully automated and idempotent—you can run db:seed anytime without creating duplicates.
    • Seed logic lives with your code, so onboarding new team members is smoother.
    • You can wire up ENV vars for different credentials in each environment (dev/staging/prod).
  2. Cons:
    • Seeds can get cluttered over time if you add lots of test data.
    • Must remember to re-run seeds after resetting the database.

🛠 Option 2: Custom Rake task or Thor script

Create a dedicated task under lib/tasks/create_admin.rake:

namespace :admin do
  desc "Create or update the first admin user"
  task create: :environment do
    email    = ENV.fetch("ADMIN_EMAIL")    { abort "Set ADMIN_EMAIL" }
    password = ENV.fetch("ADMIN_PASSWORD") { abort "Set ADMIN_PASSWORD" }

    user = User.find_or_initialize_by(email: email)
    user.password              = password
    user.password_confirmation = password
    user.role                   = "admin"
    user.save!

    puts "✅ Admin user #{email} created/updated"
  end
end

Run it with:

ADMIN_EMAIL=foo@bar.com ADMIN_PASSWORD=topsecret rails admin:create
  1. Pros:
    • Keeps seed file lean—admin-creation logic lives in a focused task.
    • Enforces presence of ENV vars (you won’t accidentally use a default password in prod).
  2. Cons:
    • Slightly more setup than plain seeds, though it’s still easy to run.

I choose for Option 2, because it is namespaced and clear what is the purpose. But in seed there will be lot of seed data together make it difficult to identify a particular task.

🛡 Why is This Better?

✅ No need to expose a sign-up page to create the very first admin.
✅ You avoid manual DB entry or Rails console commands.
✅ You can control/rotate the admin credentials easily.
✅ You can add additional seed users later if needed (for demo or testing).

📝 Summary

Seed an initial admin user
✅ Add a role check (admin? method)
✅ Lock down sensitive parts of the app to admin
✅ Use ENV vars in production for passwords


Enjoy Rails 🚀!

Setup 🛠 Rails 8 App – Part 15: Set Up CI/CD ⚙️ with GitHub Actions for Rails 8

Prerequisites

Our System Setup

  • Ruby version: 3.4.1
  • Rails version: 8.0.2
  • JavaScript tooling: using rails default tubo-stream, NO nodeJS or extra js

We would love to see:

  • RuboCop linting Checks
  • SimpleCov test coverage report
  • Brakeman security scan

Here’s how to set up CI that runs on every push, including pull requests:

1. Create GitHub Actions Workflow

Create this file: .github/workflows/ci.yml

name: Rails CI

# Trigger on pushes to main or any feature branch, and on PRs targeting main
on:
  push:
    branches:
      - main
      - 'feature/**'
  pull_request:
    branches:
      - main

jobs:
  # 1) Lint job with RuboCop
  lint:
    name: RuboCop Lint
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 3.4.1
          bundler-cache: true

      - name: Install dependencies
        run: |
          sudo apt-get update -y
          sudo apt-get install -y libpq-dev
          bundle install --jobs 4 --retry 3

      - name: Run RuboCop
        run: bundle exec rubocop --fail-level E

  # 2) Test job with Minitest
  test:
    name: Minitest Suite
    runs-on: ubuntu-latest
    needs: lint

    services:
      postgres:
        image: postgres:15
        ports:
          - 5432:5432
        env:
          POSTGRES_PASSWORD: password
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    env:
      RAILS_ENV: test
      DATABASE_URL: postgres://postgres:password@localhost:5432/test_db

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 3.4.1
          bundler-cache: true

      - name: Install dependencies
        run: |
          sudo apt-get update -y
          sudo apt-get install -y libpq-dev
          bundle install --jobs 4 --retry 3

      - name: Set up database
        run: |
          bin/rails db:create
          bin/rails db:schema:load

      - name: Run Minitest
        run: bin/rails test
  # 3) Security job with Brakeman
  security:
    name: Brakeman Scan
    runs-on: ubuntu-latest
    needs: [lint, test]

    steps:
      - uses: actions/checkout@v3
      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 3.4.1
          bundler-cache: true

      - name: Install Brakeman
        run: bundle install --jobs 4 --retry 3

      - name: Run Brakeman
        run: bundle exec brakeman --exit-on-warnings

How this works:

  1. on.push & on.pull_request:
    • Runs on any push to main or feature/**, and on PRs targeting main.
  2. lint job:
    • Checks out code, sets up Ruby 3.4.1, installs gems (with bundler-cache), then runs bundle exec rubocop --fail-level E to fail on any error-level offenses.
  3. test job:
    • Depends on the lint job (needs: lint), so lint must pass first.
    • Spins up a PostgreSQL 15 service, sets DATABASE_URL for Rails, creates & loads the test database, then runs your Minitest suite with bin/rails test.

🛠 What Does .github/dependabot.yml Do?

This YAML file tells Dependabot:
♦️ Which dependencies to monitor
♦️ Where (which directories) to look for manifest files
♦️ How often to check for updates
♦️ What package ecosystems (e.g., RubyGems, npm, Docker) are used
♦️ Optional rules like versioning, reviewer assignment, and update limits

Dependabot then opens automated pull requests (PRs) in your repository when:

  • There are new versions of dependencies
  • A security advisory affects one of your dependencies

This helps you keep your app up to date and secure without manual tracking.

🏗 Example: Typical .github/dependabot.yml

Here’s a sample for a Ruby on Rails app:

version: 2
updates:
  - package-ecosystem: bundler
    directory: "/"
    schedule:
      interval: weekly
    open-pull-requests-limit: 5
    rebase-strategy: auto
    ignore:
      - dependency-name: rails
        versions: ["7.x"]
  - package-ecosystem: github-actions
    directory: "/"
    schedule:
      interval: weekly

♦️ Place the .github/dependabot.yml file in the .github directory of your repo root.
♦️ Tailor the schedule and limits to your team’s capacity.
♦️ Use the ignore block carefully if you deliberately skip certain updates (e.g., major version jumps).
♦️ Combine it with branch protection rules so Dependabot PRs must pass tests before merging.

🚀 Steps to Push and Test Your CI

You can push both files (ci.yml and dependabot.yml) together in one commit

Here’s a step-by-step guide for testing that your CI works right after the push.

1️⃣ Stage and commit your files

git add .github/workflows/ci.yml .github/dependabot.yml
git commit -m 'feat: Add github actions CI workflow Close #23'

2️⃣ Push to a feature branch
(for example, if you’re working on feature/github-ci):

git push origin feature/github-ci

3️⃣ Open a Pull Request

  • Go to GitHub → your repository → create a pull request from feature/github-ci to main.

4️⃣ Watch GitHub Actions run

  • Go to the Pull Request page.
  • You should see a yellow dot / pending check under “Checks”.
  • Click the “Details” link next to the check (or go to the Actions tab) to see live logs.

✅ How to Know It’s Working

✔️ If all your jobs (e.g., RuboCop Lint, Minitest Suite) finish with green checkmarks, your CI setup is working!

❌ If something fails, you’ll get a red X and the logs will show exactly what failed.

So what’s the problem. Check details.

Check brakeman help for further information about the option.

➜  design_studio git:(feature/github-ci) brakeman --help | grep warn
    -z, --[no-]exit-on-warn          Exit code is non-zero if warnings found (Default)
        --ensure-ignore-notes        Fail when an ignored warnings does not include a note

Modify the option and run again:

run: bundle exec brakeman --exit-on-warn

Push the code and check all checks are passing. ✅

🛠 How to Test Further

If you want to trigger CI without a PR, you can push directly to main:

git checkout main
git merge feature/setup-ci
git push origin main

Note: Make sure your .github/workflows/ci.yml includes:

on:
  push:
    branches: [main, 'feature/**']
  pull_request:
    branches: [main]

This ensures CI runs on both pushes and pull requests.

🧪 Pro Tip: Break It Intentionally

If you want to see CI fail, you can:

  • Add a fake RuboCop error (like an unaligned indent).
  • Add a failing test (assert false).
  • Push and watch the red X appear.

This is a good way to verify your CI is catching problems!


Happy Rails CI setup! 🚀

Rails 8 App: Adding SimpleCov 🧾 & Brakeman 🔰 To Our Application For CI/CD Setup

Ensuring code quality and security in a Rails application is critical – especially as your project grows. In this post, we’ll walk through integrating two powerful tools into your Rails 8 app:

  1. SimpleCov: for measuring and enforcing test coverage
  2. Brakeman: for automated static analysis of security vulnerabilities

By the end, you’ll understand why each tool matters, how to configure them, and the advantages they bring to your development workflow.

Why Code Coverage & Security Scanning Matter

  • Maintainability
    Tracking test coverage ensures critical paths are exercised by your test suite. Over time, you can guard against regressions and untested code creeping in.
  • Quality Assurance
    High coverage correlates with fewer bugs: untested code is potential technical debt. SimpleCov gives visibility into what’s untested.
  • Security
    Rails apps can be vulnerable to injection, XSS, mass assignment, and more. Catching these issues early, before deployment, dramatically reduces risk.
  • Compliance & Best Practices
    Many organizations require minimum coverage thresholds and regular security scans. Integrating these tools automates compliance.

Part 1: Integrating SimpleCov for Test Coverage

1. Add the Gem

In your Gemfile, under the :test group, add:

group :test do
  gem 'simplecov', require: false
end

Then run:

bundle install

2. Configure SimpleCov

Create (or update) test/test_helper.rb (for Minitest) before any application code is loaded:

require 'simplecov'
SimpleCov.start 'rails' do
  coverage_dir 'public/coverage'           # output directory
  minimum_coverage 90               # fail if coverage < 90%
  add_filter '/test/'               # ignore test files themselves
  add_group 'Models', 'app/models'
  add_group 'Controllers', 'app/controllers'
  add_group 'Jobs', 'app/jobs'
  add_group 'Libraries', 'lib'
end

# Then require the rest of your test setup
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
# ...

Tip: You can customize groups, filters, and thresholds. If coverage dips below the set minimum, your CI build will fail.

Note: coverage_dir should be modified to public/coverage. Else you cannot access the html publically.

3. Run Your Tests & View the Report

✗ bin/rails test
≈ tailwindcss v4.1.3

Done in 46ms
Running 10 tests in a single process (parallelization threshold is 50)
Run options: --seed 63363

# Running:

..........

Finished in 0.563707s, 17.7397 runs/s, 60.3150 assertions/s.
10 runs, 34 assertions, 0 failures, 0 errors, 0 skips
Coverage report generated for Minitest to /Users/abhilash/rails/design_studio/public/coverage.
Line Coverage: 78.57% (88 / 112)
Line coverage (78.57%) is below the expected minimum coverage (90.00%).
SimpleCov failed with exit 2 due to a coverage related error

Once tests complete, open http://localhost:3000/coverage/index.html#_AllFiles in your browser:

  • A color-coded report shows covered (green) vs. missed (red) lines.
  • Drill down by file or group to identify untested code.

We get 78.57% only coverage and our target is 90% coverage. Let’s check where we missed the tests. ProductsController 82%. We missed coverage for #delete_image action. Let’s add it and check again.

Let’s add Product Controller json requests test cases for json error response and add the ApplicationControllerTest for testing root path.

Now we get: 88.3%

Now we have to add some Test cases for Product model.

Now we get: 92.86% ✅

4. Enforce in CI

In your CI pipeline (e.g. GitHub Actions), ensure:

- name: Run tests with coverage
  run: |
    bundle exec rails test
    # Optionally upload coverage to Coveralls or Codecov

If coverage < threshold, the job will exit non-zero and fail.


Part 2: Incorporating Brakeman for Security Analysis

1. Add Brakeman to Your Development Stack

You can install Brakeman as a gem (development-only) or run it via Docker/CLI. Here’s the gem approach:

group :development do
  gem 'brakeman', require: false
end

Then:

bundle install

2. Basic Usage

From your project root, simply run:

✗ bundle exec brakeman

Generating report...

== Brakeman Report ==

Application Path: /Users/abhilash/rails/design_studio
Rails Version: 8.0.2
Brakeman Version: 7.0.2
Scan Date: 2025-05-07 11:06:36 +0530
Duration: 0.35272 seconds
Checks Run: BasicAuth, BasicAuthTimingAttack, CSRFTokenForgeryCVE, ....., YAMLParsing

== Overview ==

Controllers: 2
Models: 3
Templates: 12
Errors: 0
Security Warnings: 0

== Warning Types ==


No warnings found

By default, Brakeman:

  • Scans app/, lib/, config/, etc.
  • Outputs a report in the terminal and writes brakeman-report.html.

3. Customize Your Scan

Create a config/brakeman.yml to fine-tune:

ignored_files:
  - 'app/controllers/legacy_controller.rb'
checks:
  - mass_assignment
  - cross_site_scripting
  - sql_injection
skip_dev: true                 # ignores dev-only gems
quiet: true                     # suppress verbose output

Run with:

bundle exec brakeman -c config/brakeman.yml -o public/security_report.html

Theconfig/brakeman.yml file is not added by default. You can add the file by copying the contents from: https://gist.github.com/abhilashak/038609f1c35942841ff8aa5e4c88b35b

Check: http://localhost:3000/security_report.html

4. CI Integration

In GitHub Actions:

- name: Run Brakeman security scan
  run: |
    bundle exec brakeman -q -o brakeman.json
- name: Upload Brakeman report
  uses: actions/upload-artifact@v3
  with:
    name: security-report
    path: brakeman.json

Optionally, you can fail the build if new warnings are introduced by comparing against a baseline report.


Advantages of Using SimpleCov & Brakeman Together

AspectSimpleCovBrakeman
PurposeTest coverage metricsStatic security analysis
Fail-fastFails when coverage drops below thresholdCan be configured to fail on new warnings
VisibilityColorized HTML coverage reportDetailed HTML/JSON vulnerability report
CI/CD ReadyIntegrates seamlessly with most CI systemsCLI-friendly, outputs machine-readable data
CustomizableGroups, filters, thresholdsChecks selection, ignored files, baseline

Together, they cover two critical quality dimensions:

  1. Quality & Maintainability (via testing)
  2. Security & Compliance (via static analysis)

Automating both checks in your pipeline means faster feedback, fewer production issues, and higher confidence when shipping code.


Best Practices & Tips

  • Threshold for SimpleCov: Start with 80%, then gradually raise to 90–95% over time.
  • Treat Brakeman Warnings Seriously: Not all findings are exploitable, but don’t ignore them—triage and document why you’re suppressing any warning.
  • Baseline Approach: Use a baseline report for Brakeman so your build only fails on newly introduced warnings, not historical ones.
  • Schedule Periodic Full Scans: In addition to per-PR scans, run a weekly scheduled Brakeman job to catch issues from merged code.
  • Combine with Other Tools: Consider adding gem like bundler-audit for known gem vulnerabilities.

Conclusion

By integrating SimpleCov and Brakeman into your Rails 8 app, you establish a robust safety net that:

  • Ensures new features are properly tested
  • Keeps an eye on security vulnerabilities
  • Automates quality gates in your CI/CD pipeline

These tools are straightforward to configure and provide immediate benefits – improved code confidence, faster code reviews, and fewer surprises in production. Start today, and make code quality and security first-class citizens in your Rails workflow!

Happy Rails CI/CD Integration .. 🚀