Docker環境でClaude Codeを利用する

やろうやろうと思いつつできていなかったClaude Codeの導入にようやく着手することができたので流れをまとめました。

プロジェクトにClaude Codeを導入する

目次

Claude Code環境の構築

参考資料:Anthropic – 開発コンテナ
https://docs.anthropic.com/ja/docs/claude-code/devcontainer

1.公式のサンプルプロジェクトのclone

git clone https://github.com/anthropics/claude-code.git

2.Dev Containersの設定をプロジェクトのルートディレクトリにコピーする

今回は最小構成で導入するため、.devcontainer のみをコピーします。

cp -r claude-code/.devcontainer app_root_path

3.(VS Code を使用する場合)Dev Container拡張機能でコンテナに接続

Claude Codeの初回起動

1.claude コマンドを実行して起動

claude

 

2.表示スタイルの設定

好みの表示スタイルを選択します。

╭──────────────────────────╮
│ ✻ Welcome to Claude Code │
╰──────────────────────────╯

 Let's get started.

 Choose the text style that looks best with your terminal:
 To change this later, run /theme

   1. Dark mode
   2. Light mode
 ❯ 3. Dark mode (colorblind-friendly)✔
   4. Light mode (colorblind-friendly)
   5. Dark mode (ANSI colors only)
   6. Light mode (ANSI colors only)


 Preview
 ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
 │   1   function greet() {                                                                                                                                             │
 │   2 -    console.log("Hello, World!");                                                                                                                               │
 │   2 +    console.log("Hello, Claude!");                                                                                                                              │
 │   3   }                                                                                                                                                              │
 ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

 

3.アカウントの設定

今回は API 利用を想定しているため、「2. Anthropic Console account」を選択します。

 Claude Code can now be used with your Claude subscription or billed based on API usage through your Console account.


 Select login method:

   1. Claude account with subscription
    Starting at $20/mo for Pro, $100/mo for Max - Best value, predictable pricing

 ❯ 2. Anthropic Console account
    API usage billing

 

ブラウザが開くので、アカウントにログインし「Authorize」を選択します。

「Login successful」と表示されればOKです。

 Browser didn't open? Use the url below to sign in:

https://console.anthropic.com/oauth/authorize?**********************************


 Logged in as ****@example.com


 Login successful. Press Enter to continue…

 

4.ログイン後の初期設定

注意事項が表示されるので内容を確認し、Enterを押します。

╭──────────────────────────╮
│ ✻ Welcome to Claude Code │
╰──────────────────────────╯

 Security notes:

 1. Claude can make mistakes
    You should always review Claude's responses, especially when
    running code.

 2. Due to prompt injection risks, only use it with code you trust
    For more details see:
    https://docs.anthropic.com/s/claude-code-security

 Press Enter to continue…

 

Shift+Enterで改行する設定を有効にするかどうか尋ねられるため、「Yes」を選択します。

╭──────────────────────────╮
│ ✻ Welcome to Claude Code │
╰──────────────────────────╯

 Use Claude Code's terminal setup?

 For the optimal coding experience, enable the recommended settings
 for your terminal: Shift+Enter for newlines

 ❯ 1. Yes, use recommended settings
   2. No, maybe later with /terminal-setup

 Enter to confirm · Esc to skip

 

プロジェクトのルートディレクトリを信頼するかどうか確認されるので、問題がなければ「Yes」を選択します。

╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                        │
│ Do you trust the files in this folder?                                                                                                                                 │
│                                                                                                                                                                        │
│ /workspace                                                                                                                                                             │
│                                                                                                                                                                        │
│ Claude Code may read files in this folder. Reading untrusted files may lead Claude Code to behave in unexpected ways.                                                  │
│                                                                                                                                                                        │
│ With your permission Claude Code may execute files in this folder. Executing untrusted code is unsafe.                                                                 │
│                                                                                                                                                                        │
│ https://docs.anthropic.com/s/claude-code-security                                                                                                                      │
│                                                                                                                                                                        │
│ ❯ 1. Yes, proceed                                                                                                                                                      │
│   2. No, exit                                                                                                                                                          │
│                                                                                                                                                                        │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
   Enter to confirm · Esc to exit

 

設定完了後、EnterでClaudeとのやり取りが可能になります。

╭───────────────────────────────────────────────────╮
│ ✻ Welcome to Claude Code!                         │
│                                                   │
│   /help for help, /status for your current setup  │
│                                                   │
│   cwd: /project-root                              │
╰───────────────────────────────────────────────────╯

 Tips for getting started:

 1. Run /init to create a CLAUDE.md file with instructions for Claude
 2. Use Claude to help with file analysis, editing, bash commands and git
 3. Be as specific as you would with another engineer for the best results
 4. ✔ Run /terminal-setup to set up terminal integration

 ※ Tip: Start with small features or bug fixes, tell Claude to propose a plan, and verify its suggested edits
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✻ Welcome to Claude Code for VS Code                                                                                                                                   │
│   installed extension v1.0.73                                                                                                                                          │
│                                                                                                                                                                        │
│  • Claude has context of ⧉ open files and ⧉ selected lines                                                                                                             │
│                                                                                                                                                                        │
│  • Review Claude Code's changes +11 -22 in the comfort of your IDE                                                                                                     │
│                                                                                                                                                                        │
│  • Cmd+Esc for Quick Launch                                                                                                                                            │
│                                                                                                                                                                        │
│  • Ctrl+Alt+K to reference files or lines in your input                                                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
   Press Enter to continue

 

5.CLAUDE.mdの作成

╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ > /init                                                                                                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
  /init                   Initialize a new CLAUDE.md file with codebase documentation
