Sha256: 799e981227b619f182cf20710226056481b5a417edfd94f2239a18ea975b854d
Contents?: true
Size: 1.77 KB
Versions: 5
Compression:
Stored size: 1.77 KB
Contents
require "rails/generators/scaffold/scaffold_generator" require "rails/generators/resource_helpers" # lib/generators/rails/typescript/typescript_generator.rb module ViteReact module Generators class ScaffoldGenerator < ScaffoldGenerator include Rails::Generators::ResourceHelpers source_root File.expand_path("templates", __dir__) argument :attributes, type: :array, default: [], banner: "field:type field:type" def create_or_update_types types_file_path = Rails.root.join("app/javascript/types.d.ts") interface_code = generate_interface_code if File.exist?(types_file_path) append_to_file types_file_path, interface_code else create_file types_file_path, interface_code end end private def generate_interface_code attributes_lines = attributes.flat_map do |attr| puts attr.inspect if attr.type == :references build_reference_lines(attr) else [ build_attribute_line(attr) ] end end <<~TS // AUTO-GENERATED by rails g scaffold #{file_name} interface #{class_name} { #{attributes_lines.join(" ")} } TS end def build_attribute_line(attr) "#{attr.name}?: #{rails_to_ts_type(attr.type)};" end def build_reference_lines(attr) referenced_interface_name = attr.name.camelize [ "#{attr.name}_id: number;", "#{attr.name}?: #{referenced_interface_name};" ] end def rails_to_ts_type(rails_type) case rails_type when "integer", "float", "decimal" then "number" when "boolean" then "boolean" else "string" end end end end end
Version data entries
5 entries across 5 versions & 1 rubygems