Class: HotwireClub::Toolbox::OptimisticForm::InstallGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/hotwire_club/toolbox/optimistic_form/install_generator.rb

Overview

Wires the optimistic-form Stimulus controller into the host app, adapting to its JavaScript setup (importmap, jsbundling/esbuild/bun, or vite), and ensures the Turbo morph refresh meta tags are present.

bin/rails generate hotwire_club:toolbox:optimistic_form:install

Constant Summary collapse

CONTROLLER_MODULE =
"hotwire_club/toolbox/optimistic_form_controller".freeze
CONTROLLERS_INDEX =
"app/javascript/controllers/index.js".freeze
LAYOUT =
"app/views/layouts/application.html.erb".freeze
MORPH_META =
<<~HTML
  <meta name="turbo-refresh-method" content="morph">
  <meta name="turbo-refresh-scroll" content="preserve">
HTML

Instance Method Summary collapse

Instance Method Details

#ensure_morph_meta_tagsObject



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/generators/hotwire_club/toolbox/optimistic_form/install_generator.rb', line 31

def ensure_morph_meta_tags
  unless File.exist?(layout_path)
    say "Could not find #{LAYOUT}; add the Turbo morph refresh meta tags to your layout <head>:", :yellow
    say MORPH_META
    return
  end

  if File.read(layout_path).include?("turbo-refresh-method")
    say_status :identical, "morph refresh meta tags", :blue
  else
    inject_into_file layout_path, indent(MORPH_META), after: /<head>\n/
  end
end


45
46
47
48
49
50
51
# File 'lib/generators/hotwire_club/toolbox/optimistic_form/install_generator.rb', line 45

def print_server_contract
  say ""
  say "Optimistic Form installed. Remember the server contract:", :green
  say "  • Success  -> head :no_content (204), or a targeted turbo_stream. Do not redirect."
  say "  • Failure  -> 4xx/422 so the client reconciles."
  say "See docs/optimistic-form.md for details."
end

#wire_javascriptObject



21
22
23
24
25
26
27
28
29
# File 'lib/generators/hotwire_club/toolbox/optimistic_form/install_generator.rb', line 21

def wire_javascript
  if importmap?
    register_for_importmap
  elsif bundler?
    register_for_bundler
  else
    say_unknown_js_setup
  end
end