Module: Ruflet::Rails::InstallSupport

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

Class Method Summary collapse

Class Method Details

.application_component_pathObject



89
90
91
# File 'lib/ruflet/rails/install_support.rb', line 89

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

.application_component_templateObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
# File 'lib/ruflet/rails/install_support.rb', line 27

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



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

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



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

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) ⇒ Object



830
831
832
833
834
835
# File 'lib/ruflet/rails/install_support.rb', line 830

def build_args_for_platform(platform)
  normalized = normalize_build_platform(platform)
  return [] if normalized.to_s.empty?

  [normalized]
end

.default_app_template(app_title:) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ruflet/rails/install_support.rb', line 12

def default_app_template(app_title:)
  template = <<~RUBY
    require "ruflet"
    require "ruflet_rails"

    Ruflet::Rails.load_views(__dir__)

    Ruflet.run do |page|
      page.title = #{app_title.inspect}
      Ruflet::Rails.render(page)
    end
  RUBY
  template.gsub(/^    /, "  ")
end

.default_backend_urlObject



810
811
812
# File 'lib/ruflet/rails/install_support.rb', line 810

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

.default_entrypoint_pathObject



837
838
839
# File 'lib/ruflet/rails/install_support.rb', line 837

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

.default_mobile_app_template(app_title:) ⇒ Object



93
94
95
# File 'lib/ruflet/rails/install_support.rb', line 93

def default_mobile_app_template(app_title:)
  default_app_template(app_title: app_title)
end

.default_ruflet_yaml(app_name:) ⇒ Object



743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/ruflet/rails/install_support.rb', line 743

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

.desktop_initializer_pathObject



757
758
759
# File 'lib/ruflet/rails/install_support.rb', line 757

def desktop_initializer_path
  File.join("config", "initializers", "ruflet_desktop.rb")
end

.desktop_initializer_templateObject



761
762
763
764
765
766
767
768
769
770
771
# File 'lib/ruflet/rails/install_support.rb', line 761

def desktop_initializer_template
  <<~RUBY
    # frozen_string_literal: true

    # Set this to true when you intentionally want the Rails server process to
    # launch the server-driven Ruflet desktop client.
    Rails.application.configure do
      config.x.ruflet_rails.desktop = false
    end
  RUBY
end

.form_field_literal(field) ⇒ Object



711
712
713
714
715
716
717
718
# File 'lib/ruflet/rails/install_support.rb', line 711

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



110
111
112
113
114
# File 'lib/ruflet/rails/install_support.rb', line 110

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



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'lib/ruflet/rails/install_support.rb', line 627

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, 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



814
815
816
817
818
819
820
821
# File 'lib/ruflet/rails/install_support.rb', line 814

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



845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# File 'lib/ruflet/rails/install_support.rb', line 845

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

  if client.to_s == "desktop"
    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

  lines
end

.model_names(model_name) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/ruflet/rails/install_support.rb', line 97

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



823
824
825
826
827
828
# File 'lib/ruflet/rails/install_support.rb', line 823

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



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/ruflet/rails/install_support.rb', line 720

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



698
699
700
701
# File 'lib/ruflet/rails/install_support.rb', line 698

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



841
842
843
# File 'lib/ruflet/rails/install_support.rb', line 841

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



773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'lib/ruflet/rails/install_support.rb', line 773

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



787
788
789
790
791
792
793
794
795
796
# File 'lib/ruflet/rails/install_support.rb', line 787

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



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/ruflet/rails/install_support.rb', line 599

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

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

.scaffold_attributes_hash(attrs) ⇒ Object



490
491
492
# File 'lib/ruflet/rails/install_support.rb', line 490

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

.scaffold_component_path(model_name) ⇒ Object



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

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



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
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/ruflet/rails/install_support.rb', line 241

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"

    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,
              children: [
                #{control_list}
              ]
            )
          ),
          actions: [
            text_button(content: text("Cancel"), on_click: ->(_event) { close_dialog(dialog) }),
            filled_button(content: text("Save"), on_click: ->(_event) {
              save_record(record, attributes.call, dialog)
            })
          ],
          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_record(record, dialog) })
          ],
          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



