ruby-rules

Ruby 编码规范:风格、模式、安全、测试。触发条件:.rb、Gemfile、.gemspec、Rails、ActiveRecord、Sidekiq、RSpec、Sorbet、rubocop。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "ruby-rules":https://skillpi.com/zh/skills/deepskill-68503947553259e2b71312960ed8746629a930c5d551196044bd7a04248225c8。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Ruby 编码规范:风格、模式、安全、测试。触发条件:.rb、Gemfile、.gemspec、Rails、ActiveRecord、Sidekiq、RSpec、Sorbet、rubocop。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: ruby-rules
description: "Ruby coding rules: style, patterns, security, testing. Triggers: .rb, Gemfile, .gemspec, Rails, ActiveRecord, Sidekiq, RSpec, Sorbet, rubocop."
effort: medium
user-invocable: false
allowed-tools: Read

Ruby Rules

These rules come from app/rules/ruby/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Ruby. Apply them when writing or reviewing Ruby code.

Ruby Coding Style

Naming

  • PascalCase: classes, modules.
  • snake_case: methods, variables, file names, directories.
  • UPPER_SNAKE: constants (MAX_RETRIES = 3).
  • Prefix boolean methods with predicate: empty?, valid?, admin?.
  • Suffix dangerous methods with !: save!, sort!, strip!.
  • Use _ prefix for intentionally unused variables: _unused.

Methods

  • Keep methods short: 5-10 lines ideal. Extract helper methods.
  • Use keyword arguments for methods with >2 parameters.
  • Use default parameter values instead of checking for nil.
  • Use def method_name = expression (Ruby 3.0+) for one-liners.
  • Prefer each over for loops. Use block-style iteration.
  • Return values implicitly (last expression). Use explicit return only for early exit.

Blocks, Procs, Lambdas

  • Use { } for single-line blocks. Use do...end for multi-line blocks.
  • Use &:method shorthand: names.map(&:upcase).
  • Use lambdas for strict argument checking. Use procs for flexible arity.
  • Use yield for single-block methods. Use explicit &block for storing/forwarding.

Classes

  • Use attr_reader, attr_writer, attr_accessor for simple getters/setters.
  • Use Struct for simple data containers. Use Data.define (Ruby 3.2+) for immutable.
  • Use modules for mixins: include for instance methods, extend for class methods.
  • Use frozen_string_literal: true magic comment at the top of every file.
  • Use private / protected keywords to control method visibility.

Collections

  • Use map, select, reject, reduce, flat_map for transformations.
  • Use each_with_object over inject when accumulating into a mutable object.
  • Use dig for safe nested hash/array access: data.dig(:user, :address, :city).
  • Use Hash#fetch with default for explicit missing-key handling.
  • Use Enumerable#lazy for large collection processing.

Pattern Matching (Ruby 3+)

  • Use case/in for structural pattern matching on hashes and arrays.
  • Use => pin operator to match against existing variables.
  • Use in pattern for conditional deconstruction in if statements.
  • Use pattern matching for API response parsing and validation.

Formatting

  • Use RuboCop for automated style enforcement.
  • Use .rubocop.yml committed to the repository for project conventions.
  • Max line length: 120 characters.
  • Two-space indentation. No tabs.
  • Use trailing commas in multi-line arrays and hashes.

Ruby Frameworks

Rails (General)

  • Follow Rails conventions: convention over configuration.
  • Use rails generate for scaffolding models, controllers, migrations.
  • Use strong parameters: params.require(:user).permit(:name, :email).
  • Use concerns for shared controller/model behavior.
  • Use config/routes.rb with resourceful routing: resources :users.
  • Use environment-specific configuration in config/environments/.

ActiveRecord

  • Use migrations for all schema changes. Never modify the database directly.
  • Use has_many, belongs_to, has_many :through for associations.
  • Use scopes for reusable query chains: scope :active, -> { where(active: true) }.
  • Use includes() for eager loading to prevent N+1 queries.
  • Use find_each for batch processing large record sets.
  • Use transaction blocks for atomic multi-record operations.

ActionController

  • Keep controllers thin: max 7 RESTful actions per controller.
  • Use before_action for authentication and authorization checks.
  • Use respond_to for content negotiation (JSON, HTML).
  • Use rescue_from for centralized error handling in controllers.
  • Use render json: with serializers (e.g., ActiveModelSerializers, Blueprinter).

Background Jobs

  • Use Sidekiq for Redis-backed background job processing.
  • Use ActiveJob as the abstraction layer over queue backends.
  • Use perform_later for async execution. Use perform_now only in tests.
  • Set retry count and discard_on / retry_on for error handling.
  • Use Sidekiq::Cron or clockwork for scheduled recurring jobs.

Sinatra / Hanami

  • Use Sinatra for lightweight APIs and microservices.
  • Use Hanami for structured, modular Ruby web applications.
  • Use Hanami actions (single-purpose) instead of fat controllers.
  • Use Hanami repositories for data access abstraction.

