diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..f2ffa9b --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,40 @@ +name: Ruby Gem Tests + +on: + push: + branches: + - main + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '3.2.2' + + steps: + - uses: actions/checkout@v4 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Install dependencies + run: bundle install + - name: Run tests + run: bundle exec rake test + continue-on-error: true + id: run_tests + - name: Report test results + if: always() + run: | + if ${{ steps.run_tests.outcome == 'success' }}; then + echo "Tests passed successfully!" + exit 0 + else + echo "Tests failed. Please check the logs for details." + exit 1 + fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9106b2a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..762eebb --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,8 @@ +AllCops: + TargetRubyVersion: 3.0 + +Style/StringLiterals: + EnforcedStyle: double_quotes + +Style/StringLiteralsInInterpolation: + EnforcedStyle: double_quotes diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..accc57a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +## [Unreleased] + +## [0.1.0] - 2024-08-04 + +- Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..67fe8ce --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[INSERT CONTACT METHOD]. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..c495367 --- /dev/null +++ b/Gemfile @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in typesmith.gemspec +gemspec + +gem "rake", "~> 13.0" + +gem "minitest", "~> 5.16" + +gem "rubocop", "~> 1.21" + +gem "simplecov", group: "test" +gem "zeitwerk", "~> 2.6" + +gem "activesupport", "~> 7.1" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..f4d78f8 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,82 @@ +PATH + remote: . + specs: + typesmith (0.1.0) + +GEM + remote: https://rubygems.org/ + specs: + activesupport (7.1.3.4) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + ast (2.4.2) + base64 (0.2.0) + bigdecimal (3.1.8) + concurrent-ruby (1.3.3) + connection_pool (2.4.1) + docile (1.4.0) + drb (2.2.1) + i18n (1.14.5) + concurrent-ruby (~> 1.0) + json (2.7.2) + language_server-protocol (3.17.0.3) + minitest (5.24.1) + mutex_m (0.2.0) + parallel (1.25.1) + parser (3.3.4.0) + ast (~> 2.4.1) + racc + racc (1.8.1) + rainbow (3.1.1) + rake (13.2.1) + regexp_parser (2.9.2) + rexml (3.3.4) + strscan + rubocop (1.65.1) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.4, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.31.3) + parser (>= 3.3.1.0) + ruby-progressbar (1.13.0) + simplecov (0.22.0) + docile (~> 1.1) + simplecov-html (~> 0.11) + simplecov_json_formatter (~> 0.1) + simplecov-html (0.12.3) + simplecov_json_formatter (0.1.4) + strscan (3.1.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (2.5.0) + zeitwerk (2.6.17) + +PLATFORMS + arm64-darwin-23 + ruby + +DEPENDENCIES + activesupport (~> 7.1) + minitest (~> 5.16) + rake (~> 13.0) + rubocop (~> 1.21) + simplecov + typesmith! + zeitwerk (~> 2.6) + +BUNDLED WITH + 2.5.14 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..8c72796 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 John Panos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6716028 --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +# Typesmith + +TODO: Delete this and the text below, and describe your gem + +Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/typesmith`. To experiment with that code, run `bin/console` for an interactive prompt. + +## Installation + +TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org. + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG + +## Usage + +TODO: Write usage instructions here + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/typesmith. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/typesmith/blob/main/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in the Typesmith project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/typesmith/blob/main/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..2bf771f --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "minitest/test_task" + +Minitest::TestTask.create + +require "rubocop/rake_task" + +RuboCop::RakeTask.new + +task default: %i[test rubocop] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..e1bab00 --- /dev/null +++ b/bin/console @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "typesmith" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/lib/typesmith.rb b/lib/typesmith.rb new file mode 100644 index 0000000..809137c --- /dev/null +++ b/lib/typesmith.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +require "zeitwerk" +require "active_support" +require "active_support/core_ext" + +module Typesmith + class Error < StandardError; end + class << self + attr_accessor :loader + + def setup + self.loader = Zeitwerk::Loader.for_gem + loader.setup + end + end +end + +Typesmith.setup diff --git a/lib/typesmith/array_property.rb b/lib/typesmith/array_property.rb new file mode 100644 index 0000000..4bd5022 --- /dev/null +++ b/lib/typesmith/array_property.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module Typesmith + class ArrayProperty < SimpleProperty + def to_typescript + "#{camelized_name}#{optional_suffix}: #{get_type_string(type)}[];" + end + + def process_value(value) + value.map { |v| super(v) } + end + end +end diff --git a/lib/typesmith/base_property.rb b/lib/typesmith/base_property.rb new file mode 100644 index 0000000..d7bedbe --- /dev/null +++ b/lib/typesmith/base_property.rb @@ -0,0 +1,62 @@ +# frozen_string_literal: true + +module Typesmith + class BaseProperty + class InvalidTypeError < StandardError; end + PRIMITIVE_TYPES = %i[string number boolean any null undefined void never unknown object Date].freeze + + attr_reader :name, :optional + + def initialize(name, optional: false) + @name = name + @optional = optional + end + + def to_typescript + raise NotImplementedError, "Subclasses must implement to_typescript" + end + + def process_value(value) + value + end + + protected + + def optional_suffix + optional ? "?" : "" + end + + def camelized_name + name.to_s.camelize(:lower) + end + + def get_type_string(type) + case type + when Class + type < Definition ? type.typescript_type_name : type.to_s + when Array + "#{get_type_string(type.first)}[]" + when Hash + key_type, value_type = type.first + "{ [key: #{get_type_string(key_type)}]: #{get_type_string(value_type)} }" + else + type.to_s + end + end + + def self.validate_type(type) + return if PRIMITIVE_TYPES.include?(type) || type.is_a?(Class) && type < Definition + + case type + when Array + validate_type(type.first) + when Hash + key_type, value_type = type.first + validate_type(key_type) + validate_type(value_type) + else + raise InvalidTypeError, "Invalid type: #{type}. Must be a primitive type or a Definition subclass." + end + end + end +end diff --git a/lib/typesmith/definition.rb b/lib/typesmith/definition.rb new file mode 100644 index 0000000..b78969e --- /dev/null +++ b/lib/typesmith/definition.rb @@ -0,0 +1,100 @@ +# frozen_string_literal: true + +require "active_support/core_ext/string/inflections" +require "active_support/core_ext/hash/keys" + +module Typesmith + class Definition + class Error < StandardError; end + class UndefinedAttributeError < Error; end + + class << self + def property(name, type: nil, optional: false, &block) + properties[name] = case type + when Array + ArrayProperty.new(name, type.first, optional: optional) + when Hash + IndexedProperty.new(name, type.keys.first, type.values.first, optional: optional) + when nil + block ? NestedProperty.new(name, block, optional: optional) : SimpleProperty.new(name, :any, optional: optional) + else + SimpleProperty.new(name, type, optional: optional) + end + end + + def properties + @properties ||= {} + end + + def to_typescript + generate_typescript_type(name.demodulize, properties) + end + + def typescript_type_name + name.demodulize + end + + private + + def generate_typescript_type(name, props) + [ + "export interface #{name} {", + generate_properties(props, 1), + "}" + ].join("\n") + end + + def generate_properties(props, indent_level = 0) + props.map do |_, prop| + lines = prop.to_typescript.split("\n") + lines.map { |line| " " * indent_level + line }.join("\n") + end.join("\n") + end + end + + attr_reader :attributes + + def properties + self.class.properties + end + + def initialize(attributes = {}) + @attributes = {} + process_attributes(attributes.deep_symbolize_keys) + validate_required_attributes + end + + def to_json(*_args) + @attributes + end + + def as_json(*_args) + @attributes + end + + private + + def process_attributes(attrs) + undefined_attrs = attrs.keys - properties.keys + raise UndefinedAttributeError, "Undefined attributes: #{undefined_attrs.join(", ")}" if undefined_attrs.any? + + properties.each do |key, prop| + if attrs.key?(key) + @attributes[key] = prop.process_value(attrs[key]) + define_singleton_method(key) { @attributes[key] } + else + define_singleton_method(key) { nil } + end + end + end + + def validate_required_attributes + missing_attrs = properties.reject { |_, v| v.optional }.keys - @attributes.keys + raise ArgumentError, "Missing required attributes: #{missing_attrs.join(", ")}" if missing_attrs.any? + end + + def camelize_keys(hash) + hash.deep_transform_keys { |key| key.to_s.camelize(:lower) } + end + end +end diff --git a/lib/typesmith/generator.rb b/lib/typesmith/generator.rb new file mode 100644 index 0000000..19f9b36 --- /dev/null +++ b/lib/typesmith/generator.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require "active_support" +require "active_support/core_ext" +require "active_support/core_ext/string/inflections" + +module Typesmith + class Generator + BASE_OUTPUT_DIR = File.join("app", "javascript", "types", "__generated__") + + def self.generate_all + new.generate_all + end + + def generate_all + definition_classes = ObjectSpace.each_object(Class).select { |klass| klass < Definition }.filter(&:name) + generated_files = definition_classes.map { |klass| generate_typescript_file(klass) } + generate_index_files(generated_files) + + puts "TypeScript types and index files have been generated in the '#{BASE_OUTPUT_DIR}' directory" + end + + private + + def generate_typescript_file(klass) + module_path = klass.name.underscore + directory = File.join(BASE_OUTPUT_DIR, File.dirname(module_path)) + FileUtils.mkdir_p(directory) + + file_name = "#{File.basename(module_path)}.ts" + content = generate_imports(klass) + content += klass.to_typescript + + full_path = File.join(directory, file_name) + File.write(full_path, content) + puts "Generated type for #{klass.name} in #{full_path}" + + { path: full_path, type_name: klass.typescript_type_name } + end + + def generate_imports(klass) + imports = Set.new + + klass.properties.each_value do |prop| + add_import_for_property(imports, prop) + end + + import_statements = imports.map do |type| + relative_path = calculate_relative_path(klass.name, type.name) + "import { #{type.typescript_type_name} } from '#{relative_path}';" + end + + if import_statements.present? + "#{import_statements.join("\n")}\n\n" + else + "" + end + end + + def add_import_for_property(imports, prop) + case prop + when SimpleProperty, ArrayProperty + add_import_for_type(imports, prop.type) + when IndexedProperty + add_import_for_type(imports, prop.value_type) + when NestedProperty + nested_class = Class.new(Definition) + nested_class.class_eval(&prop.block) + nested_class.properties.each_value do |nested_prop| + add_import_for_property(imports, nested_prop) + end + end + end + + def add_import_for_type(imports, type) + case type + when Class + imports.add(type) if type < Definition + when Array + add_import_for_type(imports, type.first) + when Hash + add_import_for_type(imports, type.values.first) + end + end + + def calculate_relative_path(from_class, to_class) + from_parts = from_class.underscore.split("/") + to_parts = to_class.underscore.split("/") + + from_dir = from_parts[0..-2] + to_dir = to_parts[0..-2] + + common_prefix_length = 0 + from_dir.zip(to_dir).each do |from, to| + break if from != to + + common_prefix_length += 1 + end + + up_levels = from_dir.length - common_prefix_length + down_path = to_dir[common_prefix_length..] + + relative_path = [".."] * up_levels + down_path + [to_parts.last] + "./#{relative_path.join("/")}" + end + + def generate_index_files(generated_files) + directories = generated_files.map { |file| File.dirname(file[:path]) }.uniq + + directories.each do |directory| + files_in_directory = generated_files.select { |file| File.dirname(file[:path]) == directory } + + index_content = files_in_directory.map do |file| + file_name = File.basename(file[:path], ".ts") + "export { #{file[:type_name]} } from './#{file_name}';" + end.join("\n") + + index_path = File.join(directory, "index.ts") + File.write(index_path, index_content) + puts "Generated index file in #{index_path}" + end + end + end +end diff --git a/lib/typesmith/indexed_property.rb b/lib/typesmith/indexed_property.rb new file mode 100644 index 0000000..9643bfd --- /dev/null +++ b/lib/typesmith/indexed_property.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module Typesmith + class IndexedProperty < BaseProperty + attr_reader :key_type, :value_type + + def initialize(name, key_type, value_type, optional: false) + super(name, optional: optional) + @key_type = key_type + @value_type = value_type + self.class.validate_type(key_type) + self.class.validate_type(value_type) + end + + def to_typescript + "#{camelized_name}#{optional_suffix}: { [key: #{get_type_string(key_type)}]: #{get_type_string(value_type)} };" + end + + def process_value(value) + value.transform_values do |v| + if value_type.is_a?(Array) + v.map { |item| SimpleProperty.new(nil, value_type.first).process_value(item) } + else + SimpleProperty.new(nil, value_type).process_value(v) + end + end + end + end +end diff --git a/lib/typesmith/nested_property.rb b/lib/typesmith/nested_property.rb new file mode 100644 index 0000000..d88e278 --- /dev/null +++ b/lib/typesmith/nested_property.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +module Typesmith + class NestedProperty < BaseProperty + attr_reader :block + + def initialize(name, block, optional: false) + super(name, optional: optional) + @block = block + end + + def to_typescript + nested_class = Class.new(Definition) + nested_class.class_eval(&block) + [ + "#{camelized_name}#{optional_suffix}: {", + nested_class.send(:generate_properties, nested_class.properties).split("\n").map do |line| + " #{line}" + end.join("\n"), + "};" + ].join("\n") + end + + def process_value(value) + nested_class = Class.new(Definition) + nested_class.class_eval(&block) + nested_class.new(value).attributes + end + end +end diff --git a/lib/typesmith/simple_property.rb b/lib/typesmith/simple_property.rb new file mode 100644 index 0000000..99d1838 --- /dev/null +++ b/lib/typesmith/simple_property.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Typesmith + class SimpleProperty < BaseProperty + attr_reader :type + + def initialize(name, type, optional: false) + super(name, optional: optional) + @type = type + self.class.validate_type(type) + end + + def to_typescript + "#{camelized_name}#{optional_suffix}: #{get_type_string(type)};" + end + + def process_value(value) + if type.is_a?(Class) && type < Definition + type.new(value).attributes + else + value + end + end + end +end diff --git a/lib/typesmith/version.rb b/lib/typesmith/version.rb new file mode 100644 index 0000000..aefb12d --- /dev/null +++ b/lib/typesmith/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Typesmith + VERSION = "0.1.0" +end diff --git a/sig/typesmith.rbs b/sig/typesmith.rbs new file mode 100644 index 0000000..5180504 --- /dev/null +++ b/sig/typesmith.rbs @@ -0,0 +1,4 @@ +module Typesmith + VERSION: String + # See the writing guide of rbs: https://github.com/ruby/rbs#guides +end diff --git a/test/array_property_test.rb b/test/array_property_test.rb new file mode 100644 index 0000000..60bcdbd --- /dev/null +++ b/test/array_property_test.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "typesmith" + +class ArrayPropertyTest < Minitest::Test + class CustomType < Typesmith::Definition + property :id, type: :number + property :name, type: :string + end + + def setup + @string_array = Typesmith::ArrayProperty.new("tags", :string) + @number_array = Typesmith::ArrayProperty.new("scores", :number) + @boolean_array = Typesmith::ArrayProperty.new("flags", :boolean) + @custom_array = Typesmith::ArrayProperty.new("items", CustomType) + @optional_array = Typesmith::ArrayProperty.new("optional_tags", :string, optional: true) + @nested_array = Typesmith::ArrayProperty.new("matrix", [:number]) + end + + def test_initialization + assert_equal "tags", @string_array.name + assert_equal :string, @string_array.type + refute @string_array.optional + assert @optional_array.optional + end + + def test_to_typescript + assert_equal "tags: string[];", @string_array.to_typescript + assert_equal "scores: number[];", @number_array.to_typescript + assert_equal "flags: boolean[];", @boolean_array.to_typescript + assert_equal "items: CustomType[];", @custom_array.to_typescript + assert_equal "optionalTags?: string[];", @optional_array.to_typescript + assert_equal "matrix: number[][];", @nested_array.to_typescript + end + + def test_process_value + assert_equal %w[a b c], @string_array.process_value(%w[a b c]) + assert_equal [1, 2, 3], @number_array.process_value([1, 2, 3]) + assert_equal [true, false, true], @boolean_array.process_value([true, false, true]) + + custom_values = [{ id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }] + processed_custom = @custom_array.process_value(custom_values) + assert_equal custom_values, processed_custom + assert_instance_of Array, processed_custom + assert_instance_of Hash, processed_custom.first + + assert_equal [[1, 2], [3, 4]], @nested_array.process_value([[1, 2], [3, 4]]) + end + + def test_validate_type + assert_nil Typesmith::ArrayProperty.validate_type(:string) + assert_nil Typesmith::ArrayProperty.validate_type(:number) + assert_nil Typesmith::ArrayProperty.validate_type(:boolean) + assert_nil Typesmith::ArrayProperty.validate_type(CustomType) + assert_nil Typesmith::ArrayProperty.validate_type([:number]) + + assert_raises(Typesmith::BaseProperty::InvalidTypeError) do + Typesmith::ArrayProperty.new("invalid", :invalid_type) + end + end + + def test_camelized_name + assert_equal "tags", @string_array.send(:camelized_name) + assert_equal "scores", @number_array.send(:camelized_name) + assert_equal "optionalTags", @optional_array.send(:camelized_name) + end + + def test_get_type_string + assert_equal "string[]", @string_array.send(:get_type_string, @string_array.type) + assert_equal "number[]", @number_array.send(:get_type_string, @number_array.type) + assert_equal "boolean[]", @boolean_array.send(:get_type_string, @boolean_array.type) + assert_equal "CustomType[]", @custom_array.send(:get_type_string, @custom_array.type) + assert_equal "number[][]", @nested_array.send(:get_type_string, @nested_array.type) + end +end diff --git a/test/base_property_test.rb b/test/base_property_test.rb new file mode 100644 index 0000000..eadf5b0 --- /dev/null +++ b/test/base_property_test.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +require "minitest/autorun" + +require "typesmith" + +class BasePropertyTest < Minitest::Test + def setup + @base_property = Typesmith::BaseProperty.new("test_property") + @optional_property = Typesmith::BaseProperty.new("optional_property", optional: true) + end + + def test_initialization + assert_equal "test_property", @base_property.name + refute @base_property.optional + assert @optional_property.optional + end + + def test_to_typescript_raises_not_implemented_error + assert_raises(NotImplementedError) do + @base_property.to_typescript + end + end + + def test_process_value_returns_original_value + value = "test value" + assert_equal value, @base_property.process_value(value) + end + + def test_optional_suffix + assert_equal "", @base_property.send(:optional_suffix) + assert_equal "?", @optional_property.send(:optional_suffix) + end + + def test_camelized_name + assert_equal "testProperty", @base_property.send(:camelized_name) + assert_equal "optionalProperty", @optional_property.send(:camelized_name) + end + + def test_get_type_string + assert_equal "string", @base_property.send(:get_type_string, :string) + assert_equal "number", @base_property.send(:get_type_string, :number) + assert_equal "boolean", @base_property.send(:get_type_string, :boolean) + assert_equal "any", @base_property.send(:get_type_string, :any) + assert_equal "null", @base_property.send(:get_type_string, :null) + assert_equal "undefined", @base_property.send(:get_type_string, :undefined) + assert_equal "void", @base_property.send(:get_type_string, :void) + assert_equal "never", @base_property.send(:get_type_string, :never) + assert_equal "unknown", @base_property.send(:get_type_string, :unknown) + assert_equal "object", @base_property.send(:get_type_string, :object) + assert_equal "Date", @base_property.send(:get_type_string, :Date) + end + + def test_get_type_string_with_array + assert_equal "string[]", @base_property.send(:get_type_string, [:string]) + assert_equal "number[]", @base_property.send(:get_type_string, [:number]) + end + + def test_get_type_string_with_hash + assert_equal "{ [key: string]: number }", @base_property.send(:get_type_string, { string: :number }) + assert_equal "{ [key: number]: string }", @base_property.send(:get_type_string, { number: :string }) + end + + def test_get_type_string_with_custom_class + custom_class = Class.new(Typesmith::Definition) + custom_class.define_singleton_method(:typescript_type_name) { "CustomType" } + assert_equal "CustomType", @base_property.send(:get_type_string, custom_class) + end + + def test_validate_type + Typesmith::BaseProperty::PRIMITIVE_TYPES.each do |type| + assert_nil Typesmith::BaseProperty.validate_type(type) + end + + custom_class = Class.new(Typesmith::Definition) + assert_nil Typesmith::BaseProperty.validate_type(custom_class) + + assert_nil Typesmith::BaseProperty.validate_type([:string]) + assert_nil Typesmith::BaseProperty.validate_type({ string: :number }) + + assert_raises(Typesmith::BaseProperty::InvalidTypeError) do + Typesmith::BaseProperty.validate_type(:invalid_type) + end + end +end diff --git a/test/definition_test.rb b/test/definition_test.rb new file mode 100644 index 0000000..96c25c5 --- /dev/null +++ b/test/definition_test.rb @@ -0,0 +1,229 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "typesmith" + +class DefinitionTest < Minitest::Test + def setup + @base_property = Typesmith::BaseProperty.new("test_prop") + end + + def test_camelized_name + assert_equal "testProp", @base_property.send(:camelized_name) + end + + def test_optional_suffix + assert_equal "", @base_property.send(:optional_suffix) + optional_prop = Typesmith::BaseProperty.new("test_prop", optional: true) + assert_equal "?", optional_prop.send(:optional_suffix) + end + + def test_get_type_string + assert_equal "string", @base_property.send(:get_type_string, :string) + assert_equal "number[]", @base_property.send(:get_type_string, [:number]) + assert_equal "{ [key: string]: number }", @base_property.send(:get_type_string, { string: :number }) + end + + def test_validate_type + assert_nothing_raised { Typesmith::BaseProperty.validate_type(:string) } + assert_nothing_raised { Typesmith::BaseProperty.validate_type([:number]) } + assert_nothing_raised { Typesmith::BaseProperty.validate_type({ string: :boolean }) } + + assert_raises(Typesmith::BaseProperty::InvalidTypeError) { Typesmith::BaseProperty.validate_type(:float) } + end + + class TestSimple < Typesmith::Definition + property :id, type: :number + property :name, type: :string + property :is_active, type: :boolean + property :created_at, type: :Date + property :tags, type: [:string] + end + + class TestNested < Typesmith::Definition + property :user do + property :id, type: :number + property :name, type: :string + end + end + + class TestIndexed < Typesmith::Definition + property :scores, type: { string: :number } + end + + class TestComplex < Typesmith::Definition + property :id, type: :number + property :name, type: :string + property :optional_field, type: :string, optional: true + property :items, type: [TestSimple] + property :nested, type: TestNested + property :metadata, type: { string: :any } + end + + def test_simple_properties + typescript = TestSimple.to_typescript + expected = <<~TYPESCRIPT + export interface TestSimple { + id: number; + name: string; + isActive: boolean; + createdAt: Date; + tags: string[]; + } + TYPESCRIPT + assert_equal expected.strip, typescript + end + + def test_nested_properties + typescript = TestNested.to_typescript + expected = <<~TYPESCRIPT + export interface TestNested { + user: { + id: number; + name: string; + }; + } + TYPESCRIPT + assert_equal expected.strip, typescript + end + + def test_indexed_properties + typescript = TestIndexed.to_typescript + expected = <<~TYPESCRIPT + export interface TestIndexed { + scores: { [key: string]: number }; + } + TYPESCRIPT + assert_equal expected.strip, typescript + end + + def test_complex_properties + typescript = TestComplex.to_typescript + expected = <<~TYPESCRIPT + export interface TestComplex { + id: number; + name: string; + optionalField?: string; + items: TestSimple[]; + nested: TestNested; + metadata: { [key: string]: any }; + } + TYPESCRIPT + assert_equal expected.strip, typescript + end + + class TestComplexNesting < Typesmith::Definition + property :user do + property :id, type: :number + property :name, type: :string + property :address do + property :street, type: :string + property :city, type: :string + property :country do + property :code, type: :string + property :name, type: :string + end + end + end + end + + def test_complex_nesting + typescript = TestComplexNesting.to_typescript + expected = <<~TYPESCRIPT + export interface TestComplexNesting { + user: { + id: number; + name: string; + address: { + street: string; + city: string; + country: { + code: string; + name: string; + }; + }; + }; + } + TYPESCRIPT + assert_equal expected.strip, typescript + end + + def test_attribute_processing + instance = TestComplex.new( + id: 1, + name: "Test", + items: [{ id: 2, name: "Item", is_active: false, created_at: nil, tags: [] }], + nested: { user: { id: 3, name: "User" } }, + metadata: { key: "value" } + ) + + assert_equal 1, instance.id + assert_equal "Test", instance.name + assert_nil instance.optional_field + assert_equal [{ id: 2, name: "Item", is_active: false, created_at: nil, tags: [] }], instance.items + assert_equal({ user: { id: 3, name: "User" } }, instance.nested) + assert_equal({ key: "value" }, instance.metadata) + end + + def test_missing_required_attribute + error = assert_raises(ArgumentError) do + TestComplex.new(name: "Test") + end + assert_match(/Missing required attributes: id/, error.message) + end + + def test_undefined_attribute + error = assert_raises(Typesmith::Definition::UndefinedAttributeError) do + TestComplex.new(id: 1, name: "Test", undefined: "value") + end + assert_match(/Undefined attributes: undefined/, error.message) + end + + def test_to_json + instance = TestComplex.new( + id: 1, + name: "Test", + items: [{ id: 2, name: "Item", is_active: false, created_at: nil, tags: [] }], + nested: { user: { id: 3, name: "User" } }, + metadata: { "key" => "value" } + ) + + expected = { + id: 1, + name: "Test", + items: [{ id: 2, name: "Item", is_active: false, created_at: nil, tags: [] }], + nested: { user: { id: 3, name: "User" } }, + metadata: { "key" => "value" } + }.deep_transform_keys { |key| key.to_s.camelize(:lower) } + + assert_equal expected, instance.to_json + end + + class TestIndexedArrays < Typesmith::Definition + property :simple_array, type: { string: [:string] } + property :complex_array, type: { string: [TestSimple] } + property :non_array, type: { string: TestSimple } + end + + def test_indexed_properties_with_arrays + typescript = TestIndexedArrays.to_typescript + expected = <<~TYPESCRIPT + export interface TestIndexedArrays { + simpleArray: { [key: string]: string[] }; + complexArray: { [key: string]: TestSimple[] }; + nonArray: { [key: string]: TestSimple }; + } + TYPESCRIPT + assert_equal expected.strip, typescript + end + + private + + def assert_nothing_raised(&block) + block.call + rescue StandardError => e + flunk "Expected nothing to be raised, but #{e.class} was raised" + else + pass + end +end diff --git a/test/generator_test.rb b/test/generator_test.rb new file mode 100644 index 0000000..d6457ef --- /dev/null +++ b/test/generator_test.rb @@ -0,0 +1,118 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "fileutils" +require "typesmith" + +# Define test classes outside of test methods +class TestSimple < Typesmith::Definition + property :id, type: :number + property :name, type: :string +end + +class TestNested < Typesmith::Definition + property :user do + property :id, type: :number + property :name, type: :string + end +end + +class TestImport < Typesmith::Definition + property :simple, type: TestSimple + property :nested, type: TestNested +end + +class TestComplexNesting < Typesmith::Definition + property :user do + property :id, type: :number + property :address do + property :street, type: :string + property :city, type: :string + end + end +end + +class TestIndexed < Typesmith::Definition + property :scores, type: { string: :number } +end + +class TestArray < Typesmith::Definition + property :items, type: [TestSimple] +end + +class GeneratorTest < Minitest::Test + def setup + @generator = Typesmith::Generator.new + @test_output_dir = File.join("test", "tmp", "generated") + Typesmith::Generator.const_set(:BASE_OUTPUT_DIR, @test_output_dir) + FileUtils.rm_rf(@test_output_dir) + FileUtils.mkdir_p(@test_output_dir) + end + + def teardown + FileUtils.rm_rf(@test_output_dir) + end + + def test_generate_all + @generator.generate_all + + assert File.exist?(File.join(@test_output_dir, "test_simple.ts")) + assert File.exist?(File.join(@test_output_dir, "test_nested.ts")) + assert File.exist?(File.join(@test_output_dir, "index.ts")) + + simple_content = File.read(File.join(@test_output_dir, "test_simple.ts")) + assert_match(/export interface TestSimple/, simple_content) + assert_match(/id: number;/, simple_content) + assert_match(/name: string;/, simple_content) + + nested_content = File.read(File.join(@test_output_dir, "test_nested.ts")) + assert_match(/export interface TestNested/, nested_content) + assert_match(/user: {/, nested_content) + assert_match(/id: number;/, nested_content) + assert_match(/name: string;/, nested_content) + + index_content = File.read(File.join(@test_output_dir, "index.ts")) + assert_match(%r{export { TestSimple } from './test_simple';}, index_content) + assert_match(%r{export { TestNested } from './test_nested';}, index_content) + end + + def test_generate_imports + @generator.generate_all + + import_content = File.read(File.join(@test_output_dir, "test_import.ts")) + assert_match(%r{import { TestSimple } from './test_simple';}, import_content) + assert_match(%r{import { TestNested } from './test_nested';}, import_content) + assert_match(/export interface TestImport/, import_content) + assert_match(/simple: TestSimple;/, import_content) + assert_match(/nested: TestNested;/, import_content) + end + + def test_generate_complex_nesting + @generator.generate_all + + complex_content = File.read(File.join(@test_output_dir, "test_complex_nesting.ts")) + assert_match(/export interface TestComplexNesting/, complex_content) + assert_match(/user: {/, complex_content) + assert_match(/id: number;/, complex_content) + assert_match(/address: {/, complex_content) + assert_match(/street: string;/, complex_content) + assert_match(/city: string;/, complex_content) + end + + def test_generate_indexed_properties + @generator.generate_all + + indexed_content = File.read(File.join(@test_output_dir, "test_indexed.ts")) + assert_match(/export interface TestIndexed/, indexed_content) + assert_match(/scores: { \[key: string\]: number };/, indexed_content) + end + + def test_generate_array_properties + @generator.generate_all + + array_content = File.read(File.join(@test_output_dir, "test_array.ts")) + assert_match(%r{import { TestSimple } from './test_simple';}, array_content) + assert_match(/export interface TestArray/, array_content) + assert_match(/items: TestSimple\[\];/, array_content) + end +end diff --git a/test/indexed_property_test.rb b/test/indexed_property_test.rb new file mode 100644 index 0000000..07b6f6d --- /dev/null +++ b/test/indexed_property_test.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "typesmith" + +class IndexedPropertyTest < Minitest::Test + class CustomClass < Typesmith::Definition + property :id, type: :number + property :name, type: :string + end + + def setup + @simple_indexed = Typesmith::IndexedProperty.new("simple_scores", :string, :number) + @optional_indexed = Typesmith::IndexedProperty.new("optional_scores", :string, :number, optional: true) + @nested_indexed = Typesmith::IndexedProperty.new("nested_scores", :string, [:number]) + @complex_indexed = Typesmith::IndexedProperty.new("complex_scores", :string, CustomClass) + end + + def test_initialization + assert_equal "simple_scores", @simple_indexed.name + assert_equal :string, @simple_indexed.key_type + assert_equal :number, @simple_indexed.value_type + refute @simple_indexed.optional + assert @optional_indexed.optional + end + + def test_to_typescript + expected_simple = "simpleScores: { [key: string]: number };" + assert_equal expected_simple, @simple_indexed.to_typescript + + expected_optional = "optionalScores?: { [key: string]: number };" + assert_equal expected_optional, @optional_indexed.to_typescript + + expected_nested = "nestedScores: { [key: string]: number[] };" + assert_equal expected_nested, @nested_indexed.to_typescript + + expected_complex = "complexScores: { [key: string]: CustomClass };" + assert_equal expected_complex, @complex_indexed.to_typescript + end + + def test_process_value + input = { a: 1, b: 2 } + assert_equal input, @simple_indexed.process_value(input) + + nested_input = { a: [1, 2], b: [3, 4] } + assert_equal nested_input, @nested_indexed.process_value(nested_input) + + complex_input = { + a: { id: 1, name: "Item A" }, + b: { id: 2, name: "Item B" } + } + processed = @complex_indexed.process_value(complex_input) + assert_equal complex_input, processed + assert_instance_of Hash, processed[:a] + assert_instance_of Hash, processed[:b] + end + + def test_validate_type + assert_nil Typesmith::IndexedProperty.validate_type(:string) + assert_nil Typesmith::IndexedProperty.validate_type([:number]) + + custom_class = Class.new(Typesmith::Definition) + assert_nil Typesmith::IndexedProperty.validate_type(custom_class) + + assert_raises(Typesmith::BaseProperty::InvalidTypeError) do + Typesmith::IndexedProperty.new("invalid", :invalid, :number) + end + + assert_raises(Typesmith::BaseProperty::InvalidTypeError) do + Typesmith::IndexedProperty.new("invalid", :string, :invalid) + end + end +end diff --git a/test/nested_property_test.rb b/test/nested_property_test.rb new file mode 100644 index 0000000..36c0fad --- /dev/null +++ b/test/nested_property_test.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "typesmith" + +class NestedPropertyTest < Minitest::Test + class SimpleNested < Typesmith::Definition + property :id, type: :number + property :name, type: :string + end + + def setup + @simple_nested = Typesmith::NestedProperty.new("simple_nested", proc { + property :id, type: :number + property :name, type: :string + }) + + @optional_nested = Typesmith::NestedProperty.new("optional_nested", proc { + property :id, type: :number + property :name, type: :string + }, optional: true) + + @complex_nested = Typesmith::NestedProperty.new("complex_nested", proc { + property :id, type: :number + property :nested, type: SimpleNested + property :array_prop, type: [:string] + }) + end + + def test_initialization + assert_equal "simple_nested", @simple_nested.name + refute @simple_nested.optional + assert @optional_nested.optional + assert_instance_of Proc, @simple_nested.block + end + + def test_to_typescript + expected_simple = <<~TYPESCRIPT.chomp + simpleNested: { + id: number; + name: string; + }; + TYPESCRIPT + assert_equal expected_simple, @simple_nested.to_typescript + + expected_optional = <<~TYPESCRIPT.chomp + optionalNested?: { + id: number; + name: string; + }; + TYPESCRIPT + assert_equal expected_optional, @optional_nested.to_typescript + + expected_complex = <<~TYPESCRIPT.chomp + complexNested: { + id: number; + nested: SimpleNested; + arrayProp: string[]; + }; + TYPESCRIPT + assert_equal expected_complex, @complex_nested.to_typescript + end + + def test_process_value + simple_input = { id: 1, name: "Test" } + processed_simple = @simple_nested.process_value(simple_input) + assert_equal simple_input, processed_simple + + complex_input = { + id: 1, + nested: { id: 2, name: "Nested" }, + array_prop: %w[a b c] + } + processed_complex = @complex_nested.process_value(complex_input) + assert_equal complex_input, processed_complex + assert_instance_of Hash, processed_complex[:nested] + assert_instance_of Array, processed_complex[:array_prop] + end +end diff --git a/test/simple_property_test.rb b/test/simple_property_test.rb new file mode 100644 index 0000000..a67e7ba --- /dev/null +++ b/test/simple_property_test.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "typesmith" + +class SimplePropertyTest < Minitest::Test + class CustomType < Typesmith::Definition + property :id, type: :number + property :name, type: :string + end + + def setup + @string_prop = Typesmith::SimpleProperty.new("name", :string) + @number_prop = Typesmith::SimpleProperty.new("age", :number) + @boolean_prop = Typesmith::SimpleProperty.new("is_active", :boolean) + @optional_prop = Typesmith::SimpleProperty.new("email", :string, optional: true) + @custom_prop = Typesmith::SimpleProperty.new("custom", CustomType) + @array_prop = Typesmith::SimpleProperty.new("tags", [:string]) + end + + def test_initialization + assert_equal "name", @string_prop.name + assert_equal :string, @string_prop.type + refute @string_prop.optional + assert @optional_prop.optional + end + + def test_to_typescript + assert_equal "name: string;", @string_prop.to_typescript + assert_equal "age: number;", @number_prop.to_typescript + assert_equal "isActive: boolean;", @boolean_prop.to_typescript + assert_equal "email?: string;", @optional_prop.to_typescript + assert_equal "custom: CustomType;", @custom_prop.to_typescript + assert_equal "tags: string[];", @array_prop.to_typescript + end + + def test_process_value + assert_equal "John", @string_prop.process_value("John") + assert_equal 30, @number_prop.process_value(30) + assert_equal true, @boolean_prop.process_value(true) + assert_equal %w[tag1 tag2], @array_prop.process_value(%w[tag1 tag2]) + + custom_value = { id: 1, name: "Test" } + processed_custom = @custom_prop.process_value(custom_value) + assert_equal custom_value, processed_custom + assert_instance_of Hash, processed_custom + end + + def test_validate_type + assert_nil Typesmith::SimpleProperty.validate_type(:string) + assert_nil Typesmith::SimpleProperty.validate_type(:number) + assert_nil Typesmith::SimpleProperty.validate_type(:boolean) + assert_nil Typesmith::SimpleProperty.validate_type([:string]) + assert_nil Typesmith::SimpleProperty.validate_type(CustomType) + + assert_raises(Typesmith::BaseProperty::InvalidTypeError) do + Typesmith::SimpleProperty.new("invalid", :invalid_type) + end + end + + def test_camelized_name + assert_equal "name", @string_prop.send(:camelized_name) + assert_equal "age", @number_prop.send(:camelized_name) + assert_equal "isActive", @boolean_prop.send(:camelized_name) + end + + def test_get_type_string + assert_equal "string", @string_prop.send(:get_type_string, :string) + assert_equal "number", @number_prop.send(:get_type_string, :number) + assert_equal "boolean", @boolean_prop.send(:get_type_string, :boolean) + assert_equal "CustomType", @custom_prop.send(:get_type_string, CustomType) + assert_equal "string[]", @array_prop.send(:get_type_string, [:string]) + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..e2f4353 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) +require "typesmith" + +require "minitest/autorun" diff --git a/test/test_typesmith.rb b/test/test_typesmith.rb new file mode 100644 index 0000000..374ace2 --- /dev/null +++ b/test/test_typesmith.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +require "test_helper" + +class TestTypesmith < Minitest::Test + def test_that_it_has_a_version_number + refute_nil ::Typesmith::VERSION + end + + def test_it_does_something_useful + # assert false + end +end diff --git a/test/tmp/.keep b/test/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/typesmith.gemspec b/typesmith.gemspec new file mode 100644 index 0000000..18b5b8b --- /dev/null +++ b/typesmith.gemspec @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require_relative "lib/typesmith/version" + +Gem::Specification.new do |spec| + spec.name = "typesmith" + spec.version = Typesmith::VERSION + spec.authors = ["John Panos"] + spec.email = ["johncpanos@gmail.com"] + + spec.summary = "Write a short summary, because RubyGems requires one." + spec.description = "Write a longer description or delete this line." + spec.homepage = "https://johnpanos.com" + spec.license = "MIT" + spec.required_ruby_version = ">= 3.0.0" + + spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/johnpanos/typesmith" + spec.metadata["changelog_uri"] = "https://github.com/johnpanos/typesmith/blob/master/CHANGELOG.md" + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + gemspec = File.basename(__FILE__) + spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| + ls.readlines("\x0", chomp: true).reject do |f| + (f == gemspec) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] +end