Claudeの出力結果
> /init is analyzing your codebase… 

● I'll analyze the codebase to understand its structure and create a comprehensive CLAUDE.md file. Let me start by exploring the repository structure and key files.

● Update Todos
  ⎿  ☐ Explore repository structure and identify key files        
     ☐ Analyze build and development configuration files
     ☐ Understand the application architecture and main components
     ☐ Check for existing documentation and rules files
     ☐ Create comprehensive CLAUDE.md file

● List(/workspace)
  ⎿  Listed 1236 paths (ctrl+r to expand)

● Read(README.md)
  ⎿  Read 25 lines (ctrl+r to expand)

● Search(pattern: "package.json")
  ⎿  Found 1 file (ctrl+r to expand)

● Search(pattern: "Gemfile")
  ⎿  Found 1 file (ctrl+r to expand)

● Update Todos
  ⎿  ☒ Explore repository structure and identify key files        
     ☐ Analyze build and development configuration files
     ☐ Understand the application architecture and main components
     ☐ Check for existing documentation and rules files
     ☐ Create comprehensive CLAUDE.md file

● Read(Gemfile)
  ⎿  Read 163 lines (ctrl+r to expand)

● Read(package.json)
  ⎿  Read 2 lines (ctrl+r to expand)

● Read(config/application.rb)
  ⎿  Read 51 lines (ctrl+r to expand)

● Search(pattern: "Rakefile")
  ⎿  Found 1 file (ctrl+r to expand)

● Read(Rakefile)
  ⎿  Read 7 lines (ctrl+r to expand)

● Search(pattern: "**/.cursorrules")
  ⎿  Found 0 files 

● Search(pattern: "**/.github/copilot-instructions.md")
  ⎿  Found 0 files 

● List(.cursor)
  ⎿  Listed 2 paths (ctrl+r to expand)

● Update Todos
  ⎿  ☒ Explore repository structure and identify key files        
     ☒ Analyze build and development configuration files
     ☐ Understand the application architecture and main components
     ☐ Check for existing documentation and rules files
     ☐ Create comprehensive CLAUDE.md file

● Read(app/models/application_record.rb)
  ⎿  Read 4 lines (ctrl+r to expand)

● Read(app/controllers/application_controller.rb)
  ⎿  Read 105 lines (ctrl+r to expand)

● List(lib/tasks)
  ⎿  Listed 15 paths (ctrl+r to expand)

● Read(config/routes.rb)
  ⎿  Read 169 lines (ctrl+r to expand)

● Update Todos
  ⎿  ☒ Explore repository structure and identify key files        
     ☒ Analyze build and development configuration files
     ☒ Understand the application architecture and main components
     ☐ Check for existing documentation and rules files
     ☐ Create comprehensive CLAUDE.md file

● Read(lib/tasks/seeds.rake)
  ⎿  Read 14 lines (ctrl+r to expand)

● Search(pattern: "**/CLAUDE.md")
  ⎿  Found 0 files 

● Read(spec/rails_helper.rb)
  ⎿  Read 134 lines (ctrl+r to expand)

● Read(config/schedule.rb)
  ⎿  Read 43 lines (ctrl+r to expand)

● Update Todos
  ⎿  ☒ Explore repository structure and identify key files        
     ☒ Analyze build and development configuration files
     ☒ Understand the application architecture and main components
     ☒ Check for existing documentation and rules files
     ☐ Create comprehensive CLAUDE.md file

● Write(CLAUDE.md)

╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ Create file                                                                                                                                                            │
│ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │ CLAUDE.md                                                                                                                                                          │ │
│ │                                                                                                                                                                    │ │
│ │ # CLAUDE.md                                                                                                                                                        │ │
│ │                                                                                                                                                                    │ │
│ │ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.                                                             │ │
│ │                                                                                                                                                                    │ │
│ │ ## Application Overview                                                                                                                                            │ │
│ │                                                                                                                                                                    │ │
│ │ This is a Ruby on Rails 7.0.4+ e-commerce application called **SampleApp** - an example product ordering system with subscription management           │ │
│ │ capabilities. The application features:                                                                                                                            │ │
│ │                                                                                                                                                                    │ │
│ │ - Customer-facing web interface for product browsing and purchasing                                                                                                │ │
│ │ - Administrative dashboard using ActiveAdmin for order/customer management                                                                                         │ │
│ │ - Subscription  ordering system with periodic delivery scheduling                                                                                          │ │
│ │ - Multi-payment support                                                                                           │ │
│ │ - Integrated consultation system for customer inquiries                                                                                                     │ │
│ │ - Mobile app API endpoints for cart and product management                                                                                                         │ │
│ │ - Comprehensive audit logging with the `audited` gem                                                                                                               │ │
│ │                                                                                                                                                                    │ │
│ │ ## Key Development Commands                                                                                                                                        │ │
│ │                                                                                                                                                                    │ │
│ │ ### Database Operations                                                                                                                                            │ │
│ │ ```bash                                                                                                                                                            │ │
│ │ # Run migrations                                                                                                                                                   │ │
│ │ bundle exec rails db:migrate                                                                                                                                       │ │
│ │                                                                                                                                                                    │ │
│ │ # Seed database                                                                                                                                                    │ │
│ │ bundle exec rails db:seed                                                                                                                                          │ │
│ │                                                                                                                                                                    │ │
│ │ # Seed specific data (multiple seed files in db/seeds/)                                                                                                            │ │
│ │ RAILS_ENV=development bundle exec rails db:seed:sample_data                                                                                                   │ │
│ │ RAILS_ENV=development bundle exec rails db:seed:sample_categories                                                                                                  │ │
│ │ RAILS_ENV=test bundle exec rails db:seed:sample_data  # Required before tests                                                                                 │ │
│ │                                                                                                                                                                    │ │
│ │ # Reset database (development only)                                                                                                                                │ │
│ │ bundle exec rails db:reset                                                                                                                                         │ │
│ │ ```                                                                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ### Testing                                                                                                                                                        │ │
│ │ ```bash                                                                                                                                                            │ │
│ │ # Run all tests                                                                                                                                                    │ │
│ │ bundle exec rspec                                                                                                                                                  │ │
│ │                                                                                                                                                                    │ │
│ │ # Run specific test file                                                                                                                                           │ │
│ │ bundle exec rspec spec/path/to/file_spec.rb                                                                                                                        │ │
│ │                                                                                                                                                                    │ │
│ │ # Run tests with coverage                                                                                                                                          │ │
│ │ COVERAGE=true bundle exec rspec                                                                                                                                    │ │
│ │ ```                                                                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ### Development Server                                                                                                                                             │ │
│ │ ```bash                                                                                                                                                            │ │
│ │ # Start development server                                                                                                                                         │ │
│ │ bundle exec rails server                                                                                                                                           │ │
│ │                                                                                                                                                                    │ │
│ │ # Start with specific environment                                                                                                                                  │ │
│ │ RAILS_ENV=development bundle exec rails server                                                                                                                     │ │
│ │ ```                                                                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ### Scheduled Jobs                                                                                                                                                 │ │
│ │ ```bash                                                                                                                                                            │ │
│ │ # Update crontab (uses whenever gem)                                                                                                                               │ │
│ │ bundle exec whenever --update-crontab                                                                                                                              │ │
│ │                                                                                                                                                                    │ │
│ │ # View scheduled jobs                                                                                                                                              │ │
│ │ bundle exec whenever                                                                                                                                               │ │
│ │ ```                                                                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ### Code Quality & Security                                                                                                                                        │ │
│ │ ```bash                                                                                                                                                            │ │
│ │ # Run security analysis                                                                                                                                            │ │
│ │ bundle exec brakeman                                                                                                                                               │ │
│ │                                                                                                                                                                    │ │
│ │ # Check for N+1 queries (bullet gem enabled in development)                                                                                                        │ │
│ │ # Monitor Rails logs for bullet warnings                                                                                                                           │ │
│ │ ```                                                                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ## Architecture & Key Components                                                                                                                                   │ │
│ │                                                                                                                                                                    │ │
│ │ ### Multi-User System                                                                                                                                              │ │
│ │ - **AdminUser**: Administrative users with role-based permissions via CanCanCan                                                                                    │ │
│ │ - **User/Customer**: End customers with associated delivery addresses and payment methods                                                                          │ │
│ │ - **Factory**: Multi-tenant factory system for different product suppliers                                                                                         │ │
│ │                                                                                                                                                                    │ │
│ │ ### Core Domain Models                                                                                                                                             │ │
│ │ - **Product**: Items with complex categorization, supplier relationships, and subscription settings                                                                │ │
│ │ - **Order**: One-time purchases with payment processing integration                                                                                    │ │
│ │ - **PeriodicalOrder**: Subscription orders with automated recurring delivery                                                                 │ │
│ │ - **Billing**: Financial records for completed transactions                                                                                                        │ │
│ │ - **Customer/CustomerDelivery**: Customer data with multiple delivery addresses                                                                                    │ │
│ │                                                                                                                                                                    │ │
│ │ ### Payment Integrations                                                                                                                                           │ │                                                                                                                               │ │
│ │ - **Bank Transfer**: Traditional postal transfer system                                                                                                            │ │
│ │                                                                                                                                                                    │ │
│ │ ### External API Integrations                                                                                                                                      │ │
│ │ Located in `lib/` directory:                                                                                                                                       │ │
│ │ - **ExternalApiClient**: Integration with external fulfillment system                                                                                           │ │
│ │                                                                                                                                                                    │ │
│ │ ### Background Jobs & Scheduling                                                                                                                                   │ │
│ │ - **Cron jobs** defined in `config/schedule.rb` using whenever gem:                                                                                                │ │
│ │   - Everyday processing: `sample_tasks:sample_job` (7:30 AM daily)                                                                                             │ │
│ │ - **Rake tasks** in `lib/tasks/` for data processing and maintenance                                                                                               │ │
│ │                                                                                                                                                                    │ │
│ │ ### Testing Infrastructure                                                                                                                                         │ │
│ │ - **RSpec** with Rails integration                                                                                                                                 │ │
│ │ - **FactoryBot** for test data generation                                                                                                                          │ │
│ │ - **WebMock** for external API stubbing                                                                                                                            │ │
│ │ - **Capybara + Selenium** for system tests                                                                                                                         │ │
│ │ - Custom test helpers for API mocking (ExternalApi)                                                                               │ │
│ │                                                                                                                                                                    │ │
│ │ ### Admin Interface                                                                                                                                                │ │
│ │ - **ActiveAdmin** for administrative operations                                                                                                                    │ │
│ │ - Custom admin controllers in `app/admin/`                                                                                                                         │ │
│ │ - Complex filtering and batch operations for orders, customers, and products                                                                                       │ │
│ │ - Import functionality for product and pricing data                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ## Key Configuration Notes                                                                                                                                         │ │
│ │                                                                                                                                                                    │ │
│ │ ### Environment Setup                                                                                                                                              │ │
│ │ - **Ruby 3.2.0** required                                                                                                                                          │ │
│ │ - **MySQL** database (development and production)                                                                                                                  │ │
│ │ - **Redis** for caching (if enabled)                                                                                                                               │ │
│ │ - **S3** integration for file storage                                                                                                  │ │
│ │                                                                                                                                                                    │ │
│ │ ### Security Features                                                                                                                                              │ │
│ │ - **Active Record Encryption** for sensitive data                                                                                                                  │ │
│ │ - **Rollbar** for error tracking                                                                                                                                   │ │
│ │ - **reCAPTCHA** integration                                                                                                                                        │ │
│ │ - **Content Security Policy** configured                                                                                                                           │ │
│ │ - **Audited** gem for comprehensive change tracking                                                                                                                │ │
│ │                                                                                                                                                                    │ │
│ │ ### Development-Specific Features                                                                                                                                  │ │
│ │ - **Letter Opener** for email preview in development                                                                                                               │ │
│ │ - **Bullet** gem for N+1 query detection                                                                                                                           │ │
│ │ - **Brakeman** security scanning                                                                                                                                   │ │
│ │ - Debug console available in development/test                                                                                                                      │ │
│ │                                                                                                                                                                    │ │
│ │ ## Important Development Notes                                                                                                                                     │ │
│ │                                                                                                                                                                    │ │
│ │ ### Data Dependencies                                                                                                                                              │ │
│ │ - Complex seed files in `db/seeds/` for different data types                                                                                                       │ │
│ │                                                                                                                                                                    │ │
│ │ ### API Endpoints                                                                                                                                                  │ │
│ │ - **Public API** at `/api/v1/` for mobile app integration                                                                                                          │ │
│ │ - **Cart operations**: Product management, favorites, purchase history                                                                                             │ │
│ │ - **MyPage functionality**: Customer portal with order history and subscription management                                                                         │ │
│ │                                                                                                                                                                    │ │
│ │ ### Authentication Flow                                                                                                                                            │ │
│ │ - **Devise** for user authentication with custom controllers                                                                                                       │ │
│ │ - **Cookie-based login tracking** for external systems integration                                                                                                 │ │
│ │ - **Multi-domain** cookie support for external site integration                                                                                                    │ │
│ │                                                                                                                                                                    │ │
│ │ ### Deployment Considerations                                                                                                                                      │ │
│ │ - **Docker** configuration available (`Dockerfile`, `docker-compose.yml`)                                                                                          │ │
│ │ - **Puma** web server configuration                                                                                                                                │ │
│ │ - **Asset pipeline** using Sprockets with Sass                                                                                                                     │ │
│ │ - **Rollbar** error monitoring in production                                                                                                                       │ │
│ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
│ Do you want to create CLAUDE.md?                                                                                                                                       │
│ ❯ 1. Yes                                                                                                                                                               │
│   2. Yes, for this session only (shift+tab)                                                                                                                            │
│   3. No, and tell Claude what to do differently (esc)                                                                                                                  │
│                                                                                                                                                                        │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

 