486
487
488
# File 'lib/ruflet/rails/install_support.rb', line 486

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

.scaffold_control_local(field) ⇒ Object



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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
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
# File 'lib/ruflet/rails/install_support.rb', line 494

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}.props["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}.props["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}.props["start_value"], #{control}.props["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



448
449
450
# File 'lib/ruflet/rails/install_support.rb', line 448

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

.scaffold_control_name(field) ⇒ Object



618
619
620
# File 'lib/ruflet/rails/install_support.rb', line 618

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

.scaffold_control_view_name(field) ⇒ Object



622
623
624
625
# File 'lib/ruflet/rails/install_support.rb', line 622

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



456
457
458
459
460
# File 'lib/ruflet/rails/install_support.rb', line 456

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_cases(attrs) ⇒ Object



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/ruflet/rails/install_support.rb', line 462

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



452
453
454
# File 'lib/ruflet/rails/install_support.rb', line 452

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

.scaffold_view_path(model_name) ⇒ Object



116
117
118
119
120
# File 'lib/ruflet/rails/install_support.rb', line 116

def scaffold_view_path(model_name)
  names = model_names(model_name)

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

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



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
# File 'lib/ruflet/rails/install_support.rb', line 128

def scaffold_view_template(model_name:, attributes: [])
  names = model_names(model_name)
  model_class = names[:class_name]
  view_class = "#{model_class}View"
  component_class = "#{model_class}Component"
  title = names[:title]
  attrs = normalized_form_attributes(attributes)
  resource_fields = scaffold_resource_fields(attrs)
  display_fields = scaffold_display_fields(attrs)
  display_value_cases = scaffold_display_value_cases(attrs)

  template = <<~RUBY
    # frozen_string_literal: true

    require "ruflet_rails"
    require_relative "components/#{names[:plural]}/#{names[:singular]}_component"

    class #{view_class} < Ruflet::Rails::ResourceView
      route #{("/" + names[:plural]).inspect}

      def render
        page.title = resource_title
        render_index
      end

      private

      def model_class
        #{model_class}
      end

      def resource_title
        #{title.inspect}
      end

      def singular_title
        model_class.model_name.human.titleize
      end

      def records
        scope = model_class.respond_to?(:limit) ? model_class.limit(50) : model_class.all
        scope.respond_to?(:limit) ? scope.limit(50) : scope.to_a.first(50)
      end

      def render_index
        page.views = []
        page.add(component.render)
      end

      def render_show(record)
        page.views = []
        page.add(component.show(record))
        page.update
      end

      def component
        @component ||= #{component_class}.new(page, controller: self)
      end

      def show_record(record)
        render_show(record)
      end

      def save_record(record, attributes, dialog)
        if record.update(attributes)
          close_dialog(dialog)
          render_index
          show_snackbar("\#{singular_title} saved")
        else
          show_errors(record)
        end
      end

      def destroy_record(record, dialog)
        record.destroy!
        close_dialog(dialog)
        render_index
        show_snackbar("\#{singular_title} deleted")
      rescue StandardError => e
        show_snackbar(e.message)
      end

      def resource_fields
        #{resource_fields}
      end

      def display_fields
        #{display_fields}
      end

      def display_value(record, field)
        case field
        __DISPLAY_VALUE_CASES__
        else
          record.public_send(field).to_s
        end
      end

      def primary_label(record)
        field = display_fields.first
        field ? display_value(record, field) : "##\#{record_id(record)}"
      end

      def secondary_label(record)
        field = display_fields[1]
        field ? display_value(record, field) : nil
      end

    end
  RUBY
  template.gsub(/^[ \t]*__DISPLAY_VALUE_CASES__$/, display_value_cases)
end

.shell_desktop_flag_bootstrapObject



798
799
800
801
802
803
804
805
806
807
808
# File 'lib/ruflet/rails/install_support.rb', line 798

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