API Mode

  • Use rails new --api for API-only applications (no views, sessions).
  • Use Jbuilder or Blueprinter for JSON serialization.
  • Use Rack::Attack for rate limiting and throttling.
  • Use versioned API namespaces: namespace :v1 do ... end.
  • Use pagination with kaminari or pagy for collection endpoints.

Hotwire / Turbo

  • Use Turbo Frames for partial page updates without JavaScript.
  • Use Turbo Streams for real-time server-pushed DOM updates.
  • Use Stimulus for lightweight JavaScript behavior on HTML elements.
  • Keep JavaScript minimal: let the server render HTML.

Ruby Patterns

Error Handling

  • Rescue specific exceptions. Never bare rescue (catches StandardError).
  • Create domain exception hierarchies: class AppError < StandardError; end.
  • Use raise with message and optional cause: raise AppError, "msg".
  • Use retry with a counter for transient failures.
  • Use ensure for cleanup. Use else for code that runs only on success.

Service Objects

  • Use single-purpose service classes with a call method.
  • Use Dry::Monads Result type for operation outcomes.
  • Return Success(value) or Failure(error) from service calls.
  • Chain services with bind / fmap for pipeline composition.
  • Keep services stateless. Pass all data through method parameters.

Value Objects

  • Use Data.define (Ruby 3.2+) for immutable value objects.
  • Use Struct with keyword_init: true for lightweight data containers.
  • Use freeze on objects that should not be mutated after creation.
  • Override == and hash for value-based equality when needed.

Metaprogramming (Use Sparingly)

  • Use define_method over method_missing when possible.
  • Always define respond_to_missing? alongside method_missing.
  • Use class_attribute (Rails) for inheritable class-level configuration.
  • Prefer explicit code over DSL magic for maintainability.
  • Document metaprogrammed methods with YARD @!method directives.

Concurrency

  • Use Concurrent::Future (concurrent-ruby) for parallel operations.
  • Use Concurrent::Promise for composable async chains.
  • Use thread pools (Concurrent::FixedThreadPool) for bounded concurrency.
  • Use Ractor (Ruby 3+) for true parallel execution without GVL.
  • Use Mutex and Queue for thread-safe shared state access.

Module Patterns

  • Use include for shared behavior (instance methods).
  • Use prepend for wrapping/overriding existing methods (decorating).
  • Use extend for adding class-level methods from a module.
  • Use Concern (ActiveSupport) for Rails modules with class methods.
  • Keep modules focused: one responsibility per module.

Decorator Pattern

  • Use SimpleDelegator for transparent object wrapping.
  • Use Draper gem for view-layer decorators in Rails.
  • Prefer composition (wrapping) over inheritance for adding behavior.
  • Use Module#prepend for method-level decoration without wrapper classes.

Anti-Patterns

  • Monkey-patching core classes: use refinements or wrapper methods.
  • Callbacks for business logic (Rails): use service objects.
  • God objects: split into focused classes with single responsibility.
  • N+1 queries: use includes(), preload(), eager_load().
  • Using eval or send with user input: remote code execution risk.

Ruby Security

Mass Assignment

  • Use strong parameters in controllers: params.require(:user).permit(:name, :email).
  • Never use params.permit! or pass unsanitized params to create/update.
  • Use attr_readonly for fields that should never be updated after creation.
  • Audit update_columns and update_attribute usage (bypass validations).

SQL Injection

  • Use ActiveRecord query interface with parameterized conditions.
  • Use where(name: value) hash syntax or where("name = ?", value) placeholders.
  • Never interpolate user input into where() strings: where("name = '#{input}'").
  • Use sanitize_sql_array if building raw SQL fragments is unavoidable.
  • Audit all find_by_sql, execute, and Arel.sql calls.

XSS Prevention

  • Rails auto-escapes ERB output with <%= %>. Never use raw() with user data.
  • Use sanitize() helper for allowing limited HTML tags.
  • Set Content-Security-Policy header in config/initializers/content_security_policy.rb.
  • Use content_tag helper for safe HTML generation.
  • Mark strings as html_safe only when content is guaranteed safe.

CSRF Protection

  • Use protect_from_forgery with: :exception in ApplicationController.
  • Use authenticity_token in all forms (Rails includes it by default).
  • Use X-CSRF-Token header for AJAX requests from JavaScript.
  • Exempt only webhook endpoints from CSRF (with payload signature verification).

Authentication

  • Use Devise or has_secure_password for authentication.
  • Use bcrypt for password hashing (included with has_secure_password).
  • Implement account lockout after N failed login attempts.
  • Use SecureRandom.urlsafe_base64 for generating tokens.
  • Store sessions server-side (Redis/database) instead of cookie store in production.

