Module: JsFromRoutes

Defined in:
lib/js_from_routes/version.rb,
lib/js_from_routes/generator.rb

Overview

Public: Automatically generates JS for Rails routes with { export: true }. Generates one file per controller, and one function per route.

Defined Under Namespace

Classes: Configuration, ControllerRoutes, Instance, Railtie, Route, Template, TemplateConfig

Constant Summary collapse

VERSION =

Public: This library adheres to semantic versioning.

"4.1.0"

Class Method Summary collapse

Class Method Details

.config(name = nil) ⇒ Object

Public: Configuration of the code generator.

Without a name, returns/yields the default global configuration:

JsFromRoutes.config do |config|
config.file_suffix = "Api.ts"
end

With a name, defines a named generator instance with its own configuration, allowing separate route generation for different sub-apps:

JsFromRoutes.config(:admin) do |config|
config.output_folder = Rails.root.join("app/javascript/admin/api")
config.export_if = ->(route) { route.defaults[:export] == :admin }
end


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/js_from_routes/generator.rb', line 252

def config(name = nil)
  if name
    root = ::Rails.root || Pathname.new(Dir.pwd)
    new_config = Configuration.new(root)
    yield(new_config) if block_given?
    instances[name] = Instance.new(name, new_config)
  else
    @config ||= Configuration.new(::Rails.root || Pathname.new(Dir.pwd))
    if block_given?
      @config_customized = true
      yield(@config)
    end
    @config
  end
end

.generate!(app_or_routes = Rails.application) ⇒ Object

Public: Generates code for the specified routes with { export: true }.

Runs every named instance, plus the default global config whenever it was explicitly configured (or when no named instances exist at all). This keeps mixed usage working: adding a named instance never silently disables the global config that an existing app already relies on.



279
280
281
282
283
# File 'lib/js_from_routes/generator.rb', line 279

def generate!(app_or_routes = Rails.application)
  runnable = instances.values
  runnable.unshift(Instance.new(:default, config)) if @config_customized || runnable.empty?
  runnable.each { |inst| inst.generate!(app_or_routes) }
end

.instancesObject

Public: Returns all registered named instances.



269
270
271
# File 'lib/js_from_routes/generator.rb', line 269

def instances
  @instances ||= {}
end