Sha256: 2f05584d22f1b0c519dc9633710a701f3c7439f8bd41e8acd7e4c52a3cae840f

Contents?: true

Size: 777 Bytes

Versions: 5

Compression:

Stored size: 777 Bytes

Contents

module JsRoutes
  # A Rack middleware that automatically updates routes file
  # whenever routes.rb is modified
  #
  # Inspired by
  # https://github.com/fnando/i18n-js/blob/main/lib/i18n/js/middleware.rb
  class Middleware
    def initialize(app)
      @app = app
      @routes_file = Rails.root.join("config/routes.rb")
      @mtime = nil
    end

    def call(env)
      update_js_routes
      @app.call(env)
    end

    protected

    def update_js_routes
      new_mtime = routes_mtime
      unless new_mtime == @mtime
        regenerate
        @mtime = new_mtime
      end
    end

    def regenerate
      JsRoutes.generate!
      JsRoutes.definitions!
    end

    def routes_mtime
      File.mtime(@routes_file)
    rescue Errno::ENOENT
      nil
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
js-routes-2.2.8 lib/js_routes/middleware.rb
js-routes-2.2.7 lib/js_routes/middleware.rb
js-routes-2.2.6 lib/js_routes/middleware.rb
js-routes-2.2.5 lib/js_routes/middleware.rb
js-routes-2.2.4 lib/js_routes/middleware.rb