Module: Ruflet::Rails::InstallSupport

Defined in:
lib/ruflet/rails/install_support.rb

Class Method Summary collapse

Class Method Details

.application_component_pathObject



104
105
106
# File 'lib/ruflet/rails/install_support.rb', line 104

def application_component_path
  File.join("app", "views", "ruflet", "components", "application_component.rb")
end

.application_component_templateObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
97
98
99
100
101
102
# File 'lib/ruflet/rails/install_support.rb', line 42

def application_component_template
  template = <<~RUBY
    # frozen_string_literal: true

    # ApplicationComponent is the base class for all Ruflet UI components in
    # this Rails app.  It explicitly includes Ruflet::UI::SharedControlForwarders
    # so that every subclass has the full ruflet widget DSL available as
    # instance methods (text, column, row, container, safe_area, filled_button,
    # icon, data_table, alert_dialog, and every other ruflet widget).
    # This is the same DSL that showcase uses — explicit, no Kernel magic.
    class ApplicationComponent
        include Ruflet::UI::SharedControlForwarders

        attr_reader :page

        def self.render(page, *args, **kwargs, &block)
          new(page).render(*args, **kwargs, &block)
        end

        def initialize(page)
          @page = page
        end

        private

        # Widget builder calls on this component delegate to Ruflet::DSL,
        # the same target used by the showcase App and by Kernel.
        # Override in a subclass to scope builds to a local WidgetBuilder.
        def control_delegate
          Ruflet::DSL
        end

        def platform
          page.client_details["platform"].to_s
        end

        def desktop?
          %w[macos windows linux].include?(platform)
        end

        def web?
          platform == "web"
        end

        def mobile?
          !desktop? && !web?
        end

        def screen_width
          page.client_details["width"].to_f
        end

        # Returns true when the client is narrower than 600 logical pixels
        # (phones and small tablets), enabling compact list layouts.
        def compact?
          screen_width > 0 && screen_width < 600
        end
    end
  RUBY
  template.gsub(/^    /, "  ")
end

.association_class_name_for(name, type) ⇒ Object



666
667
668
669
670
671
# File 'lib/ruflet/rails/install_support.rb', line 666

def association_class_name_for(name, type)
  return name.sub(/_id\z/, "").camelize if name.end_with?("_id")
  return name.camelize if %w[references belongs_to association].include?(type)

  nil
end

.attributes_from_model(model_class) ⇒ Object



633
634
635
636
637
638
639
# File 'lib/ruflet/rails/install_support.rb', line 633

def attributes_from_model(model_class)
  return [] unless model_class.respond_to?(:columns)

  model_class.columns.reject { |column|
    %w[id created_at updated_at].include?(column.name)
  }.map { |column| "#{column.name}:#{column.type}" }
end

.build_args_for_platform(platform, ruflet_url: nil) ⇒ Object

ruflet_rails builds only native clients. The web client is installed prebuilt (rake ruflet:web), never compiled, so “web” is not a build target here.



747
748
749
750
751
752
753
# File 'lib/ruflet/rails/install_support.rb', line 747

def build_args_for_platform(platform, ruflet_url: nil)
  normalized = normalize_build_platform(platform)
  return [] if normalized.to_s.empty?
  return [] if normalized == "web"

  [normalized]
end

.default_app_template(app_title:) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ruflet/rails/install_support.rb', line 12

