It was announced recently that Ameba is going to be extendable. That means any developer can create his own extension and use together with Ameba’s engine.
Here we will be following through the steps on how to create such an extension and use it.
It is going to be
crystal-docs extension, where a new rule will be implemented which will enforce classes to have documentation.
Creating a new Ameba extension is as simple as creating a new Crystal library:
$ crystal init lib crystal-docs && cd crystal-docs
and adding Ameba as a dependency to
It needs to be a development dependency because we don’t want to force the end application to be dependent on a specific version of Ameba.
Ameba enforces rules to be extended from
Rule::Base entity and to be a struct. Let’s create one:
A couple of things are defined here:
propertiesdefines a dsl for configurable rule properties. We only have a rule description.
MSGdefines a constant for the error message to be reported.
def test(source)is an entry point of the rule. Here the method accepts a source file and passes it to the node visitor, which allows us filter the
ClassDefnodes in the method below.
def test(source, node : Crystal::ClassDef)is a method which does an actual job. The implementation is pretty self explained: it filters out node, which have public visibility and do not have (or have empty) docs.
The extension is pretty much done. Let’s try to use it.
Somewhere in a separate project we want to plug-in the ameba engine and the extension we made.
To do that, we need to add a development dependencies for both of this projects:
Then we install those deps:
$ shards install
It will create
bin/ameba.cr file which is needed to built the ameba together with modules.
First, we need to enable the module:
require "ameba/cli" # requires Ameba's cli
And now we are ready to build and run it:
$ crystal build bin/ameba.cr -o bin/ameba
The results are displayed below.
crystal-docs extension in action:
We made a small Ameba extension and used that in a third-party project. Of course, this was just an example of the rule and not a production ready solution. However, it is a perfect example of the power of Ameba’s modules.
The sources are availabe on Github.