Layered Rails logo

Layered Rails

Community
palkan
layered-rails

Write, refactor, and review Rails code using layered architecture principles from "Layered Design for Ruby on Rails Applications". Use when writing or refactoring Rails code — models, controllers, services, jobs, mailers, policies, forms, query objects, presenters, view components, state machines, serializers, or AI/LLM features — to apply correct patterns and avoid layer violations; and when reviewing Rails code, PRs, or diffs for layer violations, fat controllers/models, anemic models, callback misuse, god objects, or specification-test failures. Triggers on "layered design", "architecture layers", "abstraction layer", "specification test", "layer violation", "fat controller/model", "god object", "anemic model", "extract service/callback/policy/concern", "service object", "form/policy/query/value object", "presenter", "view component", "state machine", "Active Delivery", "callback scoring", "Rails refactor/review", "Rails patterns/best practices", "archspec", "architecture linter/enforcement".

Overview

Publisherpalkan
Repositorylayered-rails-skills
Skill namelayered-rails
Stars
473
Forks
17
Bundled files
56
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 56 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by palkan on GitHub. Read the source before you install it.

Installation

Install the Layered Rails AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/palkan/layered-rails-skills/tree/master/layered-rails/skills/layered-rails
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/palkan/layered-rails-skills.git /tmp/layered-rails-skills
mkdir -p .claude/skills
cp -r /tmp/layered-rails-skills/layered-rails/skills/layered-rails .claude/skills/layered-rails
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Layered Rails in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Layered Rails on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Layered Rails is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Layered Rails

Design and review Rails applications using layered architecture principles.

Quick Start

Rails applications are organized into four architecture layers with unidirectional data flow:

┌─────────────────────────────────────────┐
│           PRESENTATION LAYER            │
│   Controllers, Views, Channels, Jobs*   │
│ Forms, Filters, Presenters, Serializers │
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│           APPLICATION LAYER             │
│ Services, Policies, Mailers, Deliveries │
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│             DOMAIN LAYER                │
│  Models, Value Objects, Query Objects   │
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│          INFRASTRUCTURE LAYER           │
│  Active Record, API Clients, Storage    │
└─────────────────────────────────────────┘

* Jobs are internal inbound entry points: design-wise they follow the same rules as controllers, minus authentication and user-input handling.

Core Rule: Lower layers must never depend on higher layers.

See Architecture Layers Reference for the full layer responsibilities and the Four Rules deep-dive.

What this skill is for

Use this skill when:

  1. Analyzing a codebase — apply the architecture analysis for a full audit, or zoom in with the service-layer audit, callback analysis, or god-object analysis.
  2. Reviewing code changes — run the code review workflow on a diff, file, or branch.
  3. Running the specification test — use the spec-test workflow on a single file or directory to evaluate whether code belongs in its current layer.
  4. Planning gradual adoption — generate a phased roadmap with the layerification plan workflow, focused on a goal like "introduce authorization" or "decompose god objects."
  5. Planning a feature — I'll apply the layered principles below to whichever code you're about to write.
  6. Implementing a specific pattern — authorization, notifications, view components, AI integration, etc. — see the Pattern Catalog and Topic References below.

In Claude Code with this skill installed as a plugin (/plugin install layered-rails@layered-rails-skills), each workflow above is also reachable as a slash command — see Slash Commands. Natural-language requests ("review this file with layered-rails", "run the specification test on app/models/order.rb") work in any environment that has the skill loaded.

Workflows

Reusable procedures bundled inside this skill. Read the file and apply it to the target code:

Core Principles

The Four Rules

  1. Unidirectional Data Flow - Data flows top-to-bottom only
  2. No Reverse Dependencies - Lower layers never depend on higher layers
  3. Abstraction Boundaries - Each abstraction belongs to exactly one layer
  4. Minimize Connections - Fewer inter-layer connections = looser coupling

Common Violations

