Repository Summary
Checkout URI | https://github.com/rock-core/tools-metaruby.git |
VCS Type | git |
VCS Version | master |
Last Updated | 2025-03-24 |
Dev Status | MAINTAINED |
CI status | No Continuous Integration |
Released | RELEASED |
Tags | No category tags. |
Contributing |
Help Wanted (0)
Good First Issues (0) Pull Requests to Review (0) |
Packages
Name | Version |
---|---|
metaruby | UNKNOWN |
README
Metamodelling in the Ruby type system
MetaRuby is a library that allows to (ab)use the Ruby type system to create reflexive programs: create a specialized modelling API (a.k.a. “a DSL”) at the class/module level and then get access to this model information from the objects.
This page will describe the various functionality that metaruby provides to help modelling in Ruby.
This page will reuse one of the most overused example of modelling: a car and colors.
Models
Using MetaRuby, models can either be represented by Ruby classes or by Ruby modules. You use the first one when you want to model something from which an object can be created, in our example: a car. You use the second for things that cannot be instanciated, but can be used as attributes of another object, in our example: a color.
Another point of terminology: metamodel. The metamodel is the model-of-the-model, i.e. it is the bits and pieces that allow to describe a model (the model itself describing an object). As you will see, metamodels in MetaRuby are all described in modules.
Models as classes
The metamodel of models that are represented by classes must include {MetaRuby::ModelAsClass} and are then used to extend said class
module Models
module Car
include MetaRuby::ModelAsClass
end
end
class Car
extend Models::Car
end
Then, creating a new Car model is done by subclassing the Car class:
class Peugeot < Car
# Call methods from the modelling DSL defined by Models::Car
end
This creates a named model, i.e. a model that can be accessed by name. Another way is to create an anonymous model by calling {MetaRuby::ModelAsClass#new_submodel new_submodel}:
model = Car.new_submodel do
# Call methods from the modelling DSL defined by Models::Car
end
Note that this mechanism naturally extends to submodels-of-submodels, e.g.
class P806 < Peugeot
# Call methods from the modelling DSL defined by Models::Car
end
Models as modules
The metamodel of models that are represented by modules must include {MetaRuby::ModelAsModule} and are then used to extend said module
module Models
module Color
include MetaRuby::ModelAsModule
end
end
module Color
extend Models::Color
end
Then, creating a new Color model is done by calling {MetaRuby::ModelAsModule#new_submodel new_submodel} on Color
red = Color.new_submodel
A common pattern is to define a method on the Module class, that creates new models and assigns them to constants. MetaRuby provides a helper method for this purpose, that we strongly recommend you use:
~~~ class Module def color(name, &block)
File truncated at 100 lines see the full file