class Enroute::Export

Attributes

config_path[R]
output_path[R]

Public Class Methods

call(output_path, config_path) click to toggle source
# File lib/enroute/export.rb, line 7
def self.call(output_path, config_path)
  new(output_path, config_path).call
end
new(output_path, config_path) click to toggle source
# File lib/enroute/export.rb, line 11
def initialize(output_path, config_path)
  @output_path = output_path
  @config_path = config_path
end

Public Instance Methods

build_ts_args_definition(route) click to toggle source
# File lib/enroute/export.rb, line 56
def build_ts_args_definition(route)
  route[:segments].map do |segment|
    type = route.dig(:typings, segment)&.chomp ||
           config.dig(:typings, :_default, segment)&.chomp ||
           "any"

    optional = route[:requiredSegments].include?(segment) ? "" : "?"
    "#{segment.camelize(:lower)}#{optional}: #{type}"
  end.join(", ")
end
build_ts_handler_function(route) click to toggle source
# File lib/enroute/export.rb, line 67
def build_ts_handler_function(route)
  args = JSON.pretty_generate(route.except(:typings))
  %[const #{route[:name]}Handler = buildRoute(#{args});]
end
build_ts_route_function(route) click to toggle source
# File lib/enroute/export.rb, line 72
def build_ts_route_function(route)
  args = build_ts_args_definition(route)
  segments = route[:segments].map {|segment| segment.camelize(:lower) }

  [
    %[export const #{route[:name]}Url = (#{args}): string =>],
    %[  #{route[:name]}Handler(#{segments.join(', ')});]
  ].join("\n")
end
call() click to toggle source
# File lib/enroute/export.rb, line 26
def call
  FileUtils.mkdir_p(File.dirname(output_path))

  write_template(output_path)
end
config() click to toggle source
# File lib/enroute/export.rb, line 16
def config
  @config ||= if File.file?(config_path)
                ActiveSupport::HashWithIndifferentAccess.new(
                  YAML.load_file(config_path)
                )
              else
                {}
              end
end
handler_functions() click to toggle source
# File lib/enroute/export.rb, line 48
def handler_functions
  routes.map {|route| build_ts_handler_function(route) }.join("\n\n")
end
render_template() click to toggle source
# File lib/enroute/export.rb, line 52
def render_template
  ERB.new(File.read("#{__dir__}/template.ts.erb")).result binding
end
route_functions() click to toggle source
# File lib/enroute/export.rb, line 42
def route_functions
  routes
    .map {|route| build_ts_route_function(route) }
    .join("\n\n")
end
routes() click to toggle source
# File lib/enroute/export.rb, line 32
def routes
  @routes ||= Routes.call(config)
end
write_template(output_path) click to toggle source
# File lib/enroute/export.rb, line 36
def write_template(output_path)
  File.open(output_path, "w+") do |file|
    file << render_template
  end
end