Class: JsRoutes::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/js_routes/instance.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Instance

Implementation



12
13
14
# File 'lib/js_routes/instance.rb', line 12

def initialize(options = {})
  @configuration = JsRoutes.configuration.merge(options)
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



7
8
9
# File 'lib/js_routes/instance.rb', line 7

def configuration
  @configuration
end

Instance Method Details

#generateObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/js_routes/instance.rb', line 16

def generate
  # Ensure routes are loaded. If they're not, load them.
  if named_routes.empty? && application.respond_to?(:reload_routes!)
    application.reload_routes!
  end
  content = File.read(@configuration.source_file)

  if !@configuration.dts?
    content = js_variables.inject(content) do |js, (key, value)|
      js.gsub!("RubyVariables.#{key}", value.to_s) ||
      raise("Missing key #{key} in JS template")
    end
  end
  content + routes_export + prevent_types_export
end

#generate!Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/js_routes/instance.rb', line 32

def generate!
  # Some libraries like Devise did not load their routes yet
  # so we will wait until initialization process finishes
  # https://github.com/railsware/js-routes/issues/7
  Rails.configuration.after_initialize do
    file_path = Rails.root.join(@configuration.output_file)
    source_code = generate

    # We don't need to rewrite file if it already exist and have same content.
    # It helps asset pipeline or webpack understand that file wasn't changed.
    next if File.exist?(file_path) && File.read(file_path) == source_code

    File.open(file_path, 'w') do |f|
      f.write source_code
    end
  end
end