ViolationExampleFix
Model uses CurrentCurrent.user in modelPass user as explicit parameter
Service accepts requestparam :request in serviceExtract value object from request
Controller has business logicPricing calculations in actionExtract to service or model
Anemic modelsAll logic in servicesKeep domain logic in models
CategoryReference
Layer violations (Current in models, request in services, notifications in models, business logic in controllers)layer-violations.md
Service objects (anemic models, bag of random objects, premature abstraction)service-objects.md
Callbacks (operation callbacks, skip callbacks, control flags)callbacks.md
Concerns (code-slicing, overgrown)concerns.md
Helpers (HTML construction in helpers)helpers.md
Jobs (anemic jobs)jobs.md
Testing (testing wrong layer)testing.md

The Specification Test

If the specification of an object describes features beyond the primary responsibility of its abstraction layer, such features should be extracted into lower layers.

How to apply:

  1. List responsibilities the code handles
  2. Evaluate each against the layer's primary concern
  3. Extract misplaced responsibilities to appropriate layers

See Specification Test Reference for detailed guide.

Pattern Catalog

PatternLayerUse WhenReference
Service ObjectApplicationOrchestrating domain operationsservice-objects.md
Query ObjectDomainComplex, reusable queriesquery-objects.md
Form ObjectPresentationMulti-model forms, complex validationform-objects.md
Filter ObjectPresentationRequest parameter transformationfilter-objects.md
PresenterPresentationView-specific logic, multiple modelspresenters.md
SerializerPresentationAPI response formattingserializers.md
Policy ObjectApplicationAuthorization decisionspolicy-objects.md
Value ObjectDomainImmutable, identity-less conceptsvalue-objects.md
Collaborator ObjectDomainA slice of one model's behavior in a typed delegatecollaborator-objects.md
State MachineDomainStates, events, transitionsstate-machines.md
ConcernDomainShared behavioral extractionconcerns.md
RepositoryDomainLast resort — returning custom domain objects mapped from AR data, after AR scopes (simple) and query objects (query building) are insufficientrepositories.md

Pattern Selection Guide

"Where should this code go?"

If you have...Consider...
Complex multi-model formForm Object
Request parameter filtering/transformationFilter Object
View-specific formattingPresenter
Complex database query used in multiple placesQuery Object
Business operation spanning multiple modelsService Object (as waiting room)
Authorization rulesPolicy Object
Multi-channel notificationsDelivery Object (Active Delivery)

Remember: Services are a "waiting room" for code until proper abstractions emerge. Don't let app/services become a bag of random objects.

Refactoring Scenarios

Canonical before/after transformations for the most common layerification moves. The layerification plan workflow uses these as reference templates when proposing phases.

ScenarioGoal areaReference
Extract callbacks to servicecallbacks, after_create chainscallbacks-to-service.md
Extract authorization to policyauthorization, permissionsauthorization-to-policy.md
Extract query logic to query objectcomplex scopes, reporting queriesquery-to-query-object.md
Extract Current from modelCurrent.* in domaincurrent-from-model.md
Decompose god object with associated objectsgod model, large User/Accountgod-object-decomposition.md
Replace implicit state machinetimestamp-based statusimplicit-to-explicit-state-machine.md
Extract view logic to presentertemplate logic, formattingview-logic-to-presenter.md
Form object for complex inputfat controllers, multi-model formscomplex-input-to-form-object.md

Slash Commands

These slash commands are available only when this skill is installed as a Claude Code plugin (/plugin install layered-rails@layered-rails-skills). When the skill is installed via skills.sh or any other path that delivers skills/layered-rails/ without the surrounding plugin, the commands won't be present — invoke the corresponding workflow directly (see Workflows) or just ask in plain language.

CommandWorkflowPurpose
/layered-rails:reviewreviewReview code changes from a layered architecture perspective
/layered-rails:spec-testspec-testRun specification test on specific files
/layered-rails:analyzeanalyzeFull codebase abstraction-layer analysis
/layered-rails:analyze-servicesanalyze-servicesAudit app/services/ and service-like classes — conventions, clusters, layer hygiene, test consequences
/layered-rails:analyze-callbacksanalyze-callbacksScore model callbacks, find extraction candidates
/layered-rails:analyze-godsanalyze-godsFind god objects via churn × complexity
/layered-rails:plan [goal]planPlan gradual adoption of layered patterns
/layered-rails:archspecarchspecGenerate and verify an Archspec.rb enforcing layer boundaries in CI

Topic References

For deep dives on specific topics:

