Skip to content

Commit

Permalink
Add module generation
Browse files Browse the repository at this point in the history
  • Loading branch information
tcd committed Jan 2, 2020
1 parent ab77460 commit 8842e06
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
51 changes: 51 additions & 0 deletions 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<Symbol>]
# @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
40 changes: 40 additions & 0 deletions 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

0 comments on commit 8842e06

Please sign in to comment.