Skip to content

Add Module#private_constants block for concise private constants#34

Open
mliem2k wants to merge 1 commit into
Shopify:mainfrom
mliem2k:feature/private-constants-block
Open

Add Module#private_constants block for concise private constants#34
mliem2k wants to merge 1 commit into
Shopify:mainfrom
mliem2k:feature/private-constants-block

Conversation

@mliem2k

@mliem2k mliem2k commented Jul 12, 2026

Copy link
Copy Markdown

Summary

Constants don't respect private/public regions the way methods do, so making one private normally means repeating its name in a separate private_constant call:

class Configuration
  DEFAULT_TIMEOUT = 30
  private_constant :DEFAULT_TIMEOUT
end

This implements the private_constants do ... end API suggested in the issue: every constant defined directly within the block is automatically marked private via private_constant once the block finishes.

class Configuration
  private_constants do
    DEFAULT_TIMEOUT = 30
  end
end

Configuration::DEFAULT_TIMEOUT # ❌ NameError: private constant Configuration::DEFAULT_TIMEOUT referenced

It only marks constants introduced during the block (diffing constants(false) before/after), so pre-existing constants are left untouched, and it's a no-op if the block doesn't define any new constants (avoiding Ruby's "private_constant with no argument is just ignored" warning).

Added to lib/type_toolkit/ext/module.rb, next to interface!, since it's a similar small Module-level extension. Also added a README section under "Tools".

Test plan

  • bundle exec rake test — 95 runs, 0 failures
  • bundle exec rake rubocop — no offenses
  • bundle exec rake typecheck / typecheck_prism — no errors
  • New specs in spec/private_constants_spec.rb cover: constants defined via = and via class/module keywords being made private, constants outside the block staying public, unqualified access still working from the defining scope, a no-op empty block, and exceptions inside the block propagating normally

Fixes #9

Constants don't respect private/public regions the way methods do, so
making one private normally means repeating its name in a separate
private_constant call. private_constants { ... } marks every constant
defined within the block as private automatically.
Copilot AI review requested due to automatic review settings July 12, 2026 12:33

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Better syntax for private constants

2 participants