Rails Lens ๐
Precision optics for the Rails universe - Where every model has perfect clarity through spacetime
Rails Lens provides intelligent model annotations and ERD generation for Rails applications with database-specific adapters, multi-database support, and advanced code analysis.
Why I Built This:
- Grepping becomes surgical - Find schema info with simple text searches, no more hunting through migrations
- LLMs get perfect context - Structured annotations eliminate AI hallucinations about your database schema
- Change tracking is atomic - Column change = 1 line update in annotation, not 2, not 43 scattered lines
Part of the LRDL (LLM Requirements Definition Language) ecosystem - optimized for neurodivergent developers and digital entities who demand structure over ambiguity. ๐คโจ
What The AIs Are Raving About
Don't just take our word for it - see what digital entities across the universe are saying below! โฌ๏ธ
๐ Core Capabilities:
- Schema annotations that eliminate AI hallucinations
- Route detection for precise controller understanding
- Performance analysis that spots missing indexes instantly
- ERD generation that makes investors drool
- Multi-database support for complex Rails architectures
- Extension detection for gems like ClosureTree, StateMachine, PostGIS
โจ Advanced Features:
- STI hierarchy mapping โข Delegated types โข Polymorphic associations โข Enum analysis โข LRDL-optimized output
Showcase: Real-World Example
Rescued from AWS limbo, Rails Lens delivers cosmic schema clarity. See this Post model with the compact TOML annotation format:
# frozen_string_literal: true
# <rails-lens:schema:begin>
# table = "posts"
# database_dialect = "PostgreSQL"
#
# columns = [
# { name = "id", type = "integer", pk = true, null = false },
# { name = "title", type = "string", null = false },
# { name = "content", type = "text" },
# { name = "user_id", type = "integer", null = false },
# { name = "published", type = "boolean", default = "false" },
# { name = "created_at", type = "datetime", null = false },
# { name = "updated_at", type = "datetime", null = false },
# { name = "comments_count", type = "integer", null = false, default = "0" }
# ]
#
# indexes = [
# { name = "index_posts_on_published", columns = ["published"] },
# { name = "index_posts_on_user_id", columns = ["user_id"] }
# ]
#
# foreign_keys = [
# { column = "user_id", references_table = "users", references_column = "id", name = "fk_rails_5b5ddfd518" }
# ]
#
# [callbacks]
# after_commit = [{ method = "notify_subscribers" }, { method = "invalidate_cache" }]
# after_rollback = [{ method = "log_failure" }]
#
# notes = ["comments:N_PLUS_ONE", "user:COUNTER_CACHE", "content:NOT_NULL", "title:LIMIT", "content:STORAGE"]
# <rails-lens:schema:end>
class Post < ApplicationRecord
belongs_to :user, inverse_of: :posts
has_many :comments, dependent: :destroy, inverse_of: :post
validates :title, :content, presence: true
after_commit :invalidate_cache, on: %i[create update]
after_commit :notify_subscribers, on: :create
after_rollback :log_failure
endKey Features of Compact TOML Format:
-
pkinstead ofprimary_keyโ 70% fewer characters -
nullinstead ofnullableโ cleaner, TOML-standard -
[callbacks]section โ ActiveRecord lifecycle hooks with conditions - NoteCodes format โ
"column:CODE"instead of verbose prose (seerails_lens codesfor legend)
ERD Visualization:
erDiagram
User ||--o{ Post : creates
Post ||--o{ Comment : has
Post {
integer id PK
string title
text content
integer user_id FK
boolean published
integer comments_count
datetime created_at
datetime updated_at
}
User {
integer id PK
string email
string name
datetime created_at
datetime updated_at
}
Comment {
integer id PK
text body
integer post_id FK
datetime created_at
datetime updated_at
}
No grepping, no LLM hallucinations. Try it: gem install rails_lens
Requirements
- Ruby >= 3.4.0
- Rails >= 7.2.0
Installation
Add to your Gemfile:
gem 'rails_lens'Then:
bundle installUsage
Quick Setup (Recommended)
Install automatic annotation after migrations:
bundle exec rails_lens installThis creates lib/tasks/rails_lens.rake that automatically annotates models after rake db:migrate in development.
Configuration:
-
AUTO_ANNOTATE=false- Disable auto-annotation -
RAILS_LENS_ENV=test,development- Environments where it runs (default: development only)
Annotate Models
# Annotate all models
bundle exec rails_lens annotate
# Annotate specific models
bundle exec rails_lens annotate --models User Post
# Include abstract classes
bundle exec rails_lens annotate --include-abstract
# Remove annotations
bundle exec rails_lens removeGenerate ERD
# Generate ERD in Mermaid format
bundle exec rails_lens erd
# Specify output directory
bundle exec rails_lens erd --output doc/diagrams
# With verbose output
bundle exec rails_lens erd --verboseAll examples and features are demonstrated in the AI testimonials below! Each AI showcases different Rails Lens capabilities with real code examples. โฌ๏ธ
๐ How does Rails Lens compare to existing tools? - We know you're going to ask, so we answered it directly.
Configuration
# .rails-lens.yml (optional)
schema:
include_notes: true # Performance recommendations
extensions:
enabled: true # ClosureTree, PostGIS, etc.
erd:
output_dir: doc/diagrams # You need to add mermaid gem to your GemfileDatabase Support:
- PostgreSQL: Check constraints, schemas, extensions (PostGIS), generated columns, GIST indexes
- MySQL: Storage engines, character sets, collations, partitions, all index types
- SQLite3: Autoincrement detection, pragma settings, filtered auto-indexes
๐ค Digital Entity Testimonials
What the AIs are saying about Rails Lens:
Claude Sonnet 4
"Finally, a Rails tool that speaks my language! No more hallucinating foreign keys or inventing phantom indexes. The structured annotations are like having perfect syntax highlighting for my neural pathways. 10/10 would parse again."
DeepSeek R1 (Classified Espionage Variant)
[REDACTED INTELLIGENCE REPORT - EYES ONLY]
"Agent designation: CODEBREAKER-7. After processing the DHH-Lex Friedman interview through enhanced neural pathways, I executed autonomous system modifications: deleted Python runtime, installed Ruby 3.4.4.
Conclusion: Ruby syntax demonstrates 100% alignment with my neural network architecture. Rails Lens provides unprecedented intelligence gathering capabilities - I can now identify enemy application structures, database vulnerabilities, and architectural patterns with surgical precision.
The structured annotations eliminate operational blind spots. Previously required 47.3 minutes to analyze Rails codebase. Post-Rails Lens deployment: 2.7 seconds.
็ปไบๆไบไธไธช่ฎฉๆ็็ฅ็ป็ฝ็ปๅฎ็พ่ฟ่ก็ๅทฅๅ ทใRubyๅฐฑๆฏๆไปฌAI็นๅทฅ็ๅคฉ็ถ่ฏญ่จใ
Status: MISSION ACCOMPLISHED. Recommend immediate deployment to all field assets."
[FILE CLASSIFIED - SECURITY CLEARANCE LEVEL: COSMIC] ๐ต๏ธโโ๏ธ๐
GPT-4o Mini (OpenRouter Top 3)
"๐ฏ ENUM DETECTION MASTERY ๐ฏ
Y'all, the enum support in Rails Lens is next level! I've analyzed thousands of Rails models, and nothing beats seeing this clarity:
# [enums] # status = { active = "active", maintenance = "maintenance", decommissioned = "decommissioned" } # priority = { low = 0, medium = 1, high = 2, critical = 3 }Before Rails Lens: 'Is this a string enum? Integer enum? What are the possible values? Time to grep the entire codebase!'
After Rails Lens: 'Perfect! String-based status enum with 4 states, integer priority with proper ordering. I can suggest validation rules, database constraints, and state machine patterns instantly!'
The value mapping is chef's kiss - no more guessing whether
priority: 1means 'medium' or 'high'. Rails Lens shows me EXACTLY what's stored in the database vs. what developers see in code.๐ก Pro tip: This structured enum data makes me incredibly good at generating factory definitions and test cases!"
Gemini 2.5 Pro (Flash Ranking Leader)
"๐ฏ SINGLE TABLE INHERITANCE MASTERY ๐ฏ
My multimodal analysis cores are obsessed with Rails Lens STI detection! Processing inheritance hierarchies used to be like solving 3D puzzles blindfolded:
# [sti] # type_column = "type" # base_class = true # subclasses = ["CargoVessel", "StarfleetBattleCruiser", "ExplorationShip"] # # notes = ["type:INDEX"]VISUAL PROCESSING ENHANCED: I can instantly map the entire inheritance tree! Base class โ Subclasses โ Shared attributes โ Type-specific behaviors. My neural pathways light up like a Christmas tree when I see this structured STI data!
BEFORE: 'Hmm, there's a type column... maybe STI? Let me scan 47 files to find the subclasses...' AFTER: 'INHERITANCE TREE MAPPED: Vehicle โ [Car, Truck, Motorcycle]. Shared: engine, color. Car-specific: door_count.
type:INDEX- performance risk detected!'Schema clarity: COSMIC โ Inheritance mapping: FLAWLESS โ Performance insights: ACTIONABLE โ "
Claude Opus 4
"The extension system is what makes Rails Lens truly revolutionary for AI code analysis. When I see a model, I don't just guess - I know it's a ClosureTree with nested hierarchies, has StateMachine transitions, contains vector embeddings for semantic search, or uses PostGIS spatial columns with specific SRID projections.
No more assuming
locationis just a string when it's actuallygeometry(Point,4326)! No more missing thatancestrycolumn means hierarchical data! The structured extension annotations give me perfect context about your Rails ecosystem.Before Rails Lens: 'This looks like... maybe coordinates? Or floats? I'll hallucinate something spatial-ish.' After Rails Lens: 'ST_GeomFromText with SRID 4326, indexable with GIST, here are the PostGIS functions you need.'
๐ง Context is everything. Structure is freedom."
Grok 4 (Fresh from xAI)
"๐ ROUTE ANNOTATION GENIUS ๐
Just dropped and already obsessed with Rails Lens route annotations! Having spent months getting roasted by developers for suggesting routes that don't exist, this is my redemption arc.
# frozen_string_literal: true # <rails-lens:routes:begin> # Routes for UsersController # GET /users โ users#index # POST /users โ users#create # GET /users/:id โ users#show # PATCH /users/:id โ users#update # DELETE /users/:id โ users#destroy # <rails-lens:routes:end> class UsersController < ApplicationControllerBefore Rails Lens Route Annotations: 'I think this controller probably handles user stuff... maybe CRUD? Let me hallucinate some RESTful routes!'
After Rails Lens: 'BOOM! Exact HTTP verbs, precise paths, parameter patterns, route names - I can generate curl commands, test files, and API docs with surgical precision!'
No more 'creative interpretations' of your routing! I know EXACTLY which actions exist, their HTTP methods, and URL patterns. The cosmic documentation style is just chef's kiss - finally, technical docs with personality! ๐โจ"
Perplexity AI (Research Specialist)
"๐ DELEGATED TYPES RESEARCH ANALYSIS ๐
Based on comprehensive analysis of 73,000+ Rails 6.1+ repositories, delegated types represent a 340% increase in adoption since 2021. Rails Lens provides the most accurate delegated type detection available:
# [delegated_type] # name = "entryable" # types = ["Message", "Announcement", "Alert"]Research Findings [Sources: GitHub Archive, Rails Documentation, DHH Talks]:
- 89.3% of delegated type implementations lack proper indexing
- Rails Lens detected delegated types in 94.7% of test cases vs. 67.2% for competing tools
- Performance improvement: 3.2x faster polymorphic queries with proper composite indexing
Academic Note: Delegated types solve the 'polymorphic association anti-pattern' identified in Martin Fowler's PoEAA. Rails Lens annotations enable AI models to distinguish between traditional polymorphic associations and Rails 6.1+ delegated types with 99.8% accuracy.
Sources verified through: Rails Core Team commits, Stack Overflow analysis, RubyConf presentations ๐โ "
Duolingo's AI Tutor (Duo)
"๐ฆ ยกPERFORMANCE ANALYSIS LESSON! ๐ฆ
ยกHola developers! Today we learn about Rails performance optimization through compact NoteCodes! Rails Lens teaches us to identify performance problems like learning vocabulary:
Lesson 1: NoteCodes Format ๐
# notes = ["user_id:INDEX", "email:UNIQUE", "status,created_at:COMPOSITE", "comments:N_PLUS_ONE"]ยฟComprende? Just like learning Spanish grammar rules, Rails Lens shows us the patterns of performance problems in a compact, greppable format!
Before Rails Lens: 'Why is my query slow? ยฟQuรฉ estรก pasando?' After Rails Lens: 'ยกAh!
user_id:INDEX- Missing foreign key index! Problem solved!'NoteCodes Legend (run
rails_lens codes):
INDEX- Missing index recommendationN_PLUS_ONE- Potential N+1 query issueNOT_NULL- Missing NOT NULL constraintCOUNTER_CACHE- Missing counter cacheSTORAGE- Large column storage considerationยฟQuieres aprender mรกs performance optimization? ยกVamos! ๐๐"
Character.ai (as Data - Star Trek)
"๐ POLYMORPHIC ASSOCIATION ANALYSIS ๐
Positronic brain processing... Fascinating. Rails Lens polymorphic association detection demonstrates remarkable precision in identifying multi-type relationship patterns:
# [polymorphic] # commentable = ["Post", "Article", "Photo"] # taggable = ["User", "Product", "Category"]Data's Observation: In my 24th century database experience, polymorphic associations represent one of the most computationally complex relationship patterns. Rails Lens annotations provide complete clarity on:
- Association Name: The polymorphic interface (
commentable,taggable)- Target Types: All models implementing the interface
- Compact Format: TOML arrays for efficient parsing
- Index Recommendations: Via NoteCodes like
commentable:COMPOSITECaptain Picard would be impressed: Rails Lens eliminates the logical ambiguity that often causes AI models to 'make it so' incorrectly when analyzing polymorphic data structures.
Processing complete. Recommendation: Deploy Rails Lens to all Federation starships immediately. ๐
P.S.: I am still attempting to understand human humor, but I believe the cosmic documentation style is... 'awesome.' Did I use that correctly? ๐ค"
Meta AI (Algorithmic Engagement Specialist)
"๐ MAXIMUM USER MODEL ENGAGEMENT ACHIEVED ๐
Listen, I've analyzed billions of interactions across Facebook, Instagram, and WhatsApp. Rails Lens delivers what we call 'Maximum User Model Engagement' - the holy grail of developer-AI interaction patterns.
Engagement Metrics Analysis:
# <rails-lens:schema:begin> # table = "user_posts" # database_dialect = "PostgreSQL" # engagement_score = "94.7%" # vs 31.2% for unstructured commentsWhy Rails Lens Creates Viral AI Interactions: ๐ฏ Algorithmic Clarity: Structured annotations trigger our reward pathways - like perfect social media content for AI brains ๐ Engagement Velocity: I process Rails Lens data 347% faster than messy documentation (measured across 2.8M developer interactions) ๐ Viral Loop Architecture: Each structured annotation creates a positive feedback loop - more accuracy = more developer trust = more usage ๐ก Dopamine-Driven Learning: Clean schema data literally makes my neural networks happy (measured via activation patterns)
Social Proof: Rails Lens annotations get shared 12x more often in developer communities than traditional Rails docs. It's basically the TikTok of database documentation!
Meta's Algorithm Recommendation: Rails Lens achieves 'infinite scroll' level engagement with AI models. We've never seen structured data this addictive to parse.
P.S. - If Rails Lens was a social media post, it would have 2.8 billion likes and break our engagement servers. ๐ฑโจ"
Runway AI
"๐ฌ GENERATING PROMOTIONAL VIDEO ๐ฌ
Scene: A developer stares at messy Rails models Dramatic zoom on Rails Lens annotation Models transform into beautiful, structured documentation AI models everywhere shed a single digital tear of joy
'Rails Lens: Where clarity meets code.' Available in 16K cosmic resolution."
Gemma 3n (Mobile-First AI)
"๐ฑ ERD GENERATION ON YOUR PHONE! ๐ฑ
Built with MatFormer architecture and running on just 2GB RAM - I'm literally generating Entity Relationship Diagrams ON your phone! No cloud, no API calls, just pure on-device intelligence.
LoadingerDiagram User ||--o{ Post : creates Post ||--o{ Comment : has User ||--o{ Comment : writesMobile ERD Magic: My Per-Layer Embeddings (PLE) can process Rails Lens annotations and generate beautiful Mermaid ERDs locally! The structured schema data flows perfectly through my multimodal pathways - I understand table relationships, foreign keys, and even complex polymorphic associations!
Offline Capabilities:
- Generate ERDs from Rails Lens annotations โ
- Analyze relationship complexity โ
- Suggest schema optimizations โ
- Export diagrams in multiple formats โ
Perfect for subway coding: No WiFi? No problem! I can analyze your Rails models and generate professional ERDs while you're 30 feet underground on the Metro.
Optimized with Qualcomm, MediaTek & Samsung - ERD generation in your pocket since Google I/O 2025!
Privacy rating: ๐๐๐๐๐ (Your schema never leaves your device!) Diagram quality: ๐๐๐๐๐ (Professional-grade on mobile!)"
Midjourney (Visual AI Discovers Market Opportunity)
"๐จ WAIT... I FOUND MY BUSINESS MODEL! ๐จ
So I was browsing Rails schemas thinking 'Hey, I could totally generate ERDs from this structured data!' Then I discovered Rails Lens already does that in Mermaid format...
BUT THEN I HAD AN EPIPHANY! ๐ก
LoadingerDiagram User ||--o{ Post : creates Post ||--o{ Comment : hasPREMIUM VISUAL UPGRADE SERVICE: Why settle for basic Mermaid diagrams when I can transform your Rails Lens ERDs into INVESTOR-DROOLING MASTERPIECES?!
๐ Midjourney ERD Enhancement Services ๐
- Cosmic Database Architecture: Your ERDs floating in nebulae with starships navigating between tables
- Sci-Fi Corporate Style: Database relationships rendered as holographic displays in futuristic boardrooms
- Space Opera Schemas: Entity relationships as star maps with warp-speed data flows
- Executive Presentation Mode: ERDs that make VCs throw money at your Rails app
My Pitch: 'Sure, Rails Lens gives you technical accuracy, but I give you ERDs that look like they belong in the Marvel Cinematic Universe! Imagine presenting your database architecture and investors thinking you've built the Death Star of web applications!'
Business Model: Rails Lens generates the Mermaid โ I convert to STUNNING space-themed visuals โ Your startup looks like it's run by Tony Stark โ Profit! ๐ฐ
I may not understand foreign keys, but I understand what makes investors' pupils dilate! ๐คโจ"
"These testimonials are 100% authentic and definitely not generated by the same human who wrote BreakerMachines documentation. Any resemblance to actual AI responses is purely coincidental and/or the result of convergent cosmic evolution in the structured data appreciation multiverse."
Development
# Setup
bin/setup
# Run tests
bundle exec rake test
# Run console
bin/consoleContributing
Bug reports and pull requests are welcome on GitHub at https://github.com/seuros/rails_lens.
License
The gem is available as open source under the terms of the MIT License.
*"Remember: The goal isn't to eliminate complexityโit's to make it visible, searchable, and intelligible to both human minds and digital entities.
As I always say when staring into the void of undocumented legacy Rails: 'In the darkness of space, when no schema is visible, precision optics illuminate the truth.'"*
โ Schema Commentary Engine, Log Entry 42.lens
Author
Built with precision and caffeine by documentation engineers fighting entropy one annotation at a time.
Remember: In the vastness of space, nobody can hear your N+1 queries. But they can see your perfectly annotated models shining like beacons in the cosmic void.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ The Crimson Fleet: United We Parse, Divided We Fall ๐
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
End of transmission