def default_app_template(app_title:)
  <<~RUBY
    # frozen_string_literal: true

    # The home screen for this Ruflet app. You own this file — declare your
    # screens here; nothing is auto-discovered. It is mounted explicitly in
    # config/routes.rb (the install generator adds this line):
    #   match "/ws", to: Ruflet::Rails.app(Rails.root.join("app/views/ruflet/main.rb")), via: :all
    Ruflet.run do |page|
      page.title = #{app_title.inspect}
      page.add(
        safe_area(
          container(
            expand: true,
            padding: 24,
            content: column(
              spacing: 12,
              controls: [
                text(#{app_title.inspect}, size: 24, weight: "bold"),
                text("Edit app/views/ruflet/main.rb to build your app.")
              ]
            )
          ),
          expand: true
        )
      )
    end
  RUBY
end

.default_backend_urlObject



724
725
726
# File 'lib/ruflet/rails/install_support.rb', line 724

def default_backend_url
  "http://localhost:3000"
end

.default_entrypoint_pathObject



755
756
757
# File 'lib/ruflet/rails/install_support.rb', line 755

def default_entrypoint_path
  File.join("app", "views", "ruflet", "main.rb")
end

.default_ruflet_yaml(app_name:) ⇒ Object



673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/ruflet/rails/install_support.rb', line 673

def default_ruflet_yaml(app_name:)
  <<~YAML
    app:
      name: #{app_name}
      backend_url: #{default_backend_url}

    services: []

    assets:
      splash_screen: assets/splash.png
      icon_launcher: assets/icon.png
  YAML
end

.form_field_literal(field) ⇒ Object



641
642
643
644
645
646
647
648
# File 'lib/ruflet/rails/install_support.rb', line 641

def form_field_literal(field)
  parts = [
    "name: #{field[:name].inspect}",
    "type: #{field[:type].inspect}"
  ]
  parts << "class_name: #{field[:class_name].inspect}" if field[:class_name]
  "{ #{parts.join(', ')} }"
end

.form_view_path(model_name) ⇒ Object



121
122
123
124
125
# File 'lib/ruflet/rails/install_support.rb', line 121

def form_view_path(model_name)
  names = model_names(model_name)

  File.join("app", "views", "ruflet", "components", names[:plural], "#{names[:singular]}_form.rb")
end

.form_view_template(model_name:, attributes:) ⇒ Object



557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/ruflet/rails/install_support.rb', line 557

def form_view_template(model_name:, attributes:)
  names = model_names(model_name)
  attrs = normalized_form_attributes(attributes)
  fields_literal = attrs.map { |field| form_field_literal(field) }.join(", ")
  model_class = names[:class_name]
  singular_title = names[:singular].humanize.titleize

  <<~RUBY
    # frozen_string_literal: true

    require "ruflet_rails"

    class #{model_class}Form < ApplicationComponent
        include Ruflet::Rails::FormHelpers

        def render(record:, title: nil, on_save: nil, on_cancel: nil)
          title ||= record.persisted? ? "Edit #{singular_title}" : "New #{singular_title}"
          fields = ruflet_form_bindings(record, form_fields)

          column(
            expand: true,
            spacing: 12,
            children: [
              text(title, size: 24, weight: "bold"),
              column(spacing: 8, horizontal_alignment: "stretch", children: ruflet_form_controls(fields)),
              row(
                spacing: 8,
                children: [
                  outlined_button(
                    content: text("Cancel"),
                    on_click: ->(_e) { on_cancel ? on_cancel.call(page, record) : nil }
                  ),
                  filled_button(
                    content: text(record.persisted? ? "Update #{singular_title}" : "Create #{singular_title}"),
                    on_click: ->(_e) { save(record, fields, on_save: on_save) }
                  )
                ]
              )
            ]
          )
        end

        def save(record, fields, on_save: nil)
          if record.update(ruflet_form_attributes(fields, form_fields))
            on_save ? on_save.call(page, record) : record
          else
            show_errors(record)
            false
          end
        end

        def form_fields
          [#{fields_literal}]
        end

        def show_errors(record)
          show_snackbar(error_message(record))
        end

        def show_snackbar(message)
          page.snackbar = snackbar(text(message), open: true)
        end

        def error_message(record)
          messages = record.errors.full_messages
          messages.respond_to?(:to_sentence) ? messages.to_sentence : messages.join(", ")
        end
    end
  RUBY
end

.host_desktop_platformObject



728
729
730
731
732
733
734
735
# File 'lib/ruflet/rails/install_support.rb', line 728

def host_desktop_platform
  host_os = RbConfig::CONFIG["host_os"]
  return "macos" if host_os.match?(/darwin/i)
  return "linux" if host_os.match?(/linux/i)
  return "windows" if host_os.match?(/mswin|mingw|cygwin/i)

  nil
end

.install_next_steps(target:, entrypoint:, client:, mount_path: "/ws") ⇒ Object



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
# File 'lib/ruflet/rails/install_support.rb', line 768

def install_next_steps(target:, entrypoint:, client:, mount_path: "/ws")
  lines = [
    "Ruflet Rails installed.",
    "Generated entrypoint: #{entrypoint}",
    "Added WebSocket route #{mount_path} to config/routes.rb",
    "Next steps:",
    "  1. Start Rails: bin/rails server",
    "  2. Connect your Ruflet app to ws://localhost:3000#{mount_path}"
  ]

  if %w[desktop all].include?(client.to_s)
    lines += [
      "Desktop clients are server-driven and connect to this Rails app.",
      "Plain bin/dev, bin/rails server, and bin/rails s do not launch desktop.",
      "To launch desktop for a dev server run: bin/rails s --desktop or bin/dev --desktop",
      "To download the prebuilt desktop client: bin/rails ruflet:update[desktop]",
      "To build the host desktop client: bin/rails ruflet:build[desktop]"
    ]
  end

  if %w[web all].include?(client.to_s)
    lines += [
      "Web client installed into frontend/.",
      "Open the mounted Ruflet web app at http://localhost:3000/ruflet"
    ]
  end

  lines
end

.model_names(model_name) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/ruflet/rails/install_support.rb', line 108

def model_names(model_name)
  raw = model_name.to_s.strip
  class_name = raw.camelize
  singular = raw.underscore.singularize
  plural = singular.pluralize
  {
    class_name: class_name,
    singular: singular,
    plural: plural,
    title: plural.humanize.titleize
  }
end

.normalize_build_platform(platform) ⇒ Object



737
738
739
740
741
742
# File 'lib/ruflet/rails/install_support.rb', line 737

def normalize_build_platform(platform)
  value = platform.to_s.strip.downcase
  return host_desktop_platform if value == "desktop"

  value
end

.normalize_form_attribute(value) ⇒ Object



650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# File 'lib/ruflet/rails/install_support.rb', line 650

def normalize_form_attribute(value)
  raw = value.to_s.strip
  name, type = raw.split(":", 2)
  name = name.to_s.underscore.gsub(/[^a-z0-9_]/, "")
  type = type.to_s.strip
  type = "string" if type.empty?
  name = "#{name}_id" if %w[references belongs_to association].include?(type) && !name.end_with?("_id")
  association = association_class_name_for(name, type)
  {
    name: name,
    type: association ? "association" : type
  }.tap do |field|
    field[:class_name] = association if association
  end
end

.normalized_form_attributes(attributes) ⇒ Object



628
629
630
631
# File 'lib/ruflet/rails/install_support.rb', line 628

def normalized_form_attributes(attributes)
  attrs = Array(attributes).map { |field| normalize_form_attribute(field) }.reject { |field| field[:name].empty? }
  attrs.empty? ? [{ name: "name", type: "string" }] : attrs
end

.route_snippet(entrypoint: default_entrypoint_path, mount_path: "/ws", helper: "app") ⇒ Object

Kept for backward compatibility with apps that use manual mount.



760
761
762
# File 'lib/ruflet/rails/install_support.rb', line 760

def route_snippet(entrypoint: default_entrypoint_path, mount_path: "/ws", helper: "app")
  %(match "#{mount_path}", to: Ruflet::Rails.#{helper}(Rails.root.join("#{entrypoint}")), via: :all)
end

.ruby_desktop_flag_bootstrapObject



687
688
689
690
691
692
693
694
695
696
697
698
699
# File 'lib/ruflet/rails/install_support.rb', line 687

def ruby_desktop_flag_bootstrap
  <<~RUBY
    # ruflet_rails desktop flag
    ruflet_rails_desktop = ARGV.include?("--desktop")
    ruflet_rails_command = ARGV.find { |value| !value.to_s.start_with?("-") }
    if ruflet_rails_desktop && %w[server s].include?(ruflet_rails_command.to_s)
      ENV["RUFLET_RAILS_DESKTOP"] = "true"
      ENV["RUFLET_RAILS_DESKTOP_SERVER"] = "true"
    end
    ARGV.delete("--desktop")

  RUBY
end

.ruby_dev_desktop_flag_bootstrapObject



701
702
703
704
705
706
707
708
709
710
# File 'lib/ruflet/rails/install_support.rb', line 701

def ruby_dev_desktop_flag_bootstrap
  <<~RUBY
    # ruflet_rails desktop flag
    if ARGV.delete("--desktop")
      ENV["RUFLET_RAILS_DESKTOP"] = "true"
      ENV["RUFLET_RAILS_DESKTOP_SERVER"] = "true"
    end

  RUBY
end

.scaffold_attribute_pair(field) ⇒ Object



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/ruflet/rails/install_support.rb', line 529

def scaffold_attribute_pair(field)
  name = field[:name]
  type = field[:type].to_s
  control = scaffold_control_name(field)
  value =
    case type
    when "boolean"
      "!!#{control}.value"
    when "date"
      "#{control}.value.to_s.split(\"T\", 2).first"
    when "date_range", "daterange"
      "Range.new(Date.parse(#{control}.start_value.to_s), Date.parse(#{control}.end_value.to_s))"
    else
      "#{control}.value.to_s"
    end

  "#{name.inspect} => #{value}"
end

.scaffold_attributes_hash(attrs) ⇒ Object



420
421
422
# File 'lib/ruflet/rails/install_support.rb', line 420

def scaffold_attributes_hash(attrs)
  attrs.map { |field| scaffold_attribute_pair(field) }.join(",\n        ")
end

.scaffold_component_path(model_name) ⇒ Object



127
128
129
130
131
# File 'lib/ruflet/rails/install_support.rb', line 127

def scaffold_component_path(model_name)
  names = model_names(model_name)

  File.join("app", "views", "ruflet", "components", names[:plural], "#{names[:singular]}_component.rb")
end

.scaffold_component_template(model_name:, attributes: []) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
259
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
288
289
290
291
292
293
294
295
296
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/ruflet/rails/install_support.rb', line 148

def scaffold_component_template(model_name:, attributes: [])
  names = model_names(model_name)
  model_class = names[:class_name]
  component_class = "#{model_class}Component"
  attrs = normalized_form_attributes(attributes)
  control_locals = scaffold_control_locals(attrs)
  control_list = scaffold_control_list(attrs)
  attributes_hash = scaffold_attributes_hash(attrs)

  <<~RUBY
    # frozen_string_literal: true

    require "date"
    require "ruflet_rails"

    # The model (#{model_class}) is inferred from the class name and the route
    # ("/#{names[:plural]}") is declared in config/routes.rb. This file is YOURS:
    # the whole CRUD UI (index table, detail screen, create/edit form) and the
    # database calls (#{model_class}#update, #destroy!, .new) are explicit below
    # so you can change the UI or logic however you like. The base class only
    # provides reusable helpers: record loading, field inference, dialog
    # open/close, the date/time picker value helpers, and refresh.
    #
    # The same component renders on web and on mobile/desktop.
    class #{component_class} < Ruflet::Rails::ResourceComponent
      def render
        safe_area(
          container(
            expand: true,
            padding: { left: 24, top: 16, right: 24, bottom: 24 },
            content: column(
              expand: true,
              spacing: 16,
              children: [
                index_header,
                compact? ? record_list(records) : record_table(records)
              ]
            )
          ),
          expand: true
        )
      end

      def show(record)
        safe_area(
          container(
            expand: true,
            padding: { left: 24, top: 16, right: 24, bottom: 24 },
            content: column(
              expand: true,
              spacing: 16,
              children: [
                show_header(record),
                column(
                  spacing: 8,
                  children: resource_fields.map { |field| field_row(field.humanize, display_value(record, field)) }
                )
              ]
            )
          ),
          expand: true
        )
      end

      private

      def show_header(record)
        row(
          alignment: "spaceBetween",
          vertical_alignment: "center",
          children: [
            container(expand: true, content: text("\#{singular_title} ##\#{record_id(record)}", size: 24, weight: "bold")),
            row(
              tight: true,
              spacing: 8,
              children: [
                outlined_button(content: text("Back"), on_click: ->(_event) { render_index }),
                filled_button(content: text("Edit"), on_click: ->(_event) { open_form(record) })
              ]
            )
          ]
        )
      end

      def index_header
        row(
          alignment: "spaceBetween",
          vertical_alignment: "center",
          children: [
            container(expand: true, content: text(resource_title, size: 24, weight: "bold")),
            filled_button(content: text("New \#{singular_title}"), on_click: ->(_event) { open_form(model_class.new) })
          ]
        )
      end

      def record_table(items)
        row(
          scroll: "auto",
          children: [
            data_table(
              table_columns,
              rows: items.map { |record| table_row(record) },
              column_spacing: 24,
              horizontal_margin: 12,
              show_bottom_border: true
            )
          ]
        )
      end

      def table_columns
        display_fields.map { |field| data_column(field.humanize) } + [
          data_column("Actions"),
          data_column(""),
          data_column("")
        ]
      end

      def table_row(record)
        data_row(
          display_fields.map { |field| data_cell(display_value(record, field), on_tap: ->(_event) { open_show(record) }) } +
            [
              data_cell(icon("visibility", tooltip: "Show"), on_tap: ->(_event) { open_show(record) }),
              data_cell(icon("edit", tooltip: "Edit"), on_tap: ->(_event) { open_form(record) }),
              data_cell(icon("delete", tooltip: "Delete"), on_tap: ->(_event) { open_delete(record) })
            ]
        )
      end

      def record_list(items)
        column(spacing: 4, children: items.map { |record| record_tile(record) })
      end

      def record_tile(record)
        list_tile(
          title: text(primary_label(record)),
          subtitle: secondary_label(record) ? text(secondary_label(record)) : nil,
          trailing: row(
            tight: true,
            spacing: 0,
            children: [
              icon_button("edit", tooltip: "Edit", on_click: ->(_event) { open_form(record) }),
              icon_button("delete", tooltip: "Delete", on_click: ->(_event) { open_delete(record) })
            ]
          ),
          on_click: ->(_event) { open_show(record) }
        )
      end

      def open_show(record)
        show_record(record)
      end

      def open_form(record)
        #{control_locals}

        attributes = lambda do
          {
            #{attributes_hash}
          }
        end

        dialog  = nil
        dialog  = alert_dialog(
          open: false,
          modal: true,
          scrollable: true,
          title: text(record.persisted? ? "Edit \#{singular_title}" : "New \#{singular_title}"),
          content: container(
            width: dialog_width,
            content: column(
              spacing: 8,
              horizontal_alignment: "stretch",
              children: [
                #{control_list}
              ]
            )
          ),
          actions: [
            text_button(content: text("Cancel"), on_click: ->(_event) { close_dialog(dialog) }),
            filled_button(content: text("Save"), on_click: ->(_event) {
              # Persist with the model (this is your code — change it freely).
              if record.update(attributes.call)
                close_dialog(dialog)
                refresh
                show_snackbar("\#{singular_title} saved")
              else
                show_errors(record)
              end
            })
          ],
          actions_alignment: "end"
        )
        open_dialog(dialog)
      end

      def open_delete(record)
        dialog = nil
        dialog = alert_dialog(
          open: false,
          modal: true,
          title: text("Delete \#{singular_title}?"),
          content: text("Permanently remove \#{singular_title} #\#{record_id(record)}?", no_wrap: false),
          actions: [
            text_button(content: text("Cancel"), on_click: ->(_event) { close_dialog(dialog) }),
            filled_button(content: text("Delete"), on_click: ->(_event) {
              # Destroy with the model (this is your code — change it freely).
              record.destroy!
              close_dialog(dialog)
              refresh
              show_snackbar("\#{singular_title} deleted")
            })
          ],
          actions_alignment: "end"
        )
        open_dialog(dialog)
      end

      def field_row(label, value)
        row(
          children: [
            container(width: 140, content: text(label, weight: "bold")),
            container(expand: true, content: text(value, no_wrap: false))
          ]
        )
      end
    end
  RUBY
end

.scaffold_control_list(attrs) ⇒ Object



416
417
418
# File 'lib/ruflet/rails/install_support.rb', line 416

def scaffold_control_list(attrs)
  attrs.map { |field| scaffold_control_view_name(field) }.join(",\n            ")
end

.scaffold_control_local(field) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/ruflet/rails/install_support.rb', line 424

def scaffold_control_local(field)
  name = field[:name]
  type = field[:type].to_s
  control = scaffold_control_name(field)
  label = name.humanize
  value = "record.public_send(#{name.inspect})"

  case type
  when "boolean"
    "#{control} = checkbox(label: #{label.inspect}, value: !!#{value})"
  when "date", "datetime", "timestamp"
    display_control = "#{control}_display"
    picker_value_helper = type == "date" ? "date_picker_value" : "datetime_picker_value"
    <<~RUBY.chomp
      #{control}_value = #{picker_value_helper}(#{value})
          #{display_control} = text(date_display_value(#{control}_value))
          #{control} = date_picker(
            value: #{control}_value,
            help_text: #{label.inspect},
            on_change: ->(_event) do
              close_dialogs(#{control})
              page.update(#{display_control}, value: date_display_value(#{control}.value))
            end
          )
          #{control}_field = column(
            spacing: 6,
            children: [
              text(#{label.inspect}),
              row(
                spacing: 8,
                children: [
                  container(expand: true, content: #{display_control}),
                  outlined_button(content: text("Choose #{label}"), on_click: ->(_event) { open_dialog(#{control}) })
                ]
              )
            ]
          )
    RUBY
  when "time"
    display_control = "#{control}_display"
    <<~RUBY.chomp
      #{control}_value = time_picker_value(#{value})
          #{display_control} = text(time_display_value(#{control}_value))
          #{control} = time_picker(
            value: #{control}_value,
            help_text: #{label.inspect},
            on_change: ->(_event) do
              close_dialogs(#{control})
              page.update(#{display_control}, value: time_display_value(#{control}.value))
            end
          )
          #{control}_field = column(
            spacing: 6,
            children: [
              text(#{label.inspect}),
              row(
                spacing: 8,
                children: [
                  container(expand: true, content: #{display_control}),
                  outlined_button(content: text("Choose #{label}"), on_click: ->(_event) { open_dialog(#{control}) })
                ]
              )
            ]
          )
    RUBY
  when "date_range", "daterange"
    display_control = "#{control}_display"
    <<~RUBY.chomp
      #{control}_start_value, #{control}_end_value = date_range_picker_values(#{value})
          #{display_control} = text(date_range_display_value(#{control}_start_value, #{control}_end_value))
          #{control} = date_range_picker(
            start_value: #{control}_start_value,
            end_value: #{control}_end_value,
            help_text: #{label.inspect},
            on_change: ->(_event) do
              close_dialogs(#{control})
              page.update(
                #{display_control},
                value: date_range_display_value(#{control}.start_value, #{control}.end_value)
              )
            end
          )
          #{control}_field = column(
            spacing: 6,
            children: [
              text(#{label.inspect}),
              row(
                spacing: 8,
                children: [
                  container(expand: true, content: #{display_control}),
                  outlined_button(content: text("Choose #{label}"), on_click: ->(_event) { open_dialog(#{control}) })
                ]
              )
            ]
          )
    RUBY
  when "text"
    "#{control} = text_field(value: #{value}.to_s, label: #{label.inspect}, multiline: true, min_lines: 3)"
  when "integer", "float", "decimal"
    "#{control} = text_field(value: #{value}.to_s, label: #{label.inspect}, keyboard_type: \"number\")"
  else
    "#{control} = text_field(value: #{value}.to_s, label: #{label.inspect})"
  end
end

.scaffold_control_locals(attrs) ⇒ Object



378
379
380
# File 'lib/ruflet/rails/install_support.rb', line 378

def scaffold_control_locals(attrs)
  attrs.map { |field| scaffold_control_local(field) }.join("\n    ")
end

.scaffold_control_name(field) ⇒ Object



548
549
550
# File 'lib/ruflet/rails/install_support.rb', line 548

def scaffold_control_name(field)
  "#{field[:name].gsub(/[^a-zA-Z0-9_]/, '_')}_control"
end

.scaffold_control_view_name(field) ⇒ Object



552
553
554
555
# File 'lib/ruflet/rails/install_support.rb', line 552

def scaffold_control_view_name(field)
  control = scaffold_control_name(field)
  %w[date datetime timestamp time date_range daterange].include?(field[:type].to_s) ? "#{control}_field" : control
end

.scaffold_display_fields(attrs) ⇒ Object



386
387
388
389
390
# File 'lib/ruflet/rails/install_support.rb', line 386

def scaffold_display_fields(attrs)
  fields = attrs.reject { |field| field[:type].to_s == "text" }
  fields = attrs if fields.empty?
  fields.first(3).map { |field| field[:name] }.inspect
end

.scaffold_display_value_body(display_value_cases, indent) ⇒ Object

A ‘case` with no `when` clause is a syntax error, so models without date/time attributes get the plain fallback body instead.



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/ruflet/rails/install_support.rb', line 135

def scaffold_display_value_body(display_value_cases, indent)
  return "#{indent}record.public_send(field).to_s" if display_value_cases.to_s.strip.empty?

  reindented_cases = display_value_cases.gsub(/^    /, indent)
  <<~RUBY.chomp.gsub(/^/, indent).gsub(/^#{Regexp.escape(indent)}__CASES__$/, reindented_cases)
    case field
    __CASES__
    else
      record.public_send(field).to_s
    end
  RUBY
end

.scaffold_display_value_cases(attrs) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/ruflet/rails/install_support.rb', line 392

def scaffold_display_value_cases(attrs)
  attrs.filter_map do |field|
    next unless %w[date datetime timestamp time date_range daterange].include?(field[:type].to_s)

    name = field[:name]
    formatter =
      case field[:type].to_s
      when "time"
        "value.respond_to?(:strftime) ? value.strftime(\"%H:%M\") : value.to_s"
      when "date_range", "daterange"
        "value.respond_to?(:begin) && value.respond_to?(:end) ? \"\#{value.begin} - \#{value.end}\" : value.to_s"
      when "date"
        "value.respond_to?(:to_date) ? value.to_date.iso8601 : value.to_s"
      else
        "value.respond_to?(:iso8601) ? value.iso8601 : value.to_s"
      end
    [
      "    when #{name.inspect}",
      "      value = record.public_send(#{name.inspect})",
      "      #{formatter}"
    ].join("\n")
  end.join("\n")
end

.scaffold_resource_fields(attrs) ⇒ Object



382
383
384
# File 'lib/ruflet/rails/install_support.rb', line 382

def scaffold_resource_fields(attrs)
  attrs.map { |field| field[:name] }.inspect
end

.shell_desktop_flag_bootstrapObject



712
713
714
715
716
717
718
719
720
721
722
# File 'lib/ruflet/rails/install_support.rb', line 712

def shell_desktop_flag_bootstrap
  <<~SH
    # ruflet_rails desktop flag
    if [ "$1" = "--desktop" ]; then
      export RUFLET_RAILS_DESKTOP=true
      export RUFLET_RAILS_DESKTOP_SERVER=true
      shift
    fi

  SH
end

.web_route_snippet(entrypoint: default_entrypoint_path, mount_path: "/ruflet") ⇒ Object



764
765
766
# File 'lib/ruflet/rails/install_support.rb', line 764

def web_route_snippet(entrypoint: default_entrypoint_path, mount_path: "/ruflet")
  %(mount Ruflet::Rails.web_app(app_file: Rails.root.join("#{entrypoint}")), at: "#{mount_path}")
end