TopicReference
Authorization (RBAC, ABAC, policies)authorization.md
Notifications (multi-channel delivery)notifications.md
View Componentsview-components.md
AI Integration (LLM, agents, RAG, MCP)ai-integration.md
Configurationconfiguration.md
Callbacks (scoring, extraction)callbacks.md
Current Attributescurrent-attributes.md
Instrumentation (logging, metrics)instrumentation.md

Gem References

For library-specific guidance:

GemPurposeReference
action_policyAuthorization frameworkaction-policy.md
view_componentComponent frameworkview-component.md
anyway_configTyped configurationanyway-config.md
active_deliveryMulti-channel notificationsactive-delivery.md
albaJSON serializationalba.md
workflowState machinesworkflow.md
rubanokFilter/transformation DSLrubanok.md
active_agentAI agent frameworkactive-agent.md
active_job-performsEliminate anemic jobsactive-job-performs.md
archspecEnforce layer boundaries in CI (reference Archspec.rb config)archspec.md

Extraction Signals

When to extract from models:

SignalMetricAction
God objectHigh churn × complexityDecompose into concerns, delegates, or separate models
Operation callbackScore 1-2/5Extract to service or event handler
Code-slicing concernGroups by artifact typeConvert to behavioral concern or extract
Current dependencyModel reads Current.*Pass as explicit parameter

Callback Scoring:

TypeScoreKeep?
Transformer (compute values)5/5Yes
Normalizer (sanitize input)4/5Yes
Utility (counter caches)4/5Yes
Observer (side effects)2/5Maybe
Operation (business steps)1/5Extract

See Extraction Signals Reference for detailed guide.

Model Organization

Recommended order within model files:

ruby
class User < ApplicationRecord
  # 1. Gems/DSL extensions
  has_secure_password

  # 2. Associations
  belongs_to :account
  has_many :posts

  # 3. Enums
  enum :status, { pending: 0, active: 1 }

  # 4. Normalization
  normalizes :email, with: -> { _1.strip.downcase }

  # 5. Validations
  validates :email, presence: true

  # 6. Scopes
  scope :active, -> { where(status: :active) }

  # 7. Callbacks (transformers only)
  before_validation :set_defaults

  # 8. Delegations
  delegate :name, to: :account, prefix: true

  # 9. Public methods
  def full_name = "#{first_name} #{last_name}"

  # 10. Private methods
  private

  def set_defaults
    self.locale ||= I18n.default_locale
  end
end

Success Checklist

Well-layered code:

  • No reverse dependencies (lower layers don't depend on higher)
  • Models don't access Current attributes
  • Services don't accept request objects
  • Controllers are thin (HTTP concerns only)
  • Domain logic lives in models, not services
  • Callbacks score 4+ or are extracted
  • Concerns are behavioral, not code-slicing
  • Abstractions don't span multiple layers
  • Tests verify appropriate layer responsibilities

Guidelines

  • Use domain language - Name models after business concepts (Participant, not User; Cloud, not GeneratedImage)
  • Patterns before abstractions - Let code age before extracting; premature abstraction is worse than duplication
  • Services as waiting room - Don't let app/services become permanent residence for code
  • Explicit over implicit - Prefer explicit parameters over Current attributes
  • Extraction thresholds - Consider extraction when methods exceed 15 lines or call external APIs

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Layered Rails AI skill do?

Write, refactor, and review Rails code using layered architecture principles from "Layered Design for Ruby on Rails Applications". Use when writing or refactoring Rails code — models, controllers, services, jobs, mailers, policies, forms, query objects, presenters, view components, state machines, serializers, or AI/LLM features — to apply correct patterns and avoid layer violations; and when reviewing Rails code, PRs, or diffs for layer violations, fat controllers/models, anemic models, callback misuse, god objects, or specification-test failures. Triggers on "layered design", "architectur...

Why use Layered Rails on TypingMind?

Because you install it once and use it with any model. Layered Rails is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Layered Rails in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/palkan/layered-rails-skills/tree/master/layered-rails/skills/layered-rails. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Layered Rails?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Layered Rails?

As many as you like. As long as a model supports skills, you can use Layered Rails with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Layered Rails AI skill free?

It is published on GitHub by palkan. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