出来上がったCLAUDE.md
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Application Overview

This is a Ruby on Rails 7.0.4+ e-commerce application called **SampleApp** - an example product ordering system with subscription management capabilities. The application features:

- Customer-facing web interface for product browsing and purchasing
- Administrative dashboard using ActiveAdmin for order/customer management  
- Subscription ordering system with periodic delivery scheduling
- Multi-payment support
- Integrated consultation system for customer health inquiries
- Mobile app API endpoints for cart and product management
- Comprehensive audit logging with the `audited` gem

## Key Development Commands

### Database Operations
```bash
# Run migrations
bundle exec rails db:migrate

# Seed database
bundle exec rails db:seed

# Seed specific data (multiple seed files in db/seeds/)
RAILS_ENV=development bundle exec rails db:seed:sample_data
RAILS_ENV=development bundle exec rails db:seed:sample_categories
RAILS_ENV=test bundle exec rails db:seed:sample_data  # Required before tests

# Reset database (development only)
bundle exec rails db:reset
```

### Testing
```bash
# Run all tests
bundle exec rspec

# Run specific test file
bundle exec rspec spec/path/to/file_spec.rb

# Run tests with coverage
COVERAGE=true bundle exec rspec
```

### Development Server
```bash
# Start development server
bundle exec rails server

# Start with specific environment
RAILS_ENV=development bundle exec rails server
```

### Scheduled Jobs
```bash
# Update crontab (uses whenever gem)
bundle exec whenever --update-crontab

# View scheduled jobs
bundle exec whenever
```

### Code Quality & Security
```bash
# Run security analysis
bundle exec brakeman

# Check for N+1 queries (bullet gem enabled in development)
# Monitor Rails logs for bullet warnings
```

## Architecture & Key Components

### Multi-User System
- **AdminUser**: Administrative users with role-based permissions via CanCanCan
- **User/Customer**: End customers with associated delivery addresses and payment methods
- **Factory**: Multi-tenant factory system for different product suppliers

### Core Domain Models
- **Product**: Items with complex categorization, supplier relationships, and subscription settings
- **Order**: One-time purchases with payment processing integration
- **PeriodicalOrder**: Subscription orders with automated recurring delivery
- **Billing**: Financial records for completed transactions
- **Customer/CustomerDelivery**: Customer data with multiple delivery addresses

### Payment Integrations
- **Bank Transfer**: Traditional postal transfer system

### External API Integrations
Located in `lib/` directory:
- **ExternalApiClient**: Integration with external fulfillment system

### Background Jobs & Scheduling
- **Cron jobs** defined in `config/schedule.rb` using whenever gem:
  - Everyday processing: `sample_tasks:sample_job` (7:30 AM daily)
- **Rake tasks** in `lib/tasks/` for data processing and maintenance

### Testing Infrastructure
- **RSpec** with Rails integration
- **FactoryBot** for test data generation
- **WebMock** for external API stubbing
- **Capybara + Selenium** for system tests
- Custom test helpers for API mocking (ExternalApi)

