Skip to content

Better syntax for private constants #9

@amomchilov

Description

@amomchilov

Constants are a bit of an odd ball. They don't respect the usual public/protected/private regions like methods do:

class C
  private

  SECRET = 123 # Not actually private!
end

This would need a separate private_constant :SECRET call.

Method def expressions evaluate to the name of the method that was defined, making this possible:

private def method; end

By comparison, constant definitions evaluate to their right hand side, so you can't just do this:

private_constant SECRET = 123 # TypeError: 123 is not a symbol nor a string

The clunky syntax of repeating the constant name every time you want to make it private, means that people don't actually do it in practice. Perhaps we can provide a better syntax for private constants?

Possible solution

Shopify's internal dev tool has a solution for this, using a scoped block, in which all constant definitions are made public. Example usage:

private_constants do
  SECRET = 123
  ANOTHER_CONST = 456
end

Possible implementation

# Mark all constants defined within the block as private
#: { -> void } -> void
def private_constants(&block)
  before = constants(false)
  yield
  private_constant(*(constants(false) - before))
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions