---
name: rails-repl
description: Use when you need to run Ruby code in a Rails project - evaluates code in a persistent console without startup overhead
---

# Rails REPL

Run Ruby code in a persistent Rails console. Avoids the startup overhead of `bin/rails runner` for each command.

## Usage

### 1. Check if REPL is running

```bash
REPL_DIR="${CLAUDE_REPL_DIR:-$(pwd)/tmp/claude_repl}"
PID_FILE="$REPL_DIR/pid"
if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
  echo "REPL running"
else
  echo "REPL not running"
fi
```

### 2. Start REPL if needed

```bash
bin/rails runner ~/.claude/skills/rails-repl/claude_repl.rb &
```

Wait briefly for startup, then verify PID file exists.

### 3. Send a command

Write Ruby code to `tmp/claude_repl/command.rb`:

```ruby
Tenant.first.name
```

### 4. Wait for completion

Poll until `command.rb` disappears (max 30 seconds):

```bash
REPL_DIR="${CLAUDE_REPL_DIR:-$(pwd)/tmp/claude_repl}"
while [ -f "$REPL_DIR/command.rb" ]; do sleep 0.2; done
```

### 5. Read result

Read `tmp/claude_repl/output.txt`. The output format:

- **Success**: Any stdout appears first, then `__RESULT__` on its own line, then the return value
- **Error**: Starts with `__REPL_ERROR__`, followed by exception message and backtrace

### 6. Clean up

Delete `output.txt` after reading (or before next command).

### 7. Stop REPL

Write `__EXIT__` to `command.rb`. The REPL will shut down gracefully and clean up its PID file.

## Files

| File | Purpose |
|------|---------|
| `command.rb` | Input - write Ruby code here |
| `output.txt` | Output - result or error |
| `pid` | REPL process ID |
| `audit.log` | Full history of all commands and outputs |

## Configuration

Set `CLAUDE_REPL_DIR` to change the working directory (default: `Rails.root/tmp/claude_repl`).

## Error Handling

- If REPL dies, PID file may be stale. Check with `kill -0`.
- If `command.rb` doesn't disappear after 30s, REPL may have crashed. Check `audit.log`.
- Restart REPL if needed: kill old process, delete PID file, start fresh.
