Module: SvelteOnRails::Installer::Utils

Defined in:
lib/svelte_on_rails/installer/utils.rb

Class Method Summary collapse

Class Method Details

.add_line_to_file(file_path, line) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/svelte_on_rails/installer/utils.rb', line 45

def self.add_line_to_file(file_path, line)
  file_content = File.exist?(file_path) ? File.read(file_path) : ""

  if file_content.match?(/#{line}/)
    puts "#{line} already present in #{file_path}, nothing changed here."
    return
  end

  File.open(file_path, 'a') do |file|
    file.puts(line)
  end
  puts "added #{line} to #{file_path}."
rescue StandardError => e
  puts "Error: #{e.message}"
end

.add_route(route, app_root: nil) ⇒ Object



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/svelte_on_rails/installer/utils.rb', line 297

def self.add_route(route, app_root: nil)

  file_path = app_root_path(app_root).join('config/routes.rb')

  # Read the file content
  content = File.read(file_path)

  # Split content into lines
  lines = content.lines

  # Find the index of Rails.application.routes.draw do
  ind = -1
  lines.each_with_index do |line, i|
    if line.match?(/^\s*Rails.application.routes.draw\s*do[\s\S]+$/)
      ind = i
    end
  end

  # Insert

  if ind >= 0
    lines.insert(ind + 1, route)
  else
    raise "ERROR: Could not find Rails.application.routes.draw do"
  end

  # Write the modified content back to the file
  begin
    File.write(file_path, lines.map { |l| l.gsub(/\n/, '') }.join("\n"))
    puts "Successfully inserted «root '#{route}'» into '#{file_path}'"
  rescue => e
    raise "Error writing to #{file_path} => «#{e.message}»"
  end

end

.app_root_path(app_root = nil) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/svelte_on_rails/installer/utils.rb', line 406

def self.app_root_path(app_root = nil)
  if app_root
    raise "ERROR: app_root must be class Pathname" unless app_root.is_a?(Pathname)
    app_root
  else
    begin
      Dir.exist?(Rails.root.join('app'))
      Rails.root
    rescue => e
      raise "ERROR: Could not find Rails.root => #{e}"
    end
  end
end

.ask_yn(question) ⇒ Object



289
290
291
292
293
294
295
# File 'lib/svelte_on_rails/installer/utils.rb', line 289

def self.ask_yn(question)
  begin
    puts "#{question} (y/n)"
    continue = STDIN.gets.chomp.downcase[0]
  end until ['y', 'n'].include?(continue)
  continue == 'y'
end

.check_file_exists(file_path) ⇒ Object



160
161
162
163
164
# File 'lib/svelte_on_rails/installer/utils.rb', line 160

def self.check_file_exists(file_path)
  unless File.exist?(file_path)
    raise "ERROR: File not found: #{file_path}"
  end
end

.check_file_not_exists(file_path) ⇒ Object



172
173
174
175
176
# File 'lib/svelte_on_rails/installer/utils.rb', line 172

def self.check_file_not_exists(file_path)
  if File.exist?(file_path)
    raise "ERROR: File already exists: #{file_path}"
  end
end

.check_folder_exists(folder_path) ⇒ Object



166
167
168
169
170
# File 'lib/svelte_on_rails/installer/utils.rb', line 166

def self.check_folder_exists(folder_path)
  unless File.exist?(folder_path)
    raise "ERROR: Folder not found: #{folder_path}"
  end
end

.check_folder_not_exists(folder_path) ⇒ Object



178
179
180
181
182
# File 'lib/svelte_on_rails/installer/utils.rb', line 178

def self.check_folder_not_exists(folder_path)
  if File.exist?(folder_path)
    raise "ERROR: Folder already exists: #{folder_path}"
  end
end

.create_file(file_path) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/svelte_on_rails/installer/utils.rb', line 61

def self.create_file(file_path)

  unless File.exist?(file_path)
    FileUtils.touch(file_path)
    puts "Created empty file at file://#{file_path}"
  end
end

.create_folder(folder) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/svelte_on_rails/installer/utils.rb', line 36

def self.create_folder(folder)
  if Dir.exist?(folder)
    puts "Folder already exists: #{folder}"
  else
    FileUtils.mkdir_p(folder)
    puts "Created folder: #{folder}"
  end
end

.create_javascript_initializerObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/svelte_on_rails/installer/utils.rb', line 69

def self.create_javascript_initializer
  config_path = Rails.root.join("app", "frontend", "initializers", "svelte.js")
  if File.exist?(config_path)
    puts "Initializer already exists: file://#{config_path}"
  else
    File.write(config_path, <<~JAVASCRIPT)

      import { initializeSvelteComponents, cleanupSvelteComponents } from '@csedl/svelte-on-rails';

      const components = import.meta.glob('/javascript/components/**/*.svelte', { eager: true });
      const componentsRoot = '/javascript/components';

      // Initialize Svelte components
      initializeSvelteComponents(componentsRoot, components, true);

      // Turbo event listener for page load
      document.addEventListener('turbo:load', () => {
          initializeSvelteComponents(componentsRoot, components, true);
      });

      // Turbo event listener for cleanup before page cache
      document.addEventListener('turbo:before-cache', () => {
          cleanupSvelteComponents(false);
      });
    JAVASCRIPT
    puts "Created initializer file at file://#{config_path}"
  end
end

.create_svelte_hello_worldObject



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/svelte_on_rails/installer/utils.rb', line 98

def self.create_svelte_hello_world
  file_path = Rails.root.join("app", "frontend", "javascript", "components", "HelloWorld.svelte")
  if File.exist?(file_path)
    puts "Hello World file already exists: file://#{file_path}"
  else
    File.write(file_path, <<~HTML)
      <script>
          export let items
          let count = 0;

          function increment() {
              count += 1;
          }
      </script>

      <h1>Greetings from svelte</h1>

      <button on:click={increment}>Increment: {count}</button>
      <ul>
          {#each items as item}
              <li>{item}</li>
          {/each}
      </ul>

      <style>
          button {
              background-color: darkred;
              color: white;
              padding: 10px;
              border: none;
          }
      </style>
    HTML
    puts "Hello World file at file://#{file_path}"
  end
end

.install_npm_packageObject



6
7
8
9
10
11
12
13
14
# File 'lib/svelte_on_rails/installer/utils.rb', line 6

def self.install_npm_package
  package_name = "@csedl/svelte-on-rails@latest"

  if system("npm install #{package_name}")
    puts "Installed successfully: «#{package_name}»"
  else
    abort "Failed to install «#{package_name}» by npm. You must manually."
  end
end

.install_turboObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/svelte_on_rails/installer/utils.rb', line 16

def self.install_turbo

  pkg_js = Rails.root.join("package.json")
  package_name = "@hotwired/turbo-rails"
  file_content = File.exist?(pkg_js) ? File.read(pkg_js) : ""

  if file_content.match?(/#{package_name}/)
    puts "#{package_name} is already present in package.json, assuming that it is set up well and working."
  else
    puts "Installing #{package_name} via npm..."
    if system("npm install #{package_name}")
      puts "#{package_name} successfully installed."
      add_line_to_file(Rails.root.join("app", "frontend", "entrypoints", "application.js"), "import '#{package_name}';")
    else
      abort "Failed to install #{package_name}. Please ensure npm is installed and try running 'npm install #{package_name}' manually."
    end
  end

end

.remove_files(file_paths) ⇒ Object



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/svelte_on_rails/installer/utils.rb', line 354

def self.remove_files(file_paths)
  file_paths.each do |f|
    if File.exist?(f)
      if File.directory?(f)
        Dir.delete(f)
        puts "  • Removed directory: #{f}"
      else
        File.delete(f)
        puts "  • Removed file: #{f}"
      end
    else
      puts "  • File/Path not found so not removed: #{f}"
    end
  end
end

.remove_line_from_file(file_path, string_to_find, force: false) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/svelte_on_rails/installer/utils.rb', line 370

def self.remove_line_from_file(file_path, string_to_find, force: false)

  # Read the file content
  content = File.read(file_path)

  # Split content into lines
  lines = content.lines

  found_lines = []
  modified_content = []
  lines.each do |line|
    if line.match(/^[\s\S]+#{string_to_find}[\s\S]+$/)
      found_lines.push(line)
    else
      modified_content.push(line)
    end
  end

  utils = SvelteOnRails::Installer::Utils

  if found_lines.present?
    return if !force && utils.ask_yn("Remove lines\n  • #{found_lines.join("\n  • ")}\n from #{file_path}?")

    # Write the modified content back to the file
    begin
      File.write(file_path, modified_content.map { |l| l.gsub(/\n/, '') }.join("\n"))
      puts "Successfully removed #{found_lines.length} #{'line'.pluralize(found_lines.length)}."
    rescue => e
      raise "Error writing to #{file_path} => «#{e.message}»"
    end
  else

  end

end

.route_exists?(target_route) ⇒ Boolean

Returns:

  • (Boolean)


333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/svelte_on_rails/installer/utils.rb', line 333

def self.route_exists?(target_route)

  # check if exists
  # Ensure the Rails environment is loaded
  # require File.expand_path("../config/environment", __dir__)

  # Get all routes from the Rails application
  routes = Rails.application.routes.routes

  # Check if the route exists
  routes.any? do |route|
    # Extract the path spec and remove any optional parts or constraints
    path = route.path.spec.to_s
    # Clean up the path to match the format (remove leading/trailing slashes, etc.)
    cleaned_path = path.gsub(/\(.*\)/, "").gsub(/^\/|\/$/, "")
    # Check if the cleaned path matches the target route
    cleaned_path == target_route
  end

end

.run_command(command, success_message: false) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/svelte_on_rails/installer/utils.rb', line 135

def self.run_command(command, success_message: false)

  Dir.chdir(Rails.root) do
    Bundler.with_unbundled_env do
      `pwd`
      stdout, stderr, status = Open3.capture3(command)
      err_msg = if stderr.present?
                  stderr.strip
                elsif success_message && !stdout.match(/#{success_message}/)
                  "missing string «#{success_message}» on result:\n\n+++#{stdout}\n+++"
                else
                end

      if err_msg
        puts "Error running command «#{command}»:"
        raise err_msg
      else
        puts "#{command} => Success"
      end

    end
  end

end

.template_paths(templates, app_root: nil) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/svelte_on_rails/installer/utils.rb', line 260

def self.template_paths(templates, app_root: nil)
  paths = []
  app_root = app_root_path(app_root)
  ssr_server_configured = SvelteOnRails::SsrServer.instance.configured?

  templates.each do |t|
    templates_folder = File.expand_path("../../../templates", __dir__)
    template_root = templates_folder + '/' + t
    raise "ERROR: Template «#{t}» not found:\n«#{template_root}»" unless File.directory?(template_root)

    files = Dir.glob(template_root + '/**/*').select { |e| File.file? e }
    files.each do |f|

      unless ssr_server_configured
        next if File.basename(f) == File.basename(SvelteOnRails::SsrServer.script_path_full)
      end

      paths.push(
        [
          f,
          f.gsub(template_root + '/', ''),
          app_root.join(f.gsub(template_root + '/', ''))
        ]
      )
    end
  end
  paths
end

.write_templates(templates, ask_for_overwrite: true, app_root: nil, silent: false, only: [], dry_run: false, placeholders: [], vite_dir: nil) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/svelte_on_rails/installer/utils.rb', line 184

def self.write_templates(templates, ask_for_overwrite: true, app_root: nil, silent: false, only: [], dry_run: false, placeholders: [], vite_dir: nil)

  paths = template_paths(templates, app_root: app_root)

  if only.any?
    paths = paths.select do |path|
      only.any? { |pattern| path.include?(pattern) }
    end
  end

  existing = paths.dup.select { |p| File.exist?(p[2]) }
  to_create = paths.dup.reject { |p| File.exist?(p[2]) }
  continue = nil

  if existing.present? && dry_run
    begin
      puts
      if existing.present?
        puts "Already existing #{'File'.pluralize(existing.length)}:\n • #{existing.map { |p| p[1] }.join("\n • ")}.\n => If you continue, you will be asked to overwrite for each of them.\n\n"
      end
      if to_create.present?
        puts "Files to be created: #{'File'.pluralize(to_create.length)}:\n • #{to_create.map { |p| p[1] }.join("\n • ")}.\n\n"
      end
      puts "Continue? (y/n)"
      continue = STDIN.gets.chomp.downcase[0]
    end until ['y', 'n'].include?(continue)
    if continue == 'n'
      puts " Skipping write #{'template'.pluralize(templates.length)}."
      return
    end
  end

  if dry_run
    return continue != 'n'
  else
    paths.each do |p|

      v = (File.exist?(p[2]) ? 'replaced' : 'created')

      write = true
      if ask_for_overwrite && File.exist?(p[2])
        begin
          puts "Overwrite #{p[1].to_s}? (y/n)"
          overwrite = STDIN.gets.chomp.downcase[0]
        end until ['y', 'n'].include?(overwrite)
        if overwrite == 'n'
          write = false
        end
      end

      if write
        frontend_root = Rails.root.join('app', 'frontend').to_s
        dest_path = if p[2].to_s.start_with?(frontend_root)
                      p[2].to_s.sub(frontend_root, Rails.root.join(vite_dir).to_s)
                    else
                      p[2]
                    end

        FileUtils.mkdir_p(File.dirname(dest_path))
        cont = File.read(p.first)
        placeholders.each do |k, v|
          cont = cont.gsub(k, v)
        end
        File.write(dest_path, cont)
        puts "#{v}: #{p[1]}"
        puts
      else
        puts " • skipped: #{p[1]}"
        puts
      end

    end
  end

end