### Admin Interface
- **ActiveAdmin** for administrative operations
- Custom admin controllers in `app/admin/`
- Complex filtering and batch operations for orders, customers, and products
- Import functionality for product and pricing data

## Key Configuration Notes

### Environment Setup
- **Ruby 3.2.0** required
- **MySQL** database (development and production)
- **Redis** for caching (if enabled)
- **S3** integration for file storage

### Security Features
- **Active Record Encryption** for sensitive data
- **Rollbar** for error tracking  
- **reCAPTCHA** integration
- **Content Security Policy** configured
- **Audited** gem for comprehensive change tracking

### Development-Specific Features
- **Letter Opener** for email preview in development
- **Bullet** gem for N+1 query detection
- **Brakeman** security scanning
- Debug console available in development/test

## Important Development Notes

### Data Dependencies
- Complex seed files in `db/seeds/` for different data types

### API Endpoints
- **Public API** at `/api/v1/` for mobile app integration
- **Cart operations**: Product management, favorites, purchase history
- **MyPage functionality**: Customer portal with order history and subscription management

### Authentication Flow
- **Devise** for user authentication with custom controllers
- **Cookie-based login tracking** for external systems integration
- **Multi-domain** cookie support for external site integration

### Deployment Considerations
- **Docker** configuration available (`Dockerfile`, `docker-compose.yml`)
- **Puma** web server configuration
- **Asset pipeline** using Sprockets with Sass
- **Rollbar** error monitoring in production

 

6.日本語で回答するようCLAUDE.mdに追記

╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ > 今後の回答を全て日本語で行ってください。CLAUDE.mdに追記することで次回以降のセッションでも同様な設定になるようにしてください。                                        │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Claudeの出力
> 今後の回答を全て日本語で行ってください。CLAUDE.mdに追記することで次回以降のセッションでも同様な設定になるようにしてください。

● 承知いたしました。CLAUDE.mdに日本語での回答指示を追記いたします。

  Update(CLAUDE.md)
  ⎿  Updated CLAUDE.md with 6 additions                                                                                                                              
        2    
        3    This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
        4    
        5 +  ## 言語設定 / Language Settings
        6 +  
        7 +  **重要**: このプロジェクトでは、Claude Codeとの対話は**日本語で行う**こと。すべての回答、説明、コメントは日本語で記述してください。
        8 +  
        9 +  **Important**: For this project, all interactions with Claude Code should be conducted **in Japanese**. All responses, explanations, and comments should 
          + be written in Japanese.
       10 +  
       11    ## Application Overview
       12    
       13    This is a Ruby on Rails 7.0.4+ e-commerce application called **SampleApp** - an example health product ordering system with subscription management 
            capabilities. The application features:

     Tip: Use # to memorize shortcut to quickly add to CLAUDE.md

● CLAUDE.mdに日本語での回答指示を追記しました。これで次回以降のClaude Codeセッションでも、自動的に日本語で対応するようになります。

  今後のやり取りはすべて日本語で行わせていただきます。何かご質問やご要望がございましたら、日本語でお気軽にお申し付けください。

 

Claudeに必要なファイルだけ読み込ませる

キー情報などClaudeに読み込ませたくないデータがあると思います。そういった場合基本的にはClaudeの設定ファイルで制御するのがお手軽です。

ただし、適切に設定しないと回避されてしまう可能性があるため注意が必要です。
(Readを禁止するだけだとコマンド経由での読み込みを防げない)

現状私の環境ではどれも導入が難しいのですが、環境が許すのであれば下記のような方法でClaude外からClaudeの読み書きを制限することができます。

ただし制限外のファイルにも間違えて機微情報が混ざるということは十分考えられるため、結局のところワークスペース内のファイルは全て読み込まれる前提で開発をする方が良いと思います。

  • SELinux(Linux)
  • AppArmor(Linux)
  • sandbox-exec(Macネイティブ実行、仕様が公開されていないためおそらく推奨はされていない方法)
  • ACL(Windowsネイティブ実行)

Windowsのネイティブ対応は比較的最近のため、実際に検証まで行っている記事やブログを見つけられませんでした。
未検証のため一部推測となりますが、runasで専用ユーザーとして起動し、ACLでそのユーザーの読み書きを制御することが可能と考えられます。

手段対象OS目的 / 役割特徴制御粒度
SELinuxLinux(コンテナ可)強制アクセス制御(MAC)でプロセスやファイルのアクセス権限を細かく制御非常に強力だが設定が複雑、学習コスト高プロセス単位・ファイル単位で詳細に制御
AppArmorLinux(コンテナ可)強制アクセス制御(MAC)だが SELinux よりシンプルに導入可能プロファイルベースで「許可リスト」形式、学習しやすいプロセス単位でファイルパスや機能を制御
sandbox-execmacOS (ネイティブ)アプリケーションをサンドボックス内で実行し、ファイルやネットワークアクセスを制御非推奨、柔軟性は低いプロセス単位でファイル・ネットワークアクセス制御
ACL (Access Control List)Windows (コンテナ可)ファイルやフォルダごとにユーザ・グループ単位のアクセス権を細かく設定NTFS 標準機能、導入容易、プロセス単位制御は不可ファイル/フォルダ単位でユーザ・グループごとに制御

※上記表はChatGPTで生成しています※
※記載内容は問題なさそうに思いますが、いずれも未検証の内容なので参考にする場合は十分に注意してください※

試しにDB設計書をmarkdownにしてみた

せっかくClaude Codeを導入したので、軽く動作検証がてらDB設計書をmarkdownに起こしてみました。