Authorization

  • Use Pundit or CanCanCan for authorization logic.
  • Define policies per model: class UserPolicy < ApplicationPolicy.
  • Check ownership in policies, not just role membership.
  • Use authorize @resource in every controller action.
  • Default deny: require explicit authorization for all actions.

Secrets Management

  • Use Rails.application.credentials for encrypted secrets.
  • Use EDITOR="vim" bin/rails credentials:edit to manage secrets.
  • Use per-environment credentials: credentials/production.yml.enc.
  • Never commit master.key or production.key to version control.
  • Use environment variables for CI/CD and containerized deployments.

Dependency Security

  • Run bundle audit check --update for known vulnerability scanning.
  • Use Dependabot for automated dependency update PRs.
  • Pin gem versions in Gemfile. Review Gemfile.lock changes carefully.
  • Use bundler-audit in CI pipeline as a required check.
  • Update Rails promptly when security patches are released.

Ruby Testing

Framework

  • Use RSpec as the primary test framework.
  • Use Minitest for lightweight, stdlib-based testing.
  • Use FactoryBot for test data generation.
  • Use WebMock or VCR for HTTP request stubbing.

File Naming

  • RSpec: spec/models/user_spec.rb mirroring app/models/user.rb.
  • Minitest: test/models/user_test.rb mirroring source structure.
  • Support files: spec/support/ for shared helpers and configurations.
  • Use spec/rails_helper.rb for Rails-specific RSpec configuration.

Structure (RSpec)

  • Use describe for the class/method under test. Use context for scenarios.
  • Use it for individual test cases with clear descriptions.
  • Use let for lazy-evaluated test data. Use let! for eager evaluation.
  • Use before / after blocks for setup and teardown.
  • Use subject for the primary object under test.

Matchers (RSpec)

  • Use expect(result).to eq(expected) for equality.
  • Use expect(result).to be_truthy, be_falsy, be_nil.
  • Use expect { action }.to raise_error(FooError) for exception testing.
  • Use expect { action }.to change { User.count }.by(1) for side effects.
  • Use expect(list).to include(item), contain_exactly(a, b, c).
  • Use expect(result).to match(hash_including(key: value)) for partial matching.

Mocking (RSpec)

  • Use instance_double(UserService) for verified doubles.
  • Stub: allow(mock).to receive(:find).with(1).and_return(user).
  • Verify: expect(mock).to have_received(:save).once.
  • Use receive_messages(method1: val1, method2: val2) for multi-stubbing.
  • Use class_double for stubbing class methods.
  • Avoid stubbing the object under test. Stub only collaborators.

FactoryBot

  • Define factories in spec/factories/: FactoryBot.define { factory :user { ... } }.
  • Use create for persisted records. Use build for in-memory only.
  • Use traits for variations: create(:user, :admin).
  • Use build_stubbed for fast tests that do not need database.
  • Use sequences for unique attributes: sequence(:email) { |n| "user#{n}@test.com" }.

Rails Testing

  • Use request specs for API endpoint testing (RSpec).
  • Use system specs with Capybara for browser integration tests.
  • Use DatabaseCleaner or use_transactional_fixtures for test isolation.
  • Use travel_to for time-dependent test scenarios.
  • Use ActiveJob::TestHelper for testing background jobs inline.

Best Practices

  • Test behavior, not implementation. Do not test private methods directly.
  • Use shared_examples for testing common behavior across classes.
  • Use aggregate_failures to collect multiple assertion failures.
  • Keep tests fast: stub external services, use build_stubbed.
  • Run bundle exec rspec --format documentation for readable output.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值75/100

亮点

  • 提供 Ruby 编码风格、框架使用、安全实践和测试规范的全面指导
  • 覆盖 Rails、ActiveRecord、Sidekiq、RSpec 等主流 Ruby 技术栈
  • 适用于 Ruby 开发者日常编码与代码审查场景
触发精准85/100

亮点

  • 触发条件明确列出 .rb、Gemfile、.gemspec、Rails、ActiveRecord、Sidekiq、RSpec、Sorbet、rubocop 等关键词
  • 覆盖 Ruby 开发常见文件类型与框架,边界清晰
结构规范75/100

待提升项

  • 缺少 When to Use 章节和端到端示例 原报告严重程度:轻微

    文档结构良好但未包含显式的使用场景说明和完整端到端示例

    改进建议:建议补充 When to Use 章节说明适用场景,并增加一个完整 Ruby 项目的端到端规范示例

亮点

  • 文档结构清晰,分五大模块组织内容
  • frontmatter 完整,包含 name/description/effort/user-invocable/allowed-tools
  • 每模块下细分条目,有具体代码示例
执行可靠95/100

亮点

  • 纯文档型规则集,无外部工具调用风险
  • 所有建议均为 Ruby 社区公认最佳实践,来源可靠
  • 内容静态,无运行时错误风险
证据可验 (前四项均值)83/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。