Exporting
An Entrypoint exports one value with export, and importing the Carton returns that value itself. Most Cartons have one main class or module, so they export it, as require would leave a constant behind:
# user.rb: the Entrypointclass User def initialize(name) = @name = nameend
export User # importers receive User itself# main.rbUser = import_relative 'user'User.new('Alice')- The value may be anything, including a Hash,
nil, orfalse. - Call
exportonce per Entrypoint; a second call raisesCarton::ExportError. Put other names inside the exported value instead, such asUser::VERSION. - A Symbol raises
Carton::ExportError, soexport def addcannot export:addby mistake. To export functions, define them on a module and export the module. - Bind the import to its own name,
User = import 'user'. Rename only to resolve a clash between Cartons:Module#name,inspect, and backtraces keep the original name.
A root module with private constants
Section titled “A root module with private constants”Export the root module and hide everything else with Ruby’s own private_constant, which holds across Boxes:
# lib/pricing.rb: the Entrypointmodule Pricing class Calculator end
module Internal end private_constant :Internal # stays inside the Cartonend
export Pricing# main.rbPricing = import 'pricing'Pricing::Calculator # publicPricing::Internal # NameError: private constant Pricing::Internal referencedA few values
Section titled “A few values”Keywords export a plain Hash, for values that need no module of their own:
# info.rb: the Entrypointexport version: '1.0', built_on: 'ci'# main.rbInfo = import_relative 'info'Info[:version] # => "1.0"import_relative('info') => { version: }Exports under plain require
Section titled “Exports under plain require”Only the imported Entrypoint’s export counts. In any other file, including one loaded with plain require by an app or by another Carton, export checks its argument, returns it, and does nothing else.
A gem can add export MyGem and keep working for apps that just require 'my_gem', as long as require 'carton' comes first so the method exists.