1. schema.rbからDB設計書を生成する

╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ > usersテーブルのDB設計書をmarkdownで作成してください                                                                                                                  │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

生成された内容はやや詳細すぎる部分もありましたが、少し手直しする程度で利用可能な品質でした。適切なテンプレートを用意すれば、より実用的に活用できそうです。
また、どのファイルを元に、どこに出力するという情報があるとより正確に作成ができると思います。
(今回は改行をしようとしたところ誤って送信してしまったため曖昧な指示となってしまいました)
作成時にDBの型がおかしいのも指摘してくれましたがそれも正しい指摘でした。

Claudeの出力
> usersテーブルのDB設計書をmarkdownで作成してください

● usersテーブルのDB設計書を作成いたします。まず、マイグレーションファイルとモデルファイルを確認して詳細な設計情報を取得します。

  Update Todos
  ⎿  ☐ usersテーブルのマイグレーションファイルを調査
     ☐ userモデルファイルの内容を確認
     ☐ データベーススキーマファイルを確認
     ☐ 関連するテーブルとの関係を調査
     ☐ markdownでDB設計書を作成

● Search(pattern: "create_users", path: "db/migrate")
  ⎿  Found 0 files 

● Search(pattern: "add.*users", path: "db/migrate")
  ⎿  Found 10 files (ctrl+r to expand)

● Search(pattern: "create_table.*users", path: "db/migrate")
  ⎿  Found 2 files (ctrl+r to expand)

● Read(db/migrate/[timestamp]_create_users.rb)
  ⎿  Read 14 lines (ctrl+r to expand)

● Read(db/migrate/[timestamp]_add_security_column_to_users.rb)
  ⎿  Read 8 lines (ctrl+r to expand)

● Read(db/migrate/[timestamp]_add_columns_to_users.rb)
  ⎿  Read 10 lines (ctrl+r to expand)

● Read(db/migrate/[timestamp]_add_push_token_to_users.rb)
  ⎿  Read 6 lines (ctrl+r to expand)

● Read(db/migrate/[timestamp]_add_index_unlock_token_to_user.rb)
  ⎿  Read 6 lines (ctrl+r to expand)

  Update Todos
  ⎿  ☒ usersテーブルのマイグレーションファイルを調査
     ☐ userモデルファイルの内容を確認
     ☐ データベーススキーマファイルを確認
     ☐ 関連するテーブルとの関係を調査
     ☐ markdownでDB設計書を作成

● Read(app/models/user.rb)
  ⎿  Read 41 lines (ctrl+r to expand)

● Read(db/schema.rb)
  ⎿  Read 50 lines (ctrl+r to expand)

● Search(pattern: "create_table "users"", path: "db/schema.rb", output_mode: "content")
  ⎿  Found 20 lines (ctrl+r to expand)

  Update Todos
  ⎿  ☒ usersテーブルのマイグレーションファイルを調査
     ☒ userモデルファイルの内容を確認
     ☒ データベーススキーマファイルを確認
     ☐ 関連するテーブルとの関係を調査
     ☐ markdownでDB設計書を作成

● Read(app/models/customer.rb)
  ⎿  Read 30 lines (ctrl+r to expand)

● Search(pattern: "belongs_to :user", path: "app/models")
  ⎿  Found 5 files (ctrl+r to expand)

  Update Todos
  ⎿  ☒ usersテーブルのマイグレーションファイルを調査
     ☒ userモデルファイルの内容を確認
     ☒ データベーススキーマファイルを確認
     ☒ 関連するテーブルとの関係を調査
     ☐ markdownでDB設計書を作成

  Write(docs/db_design_users.md)
  ⎿  Wrote 131 lines to docs/db_design_users.md                                                                                                                      
     # usersテーブル DB設計書
     ## 概要
     `users`テーブルは、SampleAppシステムにおける一般顧客(エンドユーザー)の認証情報を管理するテーブルです。Deviseを使用した認証システムの中核となるテーブルで、
     セキュリティ機能とプッシュ通知機能を含みます。
     ## テーブル基本情報
     | 項目 | 値 |
     |------|-----|
     … +121 lines (ctrl+r to expand)

  Update Todos
  ⎿  ☒ usersテーブルのマイグレーションファイルを調査
     ☒ userモデルファイルの内容を確認
     ☒ データベーススキーマファイルを確認
     ☒ 関連するテーブルとの関係を調査
     ☒ markdownでDB設計書を作成

● usersテーブルのDB設計書を作成いたしました。/workspace/docs/db_design_users.mdに保存されています。

  設計書の主な内容:

  基本情報

  - SampleAppシステムの顧客認証テーブル
  - Deviseを使用した認証システム
  - セキュリティ機能(アカウントロック)とプッシュ通知機能を含む

  重要な特徴

  1. Deviseモジュール: database_authenticatable, registerable, recoverable, rememberable, validatable, lockableを使用
  2. セキュリティ機能: ログイン失敗回数制限、アカウントロック、パスワード強度チェック
  3. プッシュ通知: モバイルアプリ用のpush_tokenフィールド
  4. カスタムメール: 本システム専用の件名とfrom設定

  データ型の問題点も記載

  現在のマイグレーションでsign_in_countや*_sign_in_ipフィールドの型定義に不整合があることも指摘しています。

  リレーション

  - customers テーブルと1対1関係(has_one)

  この設計書により、usersテーブルの構造と機能を包括的に理解できるようになっています。

 

出来上がった設計書
# usersテーブル DB設計書

## 概要

`users`テーブルは、SampleAppシステムにおける一般顧客(エンドユーザー)の認証情報を管理するテーブルです。Deviseを使用した認証システムの中核となるテーブルで、セキュリティ機能とプッシュ通知機能を含みます。

