Modules
Ruby’s module keyword does three jobs. Amethyst gives each its own keyword:
namespaces, protocols and mixins. Extensions, which stand in for Ruby’s open classes,
are also covered here.
Namespaces
Section titled “Namespaces”Namespaces group classes, constants, and methods. Declared with namespace, imported
with use.
# File-scoped — applies to the entire file, no block needednamespace MyApp::Models
# Block-scoped — explicit grouping within a filenamespace MyApp::Models do class User end
class Post endendImporting
Section titled “Importing”use System::Text::Jsonuse MyApp::ModelsNamespace Separator
Section titled “Namespace Separator”:: is used to reference types across namespaces in expression and type position:
MyApp::Models::User.newIn parameter declarations, the first :: after a name is the keyword argument marker;
subsequent :: are namespace separators:
def create(user:: MyApp::Models::User): Void# ^^ keyword arg ^^ namespace lookupThe parser disambiguates by context (parameter declaration vs expression).
Protocols
Section titled “Protocols”Protocols are pure contracts with optional default implementations, equivalent to C#
interfaces. Methods without a body must be implemented by the conforming type.
A protocol compiles to a .NET interface whose name has an I prefix: Comparable[T]
is IComparable<T> to C#. See .NET Naming Interop.
protocol Comparable[T] def <=>(other: T): Int # no body — must be implemented
def <(other: T): Bool # default implementation (self <=> other) < 0 end
def >(other: T): Bool (self <=> other) > 0 endendImplementing a Protocol
Section titled “Implementing a Protocol”class Temperature implements Comparable[Temperature]
getter value: Float
def <=>(other: Temperature): Int @value <=> other.value endendMultiple protocols:
class User implements Comparable[User], SerializableendProtocol Composition
Section titled “Protocol Composition”protocol Hashable def hash: Intend
protocol HashableComparable[T] implements Comparable[T] implements HashableendMixins
Section titled “Mixins”Mixins are reusable behavior with implementation that can be included into classes.
Unlike protocols, mixins can declare requirements — methods the including class must
provide. Both requires and abstract are accepted; they are equivalent.
mixin Enumerable[T] requires def each(&block: (T) -> Void): Void # including class must implement this — `abstract` is also accepted
def map[R](&block: (T) -> R): Array[R] result = [] of R each { |item| result << block.call(item) } result end
def select(&block: (T) -> Bool): Array[T] result = [] of T each { |item| result << item if block.call(item) } result end
def any?(&block: (T) -> Bool): Bool each { |item| return true if block.call(item) } false endendIncluding a Mixin
Section titled “Including a Mixin”class NumberList include Enumerable[Int]
def each(&block: (Int) -> Void): Void @items.each(&block) endendMultiple mixins:
class User include Timestamps, SearchableendExtending a Class with a Mixin
Section titled “Extending a Class with a Mixin”extend adds a mixin’s methods as class methods rather than instance methods.
include and extend can be used together:
mixin Searchable[T] def search(query: String): Array[T] # ... endend
mixin Timestamps property created_at: DateTime property updated_at: DateTimeend
class User extend Searchable[User] # adds search as a class method include Timestamps # adds created_at/updated_at as instance fieldsend
User.search("alice") # class method — from extenduser.created_at # instance method — from includeMultiple mixins can be extended at once:
class User extend Searchable[User], Auditableendextend self
Section titled “extend self”extend self inside a mixin makes all of the mixin’s own methods available as
class-level methods on itself — useful for utility mixins that can be called
directly or included into a class:
mixin MathUtils extend self
def clamp(value: Float, min: Float, max: Float): Float value < min ? min : (value > max ? max : value) endend
MathUtils.clamp(1.5, 0.0, 1.0) # called directly
class Renderer include MathUtils # clamp is now an instance method tooendMixin vs Protocol
Section titled “Mixin vs Protocol”| Protocol | Mixin | |
|---|---|---|
| Keyword | protocol |
mixin |
| Included with | implements |
include |
| Extended with | — | extend |
| Default implementation | Yes (optional) | Yes |
| Requirements | Implicit (no body) | requires def |
| Can have state | No | Yes |
Extensions
Section titled “Extensions”Extensions add methods to existing types without subclassing or modifying the original definition. Extension methods are statically resolved at compile time.
extension class String def palindrome?: Bool self == self.reverse end
def word_count: Int self.split(" ").length endend
extension class Array[T] def second: T? self.size > 1 ? self[1] : nil endendExtensions are visible within the file or namespace where they are defined, and can be
imported with use.