Using java enum, in jruby
Using an interface to supply global constants is somewhat frowned upon (actually as is any global constants file). The slightly less toxic version is to create a final class as we did in previous article. It is slightly harder to access the constants in jruby but at least you are not polluting the global namespace. Enums are preferred but still probably evidence of poor design. Here we choose to create a several instances of enum to deal with a portion of PConstants (lumping all constants together does not make much sense anyway).
Requirements
Requires JRuby, maven
The enum tests
# frozen_string_literal: true
require 'java'
require_relative 'test_helper'
require_relative '../lib/pconstants'
module Constants
java_import 'processing.core.Axis'
java_import 'processing.core.RenderMode'
java_import 'processing.core.Shapes'
end
class SpecTest < Minitest::Test
include Constants
def test_constants_is_a_module
assert_equal Module, Constants.class, 'Constants not recognized as a module'
end
def test_p3d
assert_equal String, RenderMode::P3D.render_mode.class, "failed #{:P3D} is a string"
assert_equal Java::JavaLang::String, RenderMode::P3D.render_mode.to_java(:string).class, "failed #{:P3D} can be cast as a java string"
assert_equal 'processing.opengl.PGraphics3D', RenderMode::P3D.render_mode, "failed #{:P3D} lookup"
end
def test_numeric
assert_equal 0, Axis::X.get_axis, "failed #{:X} lookup"
assert_equal 3, Shapes::CURVE_VERTEX.shape, "failed #{:CURVE_VERTEX} lookup"
end
end
The Axis enum file
/*
Use of enums is preferred for global access, however the general
recommendation is to include constants in classes that use them.
*/
package processing.core;
public enum Axis {
X(0),
Y(1),
Z(2);
Axis(int val) {
this.axis = val;
}
public int getAxis(){
return this.axis;
}
private final int axis;
}
The RenderMode enum file
/*
Use of enums is preferred for global access, however the general
recommendation is to include constants in classes that use them.
*/
package processing.core;
public enum RenderMode {
JAVA2D("processing.awt.PGraphicsJava2D"),
P2D("processing.opengl.PGraphics2D"),
P3D("processing.opengl.PGraphics3D"),
FX2D("processing.javafx.PGraphicsFX2D"),
PDF("processing.pdf.PGraphicsPDF"),
SVG("processing.svg.PGraphicsSVG"),
DXF("processing.dxf.RawDXF");
RenderMode(String val) {
this.mode = val;
}
private final String mode;
public String renderMode(){
return this.mode;
}
}
The Shapes enum file
/*
Use of enums is preferred for global access, however the general
recommendation is to include constants in classes that use them.
*/
package processing.core;
public enum Shapes {
VERTEX(0),
BEZIER_VERTEX(1),
QUADRATIC_VERTEX(2),
CURVE_VERTEX(3),
BREAK(4);
Shapes(int val) {
this.shape = val;
}
private final int shape;
public int getShape() {
return this.shape;
}
}