## テーブル基本情報

| 項目 | 値 |
|------|-----|
| テーブル名 | users |
| エンジン | InnoDB |
| 文字セット | utf8mb4 |
| 照合順序 | utf8mb4_0900_ai_ci |
| 用途 | 顧客認証・セッション管理 |

## カラム構成

| カラム名 | データ型 | NULL許可 | デフォルト値 | 説明 |
|----------|----------|----------|-------------|------|
| id | bigint | NO | AUTO_INCREMENT | 主キー |
| email | varchar(255) | YES | NULL | メールアドレス(ログインID) |
| encrypted_password | varchar(255) | YES | NULL | 暗号化されたパスワード |
| reset_password_token | varchar(255) | YES | NULL | パスワードリセット用トークン |
| reset_password_sent_at | datetime | YES | NULL | パスワードリセットメール送信日時 |
| remember_created_at | datetime | YES | NULL | ログイン状態記憶開始日時 |
| push_token | text | YES | NULL | プッシュ通知用トークン |
| last_sign_in_at | datetime | YES | NULL | 前回ログイン日時 |
| sign_in_count | datetime | YES | NULL | ログイン回数(※型がdatetimeになっているが実際はintegerのはず) |
| current_sign_in_at | datetime | YES | NULL | 現在のログイン日時 |
| current_sign_in_ip | datetime | YES | NULL | 現在のログインIPアドレス(※型がdatetimeになっているが実際はstring/inetのはず) |
| last_sign_in_ip | datetime | YES | NULL | 前回のログインIPアドレス(※型がdatetimeになっているが実際はstring/inetのはず) |
| failed_attempts | int | YES | 0 | ログイン失敗回数 |
| unlock_token | varchar(255) | YES | NULL | アカウントロック解除用トークン |
| locked_at | datetime | YES | NULL | アカウントロック日時 |
| created_at | datetime | NO | - | 作成日時 |
| updated_at | datetime | NO | - | 更新日時 |

## インデックス

| インデックス名 | カラム | ユニーク | 説明 |
|---------------|--------|----------|------|
| PRIMARY | id | YES | 主キー |
| index_users_on_unlock_token | unlock_token | YES | アカウントロック解除用トークンのユニークインデックス |

## Devise設定

このテーブルは以下のDeviseモジュールを使用しています:

- `:database_authenticatable` - データベース認証
- `:registerable` - ユーザー登録機能
- `:recoverable` - パスワードリセット機能
- `:rememberable` - ログイン状態記憶機能
- `:validatable` - バリデーション機能
- `:lockable` - アカウントロック機能(unlock_strategy: :both)

## バリデーション

### パスワードバリデーション
- 半角英数記号のみ許可: `/A[ -~]*z/`
- 英字と数字の両方を含む必要: `/A(?=.*d)(?=.*[a-zA-Z])[ -~]*z/`

## リレーション

### 1対1リレーション
| 関連テーブル | リレーション種別 | 外部キー | 説明 |
|-------------|----------------|----------|------|
| customers | has_one | user_id | 顧客詳細情報(必ず存在) |

## セキュリティ機能

### アカウントロック機能
- `failed_attempts`: ログイン失敗回数をカウント
- `unlock_token`: ロック解除用の一意トークン
- `locked_at`: ロック実行日時
- unlock_strategy: `:both` - 時間経過またはメールでの解除

### パスワードリセット機能
- `reset_password_token`: リセット用トークン
- `reset_password_sent_at`: リセットメール送信日時
- カスタムメール件名とfrom設定

## 特殊機能

### プッシュ通知
- `push_token`: モバイルアプリ向けプッシュ通知用トークン(text型)

### ログイン追跡
- `sign_in_count`: ログイン回数
- `current_sign_in_at` / `last_sign_in_at`: ログイン日時追跡
- `current_sign_in_ip` / `last_sign_in_ip`: ログインIP追跡

## カスタムメール機能

### 送信メール一覧
1. **パスワードリセット完了通知**
   - 件名: "パスワードの設定が完了しました【サンプルシステム】"
   - メソッド: `send_password_reset_complete_notification`

2. **パスワード変更通知**
   - 件名: "パスワードの変更手続きが完了しました【サンプルシステム】"
   - メソッド: `send_password_change_notification`

3. **パスワードリセット手続き案内**
   - 件名: "パスワード再設定手続きのご案内【サンプルシステム】"
   - メソッド: `send_reset_password_instructions_notification`

## 運用上の注意点

### データ型の不整合
現在のマイグレーションファイルで以下のカラムの型定義に問題があります:
- `sign_in_count`: datetime型になっているがinteger型であるべき
- `current_sign_in_ip`, `last_sign_in_ip`: datetime型になっているがstring型またはinet型であるべき

### セキュリティ考慮事項
- パスワード変更通知はデフォルトでは無効(`send_password_change_notification`が`false`を返す)
- reply_to設定をクリアしてカスタム送信者を設定

## 関連ドキュメント
- [customerテーブル設計書](./db_design_customers.md)

---
*作成日: 2025-08-19*  
*最終更新: 2025-08-19*

 

2. Claudeにmigrationと設計書修正を任せてみる

DB設計書を生成した際に指摘された不整合を修正してもらいます。
確認したところ以前検証時に作成して結局使うことなくそのままになっていたカラムでした。

╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ > usersテーブルの型の不整合を解消するmigrationを作成してください                                                                                                       │
│   合わせて @docs/db_design_users.md も修正してください                                                                                                                 │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

 (今回も本来は一つ前の手順で上がった不整合を具体的に記載して修正を依頼する予定でしたが誤って送信してしまっています。設計書を指定したので結果としては読み込んでくれていますが、ある程度長めのプロンプトになる場合は一旦テキストエディタなどで整形してからコピペするのが良いと思います)

Claudeの出力
> usersテーブルの型の不整合を解消するmigrationを作成してください
  合わせて @docs/db_design_users.md も修正してください
  ⎿  Read docs/db_design_users.md (131 lines)

● usersテーブルのデータ型不整合を解消するマイグレーションを作成いたします。

● Update Todos
  ⎿  ☐ usersテーブルの型不整合を調査・確認         
     ☐ データ型修正のマイグレーションファイルを作成
     ☐ DB設計書を修正して正しい型情報に更新

● Bash(ls -la db/migrate/ | tail -5)

● Update Todos
  ⎿  ☒ usersテーブルの型不整合を調査・確認         
     ☐ データ型修正のマイグレーションファイルを作成
     ☐ DB設計書を修正して正しい型情報に更新

● Write(/path/to/project/db/migrate/[timestamp]_fix_users_column_types.rb)
  ⎿  Wrote 17 lines to /path/to/project/db/migrate/[timestamp]_fix_users_column_types.rb
     class FixUsersColumnTypes < ActiveRecord::Migration[7.0]
       def up
         # sign_in_countをintegerに修正
         change_column :users, :sign_in_count, :integer, default: 0

         # IPアドレスフィールドをstringに修正
         change_column :users, :current_sign_in_ip, :string
         change_column :users, :last_sign_in_ip, :string
       end

       def down
         # 元に戻すためのdown処理
         change_column :users, :sign_in_count, :datetime
         change_column :users, :current_sign_in_ip, :datetime
         change_column :users, :last_sign_in_ip, :datetime
       end
     end

● Update Todos
  ⎿  ☒ usersテーブルの型不整合を調査・確認         
     ☒ データ型修正のマイグレーションファイルを作成
     ☐ DB設計書を修正して正しい型情報に更新

● Update(/path/to/project/docs/db_design_users.md)
  ⎿  Updated /path/to/project/docs/db_design_users.md with 8 additions and 7 removals                                                             
       26    | remember_created_at | datetime | YES | NULL | ログイン状態記憶開始日時 |
       27    | push_token | text | YES | NULL | プッシュ通知用トークン |
       28    | last_sign_in_at | datetime | YES | NULL | 前回ログイン日時 |
       29 -  | sign_in_count | datetime | YES | NULL | ログイン回数(※型がdatetimeになっているが実際はintegerのはず) |
       29 +  | sign_in_count | int | YES | 0 | ログイン回数 |
       30    | current_sign_in_at | datetime | YES | NULL | 現在のログイン日時 |
       31 -  | current_sign_in_ip | datetime | YES | NULL | 現在のログインIPアドレス(※型がdatetimeになっているが実際はstring/inetのはず) |
       32 -  | last_sign_in_ip | datetime | YES | NULL | 前回のログインIPアドレス(※型がdatetimeになっているが実際はstring/inetのはず) |
       31 +  | current_sign_in_ip | varchar(255) | YES | NULL | 現在のログインIPアドレス |
       32 +  | last_sign_in_ip | varchar(255) | YES | NULL | 前回のログインIPアドレス |
       33    | failed_attempts | int | YES | 0 | ログイン失敗回数 |
       34    | unlock_token | varchar(255) | YES | NULL | アカウントロック解除用トークン |
       35    | locked_at | datetime | YES | NULL | アカウントロック日時 |
     ...
       112    
       113    ## 運用上の注意点
       114    
       115 -  ### データ型の不整合
       116 -  現在のマイグレーションファイルで以下のカラムの型定義に問題があります:
       117 -  - `sign_in_count`: datetime型になっているがinteger型であるべき
       118 -  - `current_sign_in_ip`, `last_sign_in_ip`: datetime型になっているがstring型またはinet型であるべき
       115 +  ### データ型修正履歴
       116 +  以下のカラムの型不整合を修正済み(マイグレーション: `[timestamp]_fix_users_column_types.rb`):
       117 +  - `sign_in_count`: datetime → integer(デフォルト値:0)
       118 +  - `current_sign_in_ip`: datetime → varchar(255)
       119 +  - `last_sign_in_ip`: datetime → varchar(255)
       120    
       121    ### セキュリティ考慮事項
       122    - パスワード変更通知はデフォルトでは無効(`send_password_change_notification`が`false`を返す)

● Update Todos
  ⎿  ☒ usersテーブルの型不整合を調査・確認         
     ☒ データ型修正のマイグレーションファイルを作成
     ☒ DB設計書を修正して正しい型情報に更新

● usersテーブルの型不整合を解消するマイグレーションを作成し、DB設計書も修正いたしました。

  作成した内容:

  1. マイグレーションファイル

  /path/to/project/db/migrate/[timestamp]_fix_users_column_types.rb

  修正内容:
  - sign_in_count: datetime → integer(デフォルト値: 0)
  - current_sign_in_ip: datetime → string
  - last_sign_in_ip: datetime → string

  2. DB設計書の修正

  /path/to/project/docs/db_design_users.md

  更新内容:
  - カラム構成表の型情報を正しい型に修正
  - 「データ型の不整合」セクションを「データ型修正履歴」に変更し、修正済みである旨を記載

  マイグレーション実行方法:

  bundle exec rails db:migrate

  このマイグレーションにより、usersテーブルのデータ型不整合が解消され、Deviseの標準的な型定義に合致するようになります。

 

 

役に立ったらシェアしていただけると嬉しいです
  • URLをコピーしました!
  • URLをコピーしました!
目次