Muhammad Fari Madyan
Hire me
Rails · part 4 of 5

Ruby on Rails 8 & React E-Learning Part 4: High-Throughput Data Ingestion with Roo & DevSecOps Security Hardening

Master bulk spreadsheet data ingestion and automated security analysis in Ruby on Rails 8: parsing student rosters and question banks with the Roo gem, atomic database transactions, stateless JWT admin impersonation, and automated DevSecOps with Brakeman and Bundler-Audit.

Muhammad Fari Madyan

· 6 min read

Baca dalam Bahasa Indonesia →

Enterprise Ingestion & DevSecOps Priorities

In high-concurrency educational platforms, administrative operations oscillate between two extremes:

  1. Massive Bulk Ingestion: At the start of an academic semester, administrators upload spreadsheets with 2,000+ enrolled students, and teachers upload standardized test question banks with hundreds of items and complex answer options.
  2. Strict Security Verification: Academic systems manage sensitive student personal data (NISN, parent contacts, addresses). Any vulnerability, such as insecure direct object references (IDOR), SQL injection, or unpatched vulnerabilities in gem dependencies, can compromise an entire institution.

In mfarim/ruby-rails-elearning-react, we hardened the application with two core architectural pillars:

  • Resilient Spreadsheet Ingestion: The lightweight roo gem combined with atomic Active Record transactions.
  • Continuous DevSecOps: Static application security testing (SAST) with Brakeman, automated gem vulnerability auditing with Bundler-Audit, and Rails 8's native ActiveSupport::ContinuousIntegration pipeline.
┌────────────────────────────────────────────────────────────────────────────────────────┐ │ DATA INGESTION & DEVSECOPS PIPELINE │ └────────────────────────────────────────────────────────────────────────────────────────┘ 📥 Admin uploads .xlsx / .xls / .csv Spreadsheet │ ▼ Multipart Form Upload ┌──────────────────────────────────────────────────────────────────────────────────┐ │ EXCEL SERVICE (Roo Reader): │ │ • Polymorphic adapter: Roo::Excelx, Roo::Excel, Roo::CSV │ │ • Collects each row as a hash (synchronous, inside the request) │ │ • Header normalization (.to_s.strip.downcase.underscore) │ └───────────────────────┬──────────────────────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────────────────────────┐ │ ATOMIC DATABASE TRANSACTION (ActiveRecord::Base.transaction): │ │ • Upserts User records with secure BCrypt hashes │ │ • Associates Student records with Classrooms │ │ • Automatic rollback if constraint violation occurs (Zero partial data) │ └──────────────────────────────────────────────────────────────────────────────────┘ 🛡️ CONTINUOUS SECURITY AUTOMATION (bin/ci): ┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────────┐ │ RuboCop Linter │──▶│ Bundler-Audit (CVEs) │──▶│ Brakeman SAST Scan │ │ Style & Best Practice│ │ Checks vulnerable gems│ │ Checks code injection│ └───────────────────────┘ └───────────────────────┘ └───────────────────────┘

1. High-Throughput Spreadsheet Parsing with the roo Gem

In backend/app/services/excel_service.rb, we built an ingestion service that handles .xlsx, .xls, and .csv files interchangeably:

RUBY
# backend/app/services/excel_service.rb
require 'roo'

class ExcelService
  def self.parse_students(file_path)
    spreadsheet = open_spreadsheet(file_path)
    header = spreadsheet.row(1).map { |h| h.to_s.strip.downcase.underscore }
    rows = []

    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      next if row['name'].blank? || row['nis'].blank?
      rows << row
    end

    rows
  end

  def self.parse_questions(file_path)
    spreadsheet = open_spreadsheet(file_path)
    header = spreadsheet.row(1).map { |h| h.to_s.strip.downcase.underscore }
    rows = []

    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      next if row['question_text'].blank?
      rows << row
    end

    rows
  end

  private

  def self.open_spreadsheet(file_path)
    ext = File.extname(file_path).downcase
    case ext
    when '.xlsx'
      Roo::Excelx.new(file_path)
    when '.xls'
      Roo::Excel.new(file_path)
    when '.csv'
      Roo::CSV.new(file_path)
    else
      raise "Unsupported file format: #{ext}. Please upload .xlsx, .xls, or .csv"
    end
  end
end

Why Roo Beats Other Spreadsheet Gems:

Traditional spreadsheet parsers build complex in-memory object graphs for cell formatting, styles, and font metrics. For a 2,000-row student roster, that uses far too much memory. Roo reads raw values row by row, which keeps parsing lighter. This service still collects every row into an array and runs synchronously inside the request, though, so memory grows with the workbook and the import holds a Puma thread until it finishes. For large files, move the import into a background job (Active Job with Solid Queue).


2. Atomic Database Ingestion with Active Record Transactions

In backend/app/controllers/api/v1/students_controller.rb, imported records are saved inside an atomic database transaction. If row #1,999 has an invalid email format or a duplicate student ID, the entire batch rolls back so no corrupt data is left behind:

RUBY
# In backend/app/controllers/api/v1/students_controller.rb
def import_excel
  require_admin!
  return if performed?

  file = params[:file]
  raise "No file provided" unless file.present?

  records = ExcelService.parse_students(file.path)
  imported_count = 0

  ActiveRecord::Base.transaction do
    records.each do |row|
      # 1. Provision user account
      user = User.find_or_initialize_by(email: row['email'].downcase.strip)
      user.name = row['name'].strip
      user.password = "password" if user.new_record?
      user.role = "student"
      user.active = true
      user.save!

      # 2. Provision associated student profile
      student = Student.find_or_initialize_by(user: user)
      student.nis = row['nis'].to_s.strip
      student.nisn = row['nisn'].to_s.strip if row['nisn'].present?
      student.classroom_id = params[:classroom_id] if params[:classroom_id].present?
      student.gender = row['gender'].to_s.upcase.in?(%w[L P M F]) ? row['gender'].to_s.upcase : 'L'
      student.phone = row['phone']
      student.address = row['address']
      student.save!

      imported_count += 1
    end
  end

  json_response(data: { imported: imported_count }, message: "Successfully imported #{imported_count} students")
rescue => e
  json_response(success: false, message: "Import aborted: #{e.message}", status: :unprocessable_entity)
end

3. Stateless JWT Admin Impersonation

In backend/app/controllers/api/v1/auth_controller.rb, administrators can impersonate any student or teacher to diagnose issues without asking for passwords:

RUBY
# backend/app/controllers/api/v1/auth_controller.rb
def impersonate
  require_admin!
  return if performed?

  target_user = user_repository.find(params[:user_id])
  token = JsonWebToken.encode(user_id: target_user.id, impersonated_by: current_user.id)
  payload = build_auth_payload(target_user, token, impersonated_by: current_user.id)
  json_response(data: payload, message: "Impersonation started successfully")
end

def stop_impersonate
  claims = JsonWebToken.decode(request.headers["Authorization"].to_s.split.last)
  admin_user = user_repository.find_by(id: claims&.dig(:impersonated_by), role: 'ROLE_ADMIN')
  return render_error("No active impersonation session", status: :forbidden) unless admin_user

  token = JsonWebToken.encode(user_id: admin_user.id)
  payload = build_auth_payload(admin_user, token)
  json_response(data: payload, message: "Returned to admin session")
end

Security Benefits of This Implementation:

  1. Zero Stateful Server Sessions: Authentication remains strictly stateless. The React frontend stores the token and shows a persistent banner warning that impersonation is active.
  2. One-Click Session Restoration: Calling stop_impersonate mints a fresh token for the original administrator, read from the token's impersonated_by claim, with no need to re-enter a password.

4. Rails 8 DevSecOps: Brakeman & Bundler-Audit

In modern Rails, security auditing is built directly into the CI pipeline. It lives in backend/bin/ci and backend/config/ci.rb:

RUBY
# backend/config/ci.rb
CI.run do
  step "Setup", "bin/setup --skip-server"
  step "Style: Ruby", "bin/rubocop"
  step "Security: Gem audit", "bin/bundler-audit"
  step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error"
end

Static Application Security Testing (SAST) with Brakeman

Brakeman statically inspects the Abstract Syntax Tree (AST) of the Rails codebase without needing database connections:

  • Mass Assignment Vulnerabilities: Flags unpermitted strong parameters.
  • SQL Injection: Detects raw SQL string interpolations.
  • Cross-Site Scripting (XSS): Identifies unescaped outputs.

Running bin/brakeman confirms that all controller endpoints and repositories meet a zero-warning standard:

BASH
$ bin/brakeman --quiet --exit-on-warn
== Brakeman Report ==
Security Warnings: 0
Checks run: 74
No vulnerabilities found!

Dependency Auditing with Bundler-Audit

Bundler-Audit compares the project's Gemfile.lock against the Ruby Advisory Database. If any third-party gem has an unpatched Common Vulnerabilities and Exposures (CVE) entry, bin/ci fails immediately, so vulnerable dependencies never reach production.


Key Takeaways for Engineering Leads

  1. Use Roo for lightweight spreadsheet ingestion: Reading raw cell values keeps parsing lean. For large imports, run the work in a background job (Active Job with Solid Queue) instead of inside the request.
  2. Wrap bulk operations in database transactions: ActiveRecord::Base.transaction ensures that spreadsheet syntax errors or duplicate records never leave partial, corrupted data behind.
  3. Automate DevSecOps in bin/ci: Integrating Brakeman and Bundler-Audit into Rails 8's native CI runner means the security checks run every time bin/ci runs, whether in your CI pipeline or from a pre-commit hook.

In the final part, Part 5, we cover production deployment: Single VPS Production Deployment, Multi-Container Docker Compose, Puma Multithreading Tuning, and Auto-Recovery Health Monitoring Scripts.

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 3High-Precision CBT Exam Engine & Real-Time Action Cable Proctoringpart 5 →Single VPS Production Deployment

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan