diff --git a/lib/ginny/models/mod.rb b/lib/ginny/models/mod.rb new file mode 100644 index 0000000..c70679a --- /dev/null +++ b/lib/ginny/models/mod.rb @@ -0,0 +1,51 @@ +module Ginny + # Used to generate a [module](https://ruby-doc.org/core-2.6.5/Module.html). + class Mod + + # List of modules to declare the module inside. Only one is required. + # @return [String] + attr_accessor :modules + # Description of the module. [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) is supported. + # @return [String] + attr_accessor :description + # String to write into the body of the module. + # @return [String] + attr_accessor :body + + # @return [void] + def initialize() + self.modules = [] + end + + # Constructor for a Func. Use `create`, not `new`. + # + # @param args [Hash] + # @return [Ginny::Func] + def self.create(args = {}) + m = Ginny::Mod.new() + m.modules = args[:modules] unless args[:modules].nil? + m.description = args[:description] + m.body = args[:body] + return m + end + + # Write generated code out to a file. + # + # @param folder [String] + # @param file [String] + # @return [String] + def generate(folder = ".", file: nil) + name = file.nil? ? self.file_name() : file + path = File.join(File.expand_path(folder), name) + File.open(path, "a") { |f| f.write(self.render() + "\n") } + return path + end + + # Return generated code as a string. + # + # @return [String] + def render() + return Ginny.mod(self.body, self.modules) + end + end +end diff --git a/test/ginny/mod_class_test.rb b/test/ginny/mod_class_test.rb new file mode 100644 index 0000000..60c7abf --- /dev/null +++ b/test/ginny/mod_class_test.rb @@ -0,0 +1,40 @@ +require "test_helper" + +class ModClassTest < Minitest::Test + + def test_mod_without_body + want = <<~RUBY.strip + module Level1 + module Level2 + end + end + RUBY + have = Ginny::Mod.create( + modules: ["Level1", "Level2"], + ).render() + assert_equal(want, have) + end + + def test_mod_with_body + want = <<~RUBY.strip + module Level1 + module Level2 + # Say hello. + # @return [String] + def greet() + end + end + end + RUBY + have = Ginny::Mod.create( + modules: ["Level1", "Level2"], + body: Ginny::Func.create( + name: "greet", + return_type: "String", + description: "Say hello.", + ).render(), + ).render() + assert_equal(want, have) + end + +end