Class: HotGlue::ScaffoldGenerator

Inherits:
Erb::Generators::ScaffoldGenerator
  • Object
show all
Includes:
DefaultConfigLoader, GeneratorHelpers
Defined in:
lib/generators/hot_glue/scaffold_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from GeneratorHelpers

#parent_resource_name

Methods included from DefaultConfigLoader

#default_configs, #get_default_from_config

Constructor Details

#initialize(*meta_args) ⇒ ScaffoldGenerator

Returns a new instance of ScaffoldGenerator.



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
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
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
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
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
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 149

def initialize(*meta_args)
  super

  begin
    @the_object = eval(class_name)
  rescue StandardError => e
    message = "*** Oops: It looks like there is no object for #{class_name}. Please define the object + database table first."
    puts message
    raise(HotGlue::Error, message)
  end

  @meta_args = meta_args

  if options['specs_only'] && options['no_specs']
    raise(HotGlue::Error, "*** Oops: You seem to have specified both the --specs-only flag and --no-specs flags. this doesn't make any sense, so I am aborting. Aborting.")
  end

  if !options['exclude'].empty? && !options['include'].empty?
    exit_message = "*** Oops: You seem to have specified both --include and --exclude. Please use one or the other. Aborting."
    puts exit_message

    raise(HotGlue::Error, exit_message)
  end

  if @stimulus_syntax.nil?
    @stimulus_syntax = true
  end


  if Gem::Specification.find_all_by_name('pagy').any?
    if Gem::Specification.find_all_by_name('pagy').first.version.to_s.split(".").first.to_i <= 9
      @pagination_style = 'pagy9'
    else
      # warn "Pagy version 43 not yet compatible"
      @pagination_style = 'pagy43'
    end
  elsif Gem::Specification.find_all_by_name('will_paginate').any?
    @pagination_style = 'will_paginate'
  elsif Gem::Specification.find_all_by_name('kaminari').any?
    @pagination_style = 'kaminari'
  end

  if !options['markup'].nil?
    message = "Using --markup flag in the generator is deprecated; instead, use a file at config/hot_glue.yml with a key markup set to `erb` or `haml`"
    raise(HotGlue::Error, message)
  end

  @markup = get_default_from_config(key: :markup)
  @sample_file_path = get_default_from_config(key: :sample_file_path)
  @bootstrap_column_width ||= options['bootstrap_column_width'] ||
    get_default_from_config(key: :bootstrap_column_width) || 2


  @controller_prefix = options['controller_prefix']
  @default_boolean_display = get_default_from_config(key: :default_boolean_display)
  if options['layout']
    layout = options['layout']
  else
    layout = get_default_from_config(key: :layout)

    if !['hotglue', 'bootstrap', 'tailwind'].include? layout
      raise "Invalid option #{layout} in Hot glue config (config/hot_glue.yml). You must either use --layout= when generating or have a file config/hotglue.yml; specify layout as either 'hotglue' or 'bootstrap'"
    end
  end

  @button_icons = get_default_from_config(key: :button_icons) || 'none'

  @layout_strategy =
    case layout
    when 'bootstrap'
      LayoutStrategy::Bootstrap.new(self)
    when 'tailwind'
      LayoutStrategy::Tailwind.new(self)
    when 'hotglue'
      LayoutStrategy::HotGlue.new(self)
    end

  args = meta_args[0]


  @singular =   args.first.tableize.singularize # should be in form hello_world

  if @singular.include?("/")
    @singular = @singular.split("/").last
  end

  @plural = (options['plural'] || args.first.tableize.singularize.pluralize)
  if @plural.include?("/")
    @plural = @plural.split("/").last
  end
  # respects what you set in inflections.rb, to override, use plural option
  puts "SINGULAR: #{@singular}"
  puts "PLURAL: #{@plural}"

  @namespace = options['namespace'] || nil
  @namespace_value = @namespace
  use_controller_name =  plural.titleize.gsub(" ", "")


  @controller_build_name =  ((@namespace.titleize.gsub(" ", "") + "::" if @namespace) || "") + (@controller_prefix ? @controller_prefix.titleize : "") + use_controller_name + "Controller"
  @controller_build_folder = (@controller_prefix ? @controller_prefix.downcase + "_" : "") + use_controller_name.underscore
  @controller_build_folder_singular = singular

  @auth = options['auth'] || "current_user"

  @god = options['god'] || options['gd'] || false
  @auth_identifier = options['auth_identifier'] || (!@god && @auth.gsub("current_", "")) || nil

  if options['nest']
    raise HotGlue::Error, "STOP: the flag --nest has been replaced with --nested; please re-run using the --nested flag"
  end
  @nested = (!options['nested'].empty? && options['nested']) || nil
  @singular_class = args.first # note this is the full class name with a model namespace

  setup_attachments

  # polymorphic parents
  # input = options["polymorphic_parent"]
  # "parent_id[company|vc_firm|press_outlet],thing_id[apple|banana]"

  if @nested && @nested.split("/").last.include?("(")
    @polymorphic_parents = [@nested.split("/").last[/\(([^)]+)\)/, 1] + "_id"]
  
  else
    @polymorphic_parents = []
    # do we need to be able to set these via a config?
    # the use case I've implemented only supports a polymorphic parent in
    # how you build the nest structure (last nested parent)
    # what if there are two or more fields which are polymorphic on the object 
  end

  puts "polymhic_parents: #{@polymorphic_parents}"

  @exclude_fields = []
  @exclude_fields += options['exclude'].split(",").collect(&:to_sym)

  if !options['include'].empty?
    @include_fields = []

    # semicolon to denote layout columns; commas separate fields
    #
    @include_fields += options['include'].split(":").collect { |column_list|
      column_list.split(",").collect do |field|
        if field.include?("(")
          field =~ /(.*)\((.*)\)/
          field_short = $1
        else
          field_short = field
        end
        if field_short.starts_with?("**")
          nil
        else
          field_short.gsub("-", "").gsub("=", "")
        end
      end
    }.flatten.compact.collect(&:to_sym)
    @include_fields += @polymorphic_parents.collect{ |x|
      [x.to_sym, x.to_s.gsub("_id","_type").to_sym]
  }.flatten
    puts "INCLUDED FIELDS: #{@include_fields}"
  end


  @show_only = options['show_only'].split(",").collect(&:to_sym)
  if @show_only.any?
    puts "show only field #{@show_only}}"
  end

  @hidden_all = options['hidden'].split(",").collect(&:to_sym)
  @hidden_create = options['hidden_create'].split(",").collect(&:to_sym)
  @hidden_update = options['hidden_update'].split(",").collect(&:to_sym)
  @hidden_update.concat(@hidden_all) if @hidden_all.any?
  @hidden_create.concat(@hidden_all) if @hidden_all.any?
  @hidden_create.uniq!
  @hidden_update.uniq!

  if @hidden_create.any? || @hidden_update.any? || @hidden_all.any?
    puts "hidden update fields #{@hidden_update}}"
    puts "hidden create fields #{@hidden_create}}"
  end


  @invisible_all = options['invisible'].split(",").collect(&:to_sym)
  @invisible_create = options['invisible_create'].split(",").collect(&:to_sym)
  @invisible_update = options['invisible_update'].split(",").collect(&:to_sym)
  @invisible_update.concat(@invisible_all) if @invisible_all.any?
  @invisible_update.uniq!
  @invisible_create.concat(@invisible_all) if @invisible_all.any?
  @invisible_create.uniq!


  @modify_as = {}
  if !options['modify'].empty?
    modify_input = options['modify'].split(",")
    modify_input.each do |setting|
      if setting.include?("[")
        setting =~ /(.*){(.*)}\[(.*)\]/
        key, lookup_as = $1, $2, $3
      else
        setting =~ /(.*){(.*)}/
        key, lookup_as = $1, $2
      end

      if ["$"].include?($2)
        @modify_as[key.to_sym] =  {cast: $2, badges: $3}
      elsif $2.include?("|")
        binary = $2.split("|")
        @modify_as[key.to_sym] =  {binary: {truthy: binary[0],
                                            falsy: binary[1]},
                                            badges: $3}
      elsif $2 == "partial"
        @modify_as[key.to_sym] =  {enum: :partials, badges: $3 }
      elsif $2 == "tinymce"
        @modify_as[key.to_sym] =  {tinymce: 1, badges: $3}
      elsif $2 == "typeahead"
        if !$3.nil?
          nested = $3.split("/")
        else
          nested = []
        end
        @modify_as[key.to_sym] =  {typeahead: 1, nested: nested}
      elsif $2 == "timezone"
        @modify_as[key.to_sym] =  {timezone: 1, badges: $3}
      elsif $2 == "include_blank"
        @modify_as[key.to_sym] =  {include_blank: true}
      elsif $2 == "urlwrap"
        helper_method = $3
        @modify_as[key.to_sym] = { urlwrap: true,
                                   helper_method: helper_method }
      elsif $2 == "none"
        @modify_as[key.to_sym] =  {none: 1, badges: $3}
      else
        raise "unknown modification direction #{$2}"
      end
    end
  end

  @display_as = {}
  if !options['display_as'].empty?
    display_input = options['display_as'].split(",")

    display_input.each do |setting|
      setting =~ /(.*){(.*)}/
      key, lookup_as = $1, $2
      @display_as[key.to_sym] =  {boolean: $2}
    end
  end


  @update_show_only = []
  if !options['update_show_only'].empty?
    @update_show_only += options['update_show_only'].split(",").collect(&:to_sym)
  end

  # syntax should be xyz_id{xyz_email},abc_id{abc_email}
  # instead of a drop-down for the foreign entity, a text field will be presented
  # You must ALSO use a factory that contains a parameter of the same name as the 'value' (for example, `xyz_email`)

  @label = options['label'] || (eval("#{class_name}.class_variable_defined?(:@@table_label_singular)") ? eval("#{class_name}.class_variable_get(:@@table_label_singular)") : singular.gsub("_", " ").titleize)
  @list_label_heading = options['list_label_heading'] || (eval("#{class_name}.class_variable_defined?(:@@table_label_plural)") ? eval("#{class_name}.class_variable_get(:@@table_label_plural)") : plural.gsub("_", " ").upcase)

  @new_button_label = options['new_button_label'] || (eval("#{class_name}.class_variable_defined?(:@@table_label_singular)") ? "New " + eval("#{class_name}.class_variable_get(:@@table_label_singular)") : "New " + singular.gsub("_", " ").titleize)
  @new_form_heading = options['new_form_heading'] || "New #{@label}"

  # @table_display_name_singular = (eval("#{class_name}.class_variable_defined?(:@@table_label_singular)") ? eval("#{class_name}.class_variable_get(:@@table_label_singular)") : singular.gsub("_", " ").titleize)
  @table_display_name_plural = (eval("#{class_name}.class_variable_defined?(:@@table_label_plural)") ? eval("#{class_name}.class_variable_get(:@@table_label_plural)") : plural.gsub("_", " ").titleize)

  setup_hawk_keys
  @form_placeholder_labels = options['form_placeholder_labels'] # true or false
  @inline_list_labels = options['inline_list_labels'] || get_default_from_config(key: :inline_list_labels) || 'omit' # 'before','after','omit'

  @form_labels_position = options['form_labels_position']
  if @form_labels_position.nil?
    @form_labels_position = get_default_from_config(key: :form_labels_position)
    if @form_labels_position.nil?
      @form_labels_position = 'after'
    end
  else
    if !['before', 'after', 'omit'].include?(@form_labels_position)
      raise HotGlue::Error, "You passed '#{@form_labels_position}' as the setting for --form-labels-position but the only allowed options are before, after (default), and omit"
    end
  end


  if !['before', 'after', 'omit'].include?(@inline_list_labels)
    raise HotGlue::Error, "You passed '#{@inline_list_labels}' as the setting for --inline-list-labels but the only allowed options are before, after, and omit (default)"
  end

  @specs_only = options['specs_only'] || false

  @no_specs = options['no_specs'] || false
  @no_delete = options['no_delete'] || false

  @no_create = options['no_create'] || false
  @no_paginate = options['no_paginate'] || false
  @paginate_per_page_selector = options['paginate_per_page_selector']

  @big_edit = options['big_edit']

  @no_edit = options['no_edit'] || false
  @no_list = options['no_list'] || false

  @no_controller = options['no_controller'] || false
  @no_list = options['no_list'] || false
  @no_list_label = options['no_list_label'] || false
  @no_list_heading = options['no_list_heading'] || false
  @stacked_downnesting = options['stacked_downnesting']

  @display_list_after_update = options['display_list_after_update'] || false
  @display_edit_after_create = options['display_edit_after_create'] || false
  @new_in_modal = options['new_in_modal'] || false

  @smart_layout = options['smart_layout']
  @record_scope = options['record_scope']
  @downnest_shows_headings = options['downnest_shows_headings']
  @new_button_position = options['new_button_position']


  @pundit = options['pundit']
  @pundit_policy_override = options['pundit_policy_override']

  @no_nav_menu = options['no_nav_menu']

  @phantom_create_params = options['phantom_create_params'] || ""
  @phantom_update_params = options['phantom_update_params'] || ""


  if get_default_from_config(key: :pundit_default)
    raise "please note the config setting `pundit_default` has been renamed `pundit`. please update your hot_glue.yml file"
  end

  if @pundit.nil?
    @pundit = get_default_from_config(key: :pundit)
  end


  if (@invisible_create + @invisible_update).any? && !@pundit
    raise "you specified invisible fields without using Pundit. please remove the invisible fields or use --pundit"
  end

  if options['include'].include?(":") && @smart_layout
    raise HotGlue::Error, "You specified both --smart-layout and also specified grouping mode (there is a : character in your field include list); you must remove the colon(s) from your --include tag or remove the --smart-layout option"
  end

  @container_name = @layout_strategy.container_name
  @downnest = options['downnest'] || false

  @downnest_children = [] # TODO: defactor @downnest_children in favor of downnest_object
  @downnest_object = {}

  if @downnest
    @downnest_children = @downnest.split(",")

    @downnest_children.each do |child|
      if child.include?("(")
        child =~ /(.*)\((.*)\)/
        child_name, polymorph_as = $1, $2
      else
        child_name = child
      end
      extra_size = child_name.count("+")

      child_name.gsub!("+","")

      @downnest_object[child_name] = {
        name: child_name,
        extra_size: extra_size,
        polymorph_as: polymorph_as,
      }
    end
  end




  @include_object_names = options['include_object_names'] || get_default_from_config(key: :include_object_names)


  @back_link_to_parent = options['back_link_to_parent'] || false

  if @god
    # @auth = nil
  end
  # when in self auth, the object is the same as the authenticated object

  if @auth && auth_identifier == @singular
    @self_auth = true
  end

  if @self_auth && !@no_create
    raise "This controller appears to be the same as the authentication object but in this context you cannot build a new/create action; please re-run with --no-create flag"
  end

  @magic_buttons = []
  if options['magic_buttons']
    @magic_buttons = options['magic_buttons'].split(',')
  end

  @small_buttons = options['small_buttons'] || false

  @build_update_action = !@no_edit || !@magic_buttons.empty?
  # if the magic buttons are present, build the update action anyway

  @ujs_syntax = options['ujs_syntax']
  if !@ujs_syntax
    @ujs_syntax = !defined?(Turbo::Engine)
  end

  # NEST CHAIN
  # new syntax
  # @nested_set = [
  # {
  #    singular: ...,
  #    plural: ...,
  #    optional: false
  # }]
  @nested_set = []

  if !@nested.nil?
    @nested_set = @nested.split("/").collect { |arg|
      if arg.include?("[") && arg.include?("(")
        arg =~ /(.*)\((.*)\)\[(.*)\]/
        singular, polymorph_as, parent_name = $1, $2, $3

      elsif arg.include?("(")
        arg =~ /(.*)\((.*)\)/
        singular, polymorph_as = $1, $2
        parent_name = singular
      elsif arg.include?("[")
        arg =~ /(.*)\[(.*)\]/
        singular, parent_name = $1, $2
      else
        singular = arg
        parent_name = singular
      end

      {
        singular: singular,
        plural: singular.pluralize,
        polymorph_as: polymorph_as,
        parent_name: parent_name
      }
    }
    puts "NESTING: #{@nested_set}"
  end

  if @nested_set.any?
    @lazy = true
  end

  # related_sets
  related_set_input = options['related_sets'].split(",")
  @related_sets = {}
  related_set_input.each do |setting|

    if setting.include?("{") && setting.include?("[")
      setting =~ /(.*){(.*)}\[(.*)\]/
      key, label, hawk = $1, $2 , $3
    elsif setting.include?("{") && !setting.include?("[")
      setting =~ /(.*){(.*)}/
      key, label = $1, $2 , $3
    elsif setting.include?("[") && !setting.include?("{")
      setting =~ /(.*)\[(.*)\]/
      key, hawk = $1, $2
    else

      key = setting
      label = "label"
    end

    association_ids_method = eval("#{singular_class}.reflect_on_association(:#{key.to_sym})").class_name.underscore + "_ids"
    class_name = eval("#{singular_class}.reflect_on_association(:#{key.to_sym})").class_name

    @related_sets[key.to_sym] =   { name: key.to_sym,
                        association_ids_method: association_ids_method,
                        class_name: class_name,
                        label_field: label,
                        hawk: hawk }
  end

  if @related_sets.any?
    puts "RELATED SETS: #{@related_sets}"

  end

  # OBJECT OWNERSHIP & NESTING
  @reference_name = HotGlue.derrive_reference_name(singular_class)


  if @auth && @self_auth
    @object_owner_sym = @auth.gsub("current_", "").to_sym
    @object_owner_eval = @auth
    @object_owner_optional = false
    @object_owner_name = @auth.gsub("current_", "").to_s

  elsif @auth && !@self_auth && @nested_set.none? && !@auth.include?(".")
    @object_owner_sym = @auth.gsub("current_", "").to_sym
    @object_owner_eval = @auth
    @object_owner_optional = false
    @object_owner_name = @auth.gsub("current_", "").to_s

  elsif @auth && @auth.include?(".")
    @object_owner_sym = nil
    @object_owner_eval = @auth
  else
    if @nested_set.any?

      @object_owner_sym = (@nested_set.last[:polymorph_as] || @nested_set.last[:singular]).to_sym

      @object_owner_eval = "#{( @nested_set.last[:singular])}"
      @object_owner_name = (@nested_set.last[:polymorph_as] || @nested_set.last[:singular])
    else
      @object_owner_sym = nil
      @object_owner_eval = ""
    end
  end

  unless options['factory_creation'].nil?
    @factory_creation = options['factory_creation'].gsub(";", "\n")
  end

  identify_object_owner
  setup_fields


  if (@columns - @show_only - (@ownership_field ? [@ownership_field.to_sym] : [])).empty?
    @no_field_form = true
  end

  @code_before_create = options['code_before_create']
  @code_after_create = options['code_after_create']
  @code_before_update = options['code_before_update']
  @code_after_update = options['code_after_update']
  @code_after_new = options['code_after_new']
  @code_in_controller = options['code_in_controller'] || ""

  buttons_width = ((!@no_edit && 1) || 0) + ((!@no_delete && 1) || 0) + (@magic_buttons.any? ? 1 : 0)


  # alt_lookups_entry =


  @alt_lookups = {}

  options['alt_foreign_key_lookup'].split(",").each do |setting|
    setting =~ /(.*){(.*)}/
    key, lookup_as = $1, $2



    if !eval("#{class_name}.reflect_on_association(:#{key.to_s.gsub("_id","")})")
      raise "couldn't find association for #{key} in the object #{class_name}"
    end
    assoc = eval("#{class_name}.reflect_on_association(:#{key.to_s.gsub("_id","")}).class_name")

    data = {lookup_as: lookup_as.gsub("+",""),
            assoc: assoc,
            with_create: lookup_as.include?("+")}
    @alt_lookups[key] = data
  end



  # @update_alt_lookups = @alt_lookups.collect{|key, value|
  #   @update_show_only.include?(key) ?
  #     {  key: value }
  #     : nil}.compact

  @stimmify = options['stimmify']
  if @stimmify === "stimmify"
    @stimmify = @singular.gsub("_", "-") + "-form"
    @stimify_camel = @stimmify.camelize
  end

  # build a new polymorphic object
  @associations = []
  @columns_map = {}

  @columns.each do |col|
    # if !(@the_object.columns_hash.keys.include?(col.to_s) || @attachments.keys.include?(col))
    #   raise "couldn't find #{col} in either field list or attachments list"
    # end

    if col.to_s.starts_with?("_")
      @show_only << col
    end

    if @the_object.columns_hash.keys.include?(col.to_s)
      type = @the_object.columns_hash[col.to_s].type
    elsif @attachments.keys.include?(col)
      type = :attachment
    elsif @related_sets.keys.include?(col)
      type = :related_set
    else
      raise "couldn't find #{col} in either field list, attachments, or related sets"
    end
    this_column_object = FieldFactory.new(name: col.to_s,
                                          generator: self,
                                          type: type)
    field = this_column_object.field
    if field.is_a?(AssociationField)
      @associations << field.assoc_name.to_sym
    end
    @columns_map[col] = this_column_object.field
  end


  @columns_map.each do |key, field|
    if field.is_a?(AssociationField)
      if @modify_as && @modify_as[key] && @modify_as[key][:typeahead]
        assoc_name = field.assoc_name
        file_path = "app/controllers/#{@namespace ? @namespace + "/" : ""}#{assoc_name.pluralize}_typeahead_controller.rb"

        if ! File.exist?(file_path)

          assoc_model = eval("#{class_name}.reflect_on_association(:#{field.assoc_name})")
          assoc_class = assoc_model.class_name
          puts "##############################################"
          puts "WARNING: you specified --modify=#{key}{typeahead} but there is no file at `#{file_path}`; please create one with:"
          puts "bin/rails generate hot_glue:typeahead #{assoc_class} #{namespace ? " --namespace=\#{namespace}" : ""}"
          puts "##############################################"
        end
      end
    end
  end


  puts "------ ALT LOOKUPS for #{@alt_lookups}"
  @alt_lookups.each do |key, value|
    if !@columns_map[key.to_sym].is_a?(AssociationField)
      raise "You specified an alt-lookup for #{key} but that field is not an association field"
    elsif !@columns_map[key.to_sym]
      raise "You specified an alt-lookup for #{key} but that field does not exist in the list of columns"
    elsif !@god && !@hawk_keys.include?(key.to_sym) && !@factory_creation
      raise "You specified an alt-lookup for #{key} in non-Gd mode but this would leave the lookup unprotected. To fix, use with --hawk or with --factory-creation "
    end
  end


  if options['phantom_search']
    ps_input = options['phantom_search']
    @phantom_search = {}


    ps_input.split(",").each do |input_setting|
      input_setting =~ /(.*)\[(.*)\]/
      type_and_label, settings = $1, $2


      type = type_and_label.split("_")[0]
      label = type_and_label.split("_")[1]

      choices = settings.split("|")


      @phantom_search[label.to_sym] = {
        type: type,
        name: label.humanize,
        choices: []
      }

      choices.each do |choice|
        if type == "radio"
          choice_label = choice.split(":")[0]
          choice_scope = choice.split(":")[1]
        elsif type == "checkboxes"
          choice_label = choice.split(":")[0]
          choice_scope_negative = choice.split(":")[1]
          choice_scope  = choice.split(":")[2]
        end

        if choice_scope.nil? || choice_scope.strip.empty?
          choice_scope = "all"
        end

        if choice_scope_negative.nil? || choice_scope_negative.strip.empty?
          choice_scope_negative = "all"
        end

        choice_scope = ".#{choice_scope}" if !choice_scope.start_with?(".")
        choice_scope_negative = ".#{choice_scope_negative}" if !choice_scope_negative.start_with?(".")

        @phantom_search[label.to_sym][:choices] << {
          label: choice_label,
          scope: choice_scope,
          scope_negative: choice_scope_negative,
        }
      end
    end


    puts "phantom search #{@phantom_search}"
  else
    @phantom_search = {}
  end

  # search
  @search = options['search']

  if @search == 'set'
    if options['search_fields'].nil?
      if  !@phantom_search
        puts "Since you did not specify search fields or phantom search fields I am including all columns in search"
        @search_fields = @columns
      else
        @search_fields = []
      end
    else
      @search_fields = options['search_fields'].split(',')
    end

    # within the set search we will take out any fields on the query list
    # or the field
    @search_query_fields = options['search_query_fields'].split(',') || []
    @search_position = options['search_position'] || 'vertical'

    @search_fields = @search_fields - @search_query_fields

    @search_clear_button = !!options['search_clear_button']
    @search_autosearch = !!options['search_autosearch']

  elsif @search == 'predicate'

  end

  if @search_fields
    @search_fields.each do |field|
      if !@columns.include?(field.to_sym) && !@phantom_search.include?(field.to_sym)
        raise "You specified a search field for #{field} but that field is not in the list of columns"
      end
    end
  end

  builder = HotGlue::Layout::Builder.new(generator: self,
                                         include_setting: options['include'],
                                         buttons_width: buttons_width)

  @layout_object = builder.construct

  # syntax should be xyz_id{xyz_email},abc_id{abc_email}
  # instead of a drop-down for the foreign entity, a text field will be presented
  # You must ALSO use a factory that contains a parameter of the same name as the 'value' (for example, `xyz_email`)

  # create the template object


  if @markup == "erb"
    @template_builder = HotGlue::ErbTemplate.new(
      layout_object: @layout_object,
      layout_strategy: @layout_strategy,
      magic_buttons: @magic_buttons,
      small_buttons: @small_buttons,
      inline_list_labels: @inline_list_labels,
      show_only: @show_only,
      update_show_only: @update_show_only,
      singular_class: singular_class,
      singular: singular,
      plural: @plural,
      hawk_keys: @hawk_keys,
      ownership_field: @ownership_field,
      form_labels_position: @form_labels_position,
      form_placeholder_labels: @form_placeholder_labels,
      attachments: @attachments,
      columns_map: @columns_map,
      pundit: @pundit,
      related_sets: @related_sets,
      search: @search,
      search_fields: @search_fields,
      search_query_fields: @search_query_fields,
      search_position: @search_position,
      search_clear_button: @search_clear_button,
      search_autosearch: @search_autosearch,
      form_path: form_path_new_helper,
      stimmify: @stimmify,
      stimmify_camel: @stimmify_camel,
      hidden_create: @hidden_create,
      hidden_update: @hidden_update,
      invisible_create: @invisible_create,
      invisible_update: @invisible_update,
      phantom_search: @phantom_search,
      pagination_style: @pagination_style,
      namespace: @namespace,
      controller_build_folder: @controller_build_folder
    )
  elsif @markup == "slim"
    raise(HotGlue::Error, "SLIM IS NOT IMPLEMENTED")
  elsif @markup == "haml"
    raise(HotGlue::Error, "HAML IS NOT IMPLEMENTED")
  end


  @menu_file_exists = true if @nested_set.none? && File.exist?("#{Rails.root}/app/views/#{namespace_with_trailing_dash}_menu.#{@markup}")

  @turbo_streams = !!options['with_turbo_streams']

  puts "show only #{@show_only}"
  puts "update show only #{@update_show_only}"

end

Instance Attribute Details

#alt_lookupsObject

Returns the value of attribute alt_lookups.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def alt_lookups
  @alt_lookups
end

#attachmentsObject

Returns the value of attribute attachments.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def attachments
  @attachments
end

#authObject

Returns the value of attribute auth.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def auth
  @auth
end

Returns the value of attribute back_link_to_parent.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def back_link_to_parent
  @back_link_to_parent
end

#big_editObject

Returns the value of attribute big_edit.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def big_edit
  @big_edit
end

#bootstrap_column_widthObject

Returns the value of attribute bootstrap_column_width.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def bootstrap_column_width
  @bootstrap_column_width
end

#button_iconsObject

Returns the value of attribute button_icons.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def button_icons
  @button_icons
end

#columnsObject

Returns the value of attribute columns.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def columns
  @columns
end

#default_boolean_displayObject

Returns the value of attribute default_boolean_display.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def default_boolean_display
  @default_boolean_display
end

#display_asObject

Returns the value of attribute display_as.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def display_as
  @display_as
end

#downnest_childrenObject

Returns the value of attribute downnest_children.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def downnest_children
  @downnest_children
end

#downnest_objectObject

Returns the value of attribute downnest_object.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def downnest_object
  @downnest_object
end

#form_labels_positionObject

Returns the value of attribute form_labels_position.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def form_labels_position
  @form_labels_position
end

#form_placeholder_labelsObject

Returns the value of attribute form_placeholder_labels.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def form_placeholder_labels
  @form_placeholder_labels
end

#godObject

Returns the value of attribute god.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def god
  @god
end

#hawk_keysObject

Returns the value of attribute hawk_keys.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def hawk_keys
  @hawk_keys
end

#hidden_createObject

Returns the value of attribute hidden_create.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def hidden_create
  @hidden_create
end

#hidden_updateObject

Returns the value of attribute hidden_update.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def hidden_update
  @hidden_update
end

#include_object_namesObject

Returns the value of attribute include_object_names.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def include_object_names
  @include_object_names
end

#invisible_createObject

Returns the value of attribute invisible_create.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def invisible_create
  @invisible_create
end

#invisible_updateObject

Returns the value of attribute invisible_update.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def invisible_update
  @invisible_update
end

#layout_objectObject

Returns the value of attribute layout_object.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def layout_object
  @layout_object
end

#layout_strategyObject

Returns the value of attribute layout_strategy.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def layout_strategy
  @layout_strategy
end

#lazyObject

Returns the value of attribute lazy.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def lazy
  @lazy
end

#modify_asObject

Returns the value of attribute modify_as.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def modify_as
  @modify_as
end

#namespace_valueObject

Returns the value of attribute namespace_value.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def namespace_value
  @namespace_value
end

#nest_withObject

Returns the value of attribute nest_with.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def nest_with
  @nest_with
end

#no_nav_menuObject

Returns the value of attribute no_nav_menu.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def no_nav_menu
  @no_nav_menu
end

#ownership_fieldObject

Returns the value of attribute ownership_field.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def ownership_field
  @ownership_field
end

#pathObject

Returns the value of attribute path.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def path
  @path
end

#phantom_create_paramsObject

Returns the value of attribute phantom_create_params.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def phantom_create_params
  @phantom_create_params
end

#phantom_update_paramsObject

Returns the value of attribute phantom_update_params.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def phantom_update_params
  @phantom_update_params
end

#pluralObject

Returns the value of attribute plural.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def plural
  @plural
end

#polymorphic_parentsObject

Returns the value of attribute polymorphic_parents.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def polymorphic_parents
  @polymorphic_parents
end

#punditObject

Returns the value of attribute pundit.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def pundit
  @pundit
end

#record_scopeObject

Returns the value of attribute record_scope.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def record_scope
  @record_scope
end

Returns the value of attribute related_sets.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def related_sets
  @related_sets
end

#sample_file_pathObject

Returns the value of attribute sample_file_path.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def sample_file_path
  @sample_file_path
end

#search_autosearchObject

Returns the value of attribute search_autosearch.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def search_autosearch
  @search_autosearch
end

#search_clear_buttonObject

Returns the value of attribute search_clear_button.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def search_clear_button
  @search_clear_button
end

#self_authObject

Returns the value of attribute self_auth.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def self_auth
  @self_auth
end

#show_only_dataObject

Returns the value of attribute show_only_data.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def show_only_data
  @show_only_data
end

#singularObject

Returns the value of attribute singular.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def singular
  @singular
end

#singular_classObject

Returns the value of attribute singular_class.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def singular_class
  @singular_class
end

#smart_layoutObject

Returns the value of attribute smart_layout.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def smart_layout
  @smart_layout
end

#stacked_downnestingObject

Returns the value of attribute stacked_downnesting.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def stacked_downnesting
  @stacked_downnesting
end

#stimmifyObject

Returns the value of attribute stimmify.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def stimmify
  @stimmify
end

#stimmify_camelObject

Returns the value of attribute stimmify_camel.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def stimmify_camel
  @stimmify_camel
end

#update_show_onlyObject

Returns the value of attribute update_show_only.



22
23
24
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 22

def update_show_only
  @update_show_only
end

Instance Method Details

#all_line_fieldsObject



1841
1842
1843
1844
1845
1846
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1841

def all_line_fields
  @template_builder.all_line_fields(
    perc_width: @layout_strategy.each_col, # undefined method `each_col'
    layout_strategy: @layout_strategy
  )
end

#all_objects_rootObject



1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1592

def all_objects_root
  if @auth
    if @self_auth
      @singular_class + ".where(id: #{@auth}.id)"
    elsif @nested_set.none?
      @auth + ".#{plural}"
    else
      "@" + @nested_set.last[:singular] + ".#{plural}"
    end
  else
    @singular_class + ".all"
  end
end

#all_viewsObject



1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1770

def all_views
  res = %w(index  _line _list _show)

  unless @no_create
    res += %w(new _new_form _new_button)
  end

  unless @no_edit
    res += %w{edit _edit}
  end

  if !(@no_edit && @no_create)
    res << '_form'
  end

  if @no_list
    res -= %w{_list _line index}
  end

  if @lazy
    res << '_lazy_list'
  end

  res
end

#any_nested?Boolean

Returns:

  • (Boolean)


1606
1607
1608
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1606

def any_nested?
  @nested_set.any?
end

#append_model_callbacksObject



1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1704

def append_model_callbacks
  # somehow the generator invokes this

  if options['with_turbo_streams'] == true
    dest_filename = cc_filename_with_extensions("#{singular_class.underscore}", "rb")
    dest_filepath = File.join("#{filepath_prefix}app/models", dest_filename)

    puts "appending turbo callbacks to #{dest_filepath}"

    text = File.read(dest_filepath)

    append_text = "class #{singular_class} < ApplicationRecord\n"
    if !text.include?("include ActionView::RecordIdentifier")
      append_text << "  include ActionView::RecordIdentifier\n"
    end
    append_text << "  after_update_commit lambda { broadcast_replace_to self, target: \"#{@namespace}__\#{dom_id(self)}\", partial: \"#{@namespace}/#{@plural}/line\" }\n  after_destroy_commit lambda { broadcast_remove_to self, target: \"#{@namespace}__\#{dom_id(self)}\"}\n"

    replace = text.gsub(/class #{singular_class} < ApplicationRecord/, append_text)
    File.open(dest_filepath, "w") { |file| file.puts replace }
  end
end

#auth_identifierObject



1386
1387
1388
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1386

def auth_identifier
  @auth_identifier
end

#auth_objectObject

def all_objects_variable

all_objects_root + ".page(params[:page])"

end



1614
1615
1616
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1614

def auth_object
  @auth
end

#capybara_make_updates(which_partial = :create) ⇒ Object



1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1390

def capybara_make_updates(which_partial = :create)
  @columns_map.map { |col, col_obj|
    show_only_list = which_partial == :create ? @show_only : (@update_show_only + @show_only)

    if show_only_list.include?(col)
      # TODO: decide if this should get re-implemeneted
      # "      page.should have_no_selector(:css, \"[name='#{testing_name}[#{ col.to_s }]'\")"
    else
      col_obj.spec_setup_and_change_act(which_partial)
    end
  }.join("\n")
end

#check_if_sample_file_is_presentObject



1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1190

def check_if_sample_file_is_present
  if sample_file_path.nil?
    puts "you have no sample file path set in config/hot_glue.yml"
    settings = File.read("config/hot_glue.yml")
    @sample_file_path = "spec/files/computer_code.jpg"
    added_setting = ":sample_file_path: #{sample_file_path}"
    File.open("config/hot_glue.yml", "w") { |f| f.write settings + "\n" + added_setting }

    puts "adding `#{added_setting}` to config/hot_glue.yml"
  elsif !File.exist?(sample_file_path)
    puts "NO SAMPLE FILE FOUND: adding sample file at #{sample_file_path}"
    template "computer_code.jpg", File.join("#{filepath_prefix}spec/files/", "computer_code.jpg")
  end

  puts ""
end

#columns_spec_with_sample_dataObject



1326
1327
1328
1329
1330
1331
1332
1333
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1326

def columns_spec_with_sample_data
  @columns_map.map { |col, col_object|
    unless col_object.is_a?(AssociationField)
      random_data = col_object.spec_random_data
      col.to_s + ": '" + random_data.to_s + "'"
    end
  }.join(", ")
end

#controller_class_nameObject



1378
1379
1380
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1378

def controller_class_name
  @controller_build_name
end

#controller_descends_fromObject



1848
1849
1850
1851
1852
1853
1854
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1848

def controller_descends_from
  if defined?(@namespace.titlecase.gsub(" ", "") + "::BaseController")
    @namespace.titlecase.gsub(" ", "") + "::BaseController"
  else
    "ApplicationController"
  end
end

#controller_magic_button_update_actionsObject



1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1900

def controller_magic_button_update_actions
  @magic_buttons.collect { |magic_button|
    "    if #{singular}_params[:#{magic_button}]
    begin
      res = @#{singular}.#{magic_button}!
      res = \"#{magic_button.titleize}ed.\" if res === true
      flash[:notice] = (flash[:notice] || \"\") <<  (res ? res + \" \" : \"\")
    rescue ActiveRecord::RecordInvalid => e
      @#{singular}.errors.add(:base, e.message)
      flash[:alert] = (flash[:alert] || \"\") << 'There was an error #{magic_button}ing your #{@singular}: '
    end
  end"

  }.join("\n") + "\n"
end

#controller_prefix_snakeObject



949
950
951
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 949

def controller_prefix_snake
  @controller_prefix&.underscore
end

#controller_update_params_tap_away_magic_buttonsObject



1916
1917
1918
1919
1920
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1916

def controller_update_params_tap_away_magic_buttons
  @magic_buttons.collect { |magic_button|
    ".tap{ |ary| ary.delete('__#{magic_button}') }"
  }.join("")
end

#copy_controller_and_spec_filesObject



1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1253

def copy_controller_and_spec_files
  @default_colspan = @columns.size

  unless @specs_only || @no_controller
    template "controller.rb.erb", File.join("#{filepath_prefix}app/controllers#{namespace_with_dash}", "#{@controller_build_folder}_controller.rb")
    if @namespace
      begin
        eval(controller_descends_from)
      rescue NameError => e
        template "base_controller.rb.erb", File.join("#{filepath_prefix}app/controllers#{namespace_with_dash}", "base_controller.rb")
      end
    end
  end

  unless @no_specs
    dest_file = File.join("#{filepath_prefix}spec/features#{namespace_with_dash}", "#{plural}_behavior_spec.rb")

    if File.exist?(dest_file)
      existing_file = File.open(dest_file)
      existing_content = existing_file.read
      if existing_content =~ /\# HOTGLUE-SAVESTART/
        if existing_content !~ /\# HOTGLUE-END/
          raise "Your file at #{dest_file} contains a # HOTGLUE-SAVESTART marker without # HOTGLUE-END"
        end
        @existing_content = existing_content[(existing_content =~ /\# HOTGLUE-SAVESTART/)..(existing_content =~ /\# HOTGLUE-END/) - 1]
        @existing_content << "# HOTGLUE-END"

      else
        @existing_content = "  # HOTGLUE-SAVESTART\n  # HOTGLUE-END"
      end
      existing_file.rewind
    else
      @existing_content = "  # HOTGLUE-SAVESTART\n  # HOTGLUE-END"
    end

    template "system_spec.rb.erb", dest_file
  end
  # if !File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/_errors.#{@markup}")
  #   # File.delete("#{filepath_prefix}app/views#{namespace_with_dash}/_errors.#{@markup}")
  #
  #   template "_errors.erb", File.join("#{filepath_prefix}app/views#{namespace_with_dash}", "_errors.#{@markup}")
  # end
end

#copy_view_filesObject



1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1664

def copy_view_files
  return if @specs_only
  @edit_within_form_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_edit_within_form.html.#{@markup}")
  @edit_after_form_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_edit_after_form.html.#{@markup}")
  @new_within_form_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_new_within_form.html.#{@markup}")
  @new_after_form_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_new_within_form.html.#{@markup}")
  @index_before_list_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_index_before_list.html.#{@markup}")
  @list_after_each_row_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_list_after_each_row.html.#{@markup}")
  @list_after_each_row_heading_partial = File.exist?("#{filepath_prefix}app/views#{namespace_with_dash}/#{@controller_build_folder}/_list_after_each_row_heading.html.#{@markup}")
  if @no_controller
    File.write("#{Rails.root}/app/views/#{namespace_with_trailing_dash}/#{plural}/REGENERATE.md", regenerate_me_code)
  end

  all_views.each do |view|
    formats.each do |format|
      source_filename = cc_filename_with_extensions("#{@markup}/#{view}", "#{@markup}")
      dest_filename = cc_filename_with_extensions("#{view}", "#{@markup}")
      dest_filepath = File.join("#{filepath_prefix}app/views#{namespace_with_dash}",
                                @controller_build_folder, dest_filename)

      template source_filename, dest_filepath
      gsub_file dest_filepath, '\%', '%'

    end
  end

  turbo_stream_views.each do |view|
    formats.each do |format|
      source_filename = cc_filename_with_extensions("#{@markup}/#{view}.turbo_stream.#{@markup}")
      dest_filename = cc_filename_with_extensions("#{view}", "turbo_stream.#{@markup}")
      dest_filepath = File.join("#{filepath_prefix}app/views#{namespace_with_dash}",
                                @controller_build_folder, dest_filename)

      template source_filename, dest_filepath
      gsub_file dest_filepath, '\%', '%'

    end
  end
end

#create_actionObject



1883
1884
1885
1886
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1883

def create_action
  return false if @self_auth
  return !@no_create
end

#creation_syntaxObject



1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1211

def creation_syntax
  if @factory_creation.nil? && ! @alt_lookups.any?

    res = (@hawk_keys.any? ?   "modified_params = hawk_params({#{ hawk_to_ruby(in_controller: true) }}, modified_params)\n    " : "")  + "@#{singular } = #{ class_name }.new(modified_params)"
  elsif @factory_creation.nil? && @alt_lookups.any?

    prelookup_syntax = @alt_lookups.collect{|lookup, data|
      col = @columns_map[lookup.to_sym]
      col.prelookup_syntax
    }.join("\n")

    prelookup_syntax + "\n     @#{singular } = #{ class_name }.new(modified_params" +
      (@alt_lookups.any? ? (".merge(" + @alt_lookups.collect{|lookup,field|
        field_name = lookup.gsub("_id","")
        "#{field_name}: #{field_name}"
      }.join(",") + ")" ) : "") + ")"

  else
    res = +"begin
    #{@factory_creation}
    "
    res << "\n      " + "@#{singular} = factory.#{singular}" unless res.include?("@#{singular} = factory.#{singular}")
    res << "\n    rescue ActiveRecord::RecordInvalid"
    res << "\n    @#{singular} = factory.#{singular}"
    res << "\n     @action = 'new'"
  end
  res
end

#current_user_objectObject



1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1618

def current_user_object

  # TODO: in god mode, there's no way for the time input
  # to know who the current user under this design
  # for timeinput = user_centered , we need to know who the current user is
  # so we can set the time zone to the user's time zone

  if options['auth']
    options['auth']
  elsif @god
    "nil"
  else
    @auth
  end
end

#datetime_fields_listObject



1439
1440
1441
1442
1443
1444
1445
1446
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1439

def datetime_fields_list
  @columns.each_with_object({}) do |col, hash|
    column = @the_object.columns_hash[col.to_s]
    if column && [:datetime, :time].include?(column.type)
      hash[col.to_sym] = column.type
    end
  end
end

#delete_path_helperObject



1469
1470
1471
1472
1473
1474
1475
1476
1477
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1469

def delete_path_helper
  res = HotGlue.optionalized_ternary(namespace: @namespace,
                               prefix: (@controller_prefix ? controller_prefix_snake + "_" : ""),
                               target: @singular,
                               nested_set: @nested_set,
                               with_params: false,
                               put_form: true)
  res
end

#destroy_actionObject



1878
1879
1880
1881
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1878

def destroy_action
  return false if @self_auth
  return !@no_delete
end

#display_classObject



1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1856

def display_class
  me = eval(singular_class)

  @display_class ||=
    if me.column_names.include?("name") || me.instance_methods(false).include?(:name)
      # note that all class object respond_to?(:name) with the name of their own class
      # this one is unique
      "name"
    elsif me.column_names.include?("to_label") || me.instance_methods(false).include?(:to_label)
      "to_label"
    elsif me.column_names.include?("full_name") || me.instance_methods(false).include?(:full_name)
      "full_name"
    elsif me.column_names.include?("display_name") || me.instance_methods(false).include?(:display_name)
      "display_name"
    elsif me.column_names.include?("email") || me.instance_methods(false).include?(:email)
      "email"
    else
      exit_message = "*** Oops: Can't find any column to use as the display label on #{singular_class} model . TODO: Please implement just one of: 1) name, 2) to_label, 3) full_name, 4) display_name, 5) email, or 6) number directly on your #{singular_class} model (either as database field or model methods), then RERUN THIS GENERATOR. (If more than one is implemented, the field to use will be chosen based on the rank here, e.g., if name is present it will be used; if not, I will look for a to_label, etc)"
      raise(HotGlue::Error, exit_message)
    end
end

#edit_parent_path_helper(top_level = false) ⇒ Object



1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1426

def edit_parent_path_helper(top_level = false)
  # the path to the edit route of the PARENT
  if @nested_set.any? && @nested
    "edit_#{@namespace + "_" if @namespace}#{(@nested_set.collect { |x| x[:singular] }.join("_") + "_" if @nested_set.any?)}path(" +
    "#{@nested_set.collect { |x| (top_level ? "@": "" ) + x[:singular] }.join(", ")}" + ")"

  else
    "edit_#{@namespace + "_" if @namespace}path"
  end
end

#edit_path_helperObject



1479
1480
1481
1482
1483
1484
1485
1486
1487
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1479

def edit_path_helper
  HotGlue.optionalized_ternary(namespace: @namespace,
                               prefix: (@controller_prefix ? controller_prefix_snake + "_" : ""),
                               target: @singular,
                               nested_set: @nested_set,
                               modifier: "edit_",
                               with_params: false,
                               put_form: true)
end

#factory_testing_nameObject



1305
1306
1307
1308
1309
1310
1311
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1305

def factory_testing_name
  if !@self_auth
    "#{singular}1"
  else
    "current_#{singular}"
  end
end

#fields_filtered_for_strong_paramsObject



1207
1208
1209
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1207

def fields_filtered_for_strong_params
  @columns - @related_sets.collect{|key, set| set[:name]}
end

#filepath_prefixObject



1249
1250
1251
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1249

def filepath_prefix
  'spec/dummy/' if $INTERNAL_SPECS
end

#form_fields_htmlObject



1829
1830
1831
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1829

def form_fields_html
  @template_builder.all_form_fields(layout_strategy: @layout_strategy)
end

#form_path_edit_helperObject



1459
1460
1461
1462
1463
1464
1465
1466
1467
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1459

def form_path_edit_helper
  HotGlue.optionalized_ternary(namespace: @namespace,
                               target:  @singular,
                               prefix: (@controller_prefix ? controller_prefix_snake + "_" : ""),
                               nested_set: @nested_set,
                               with_params: false,
                               put_form: true,
                               top_level: false)
end

#form_path_new_helperObject



1451
1452
1453
1454
1455
1456
1457
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1451

def form_path_new_helper
  HotGlue.optionalized_ternary(namespace: @namespace,
                               target: @controller_build_folder,
                               nested_set: @nested_set,
                               with_params: false,
                               top_level: false)
end

#formatObject



1245
1246
1247
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1245

def format
  nil
end

#formatsObject



1241
1242
1243
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1241

def formats
  [format]
end

#handlerObject



1817
1818
1819
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1817

def handler
  :erb
end

#identify_object_ownerObject



1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1112

def identify_object_owner
  return if @god
  auth_assoc = @auth && @auth.gsub("current_", "")

  if @object_owner_sym && !@self_auth
    auth_assoc_field = auth_assoc + "_id" unless @god

    assoc = eval("#{singular_class}.reflect_on_association(:#{@object_owner_sym})")

    if assoc
      @ownership_field = assoc.name.to_s + "_id"
    elsif !@nested_set.any?
      exit_message = "*** Oops: It looks like is no association `#{@object_owner_sym}` from the object #{@singular_class}. If your user is called something else, pass with flag auth=current_X where X is the model for your users as lowercase. Also, be sure to implement current_X as a method on your controller. (If you really don't want to implement a current_X on your controller and want me to check some other method for your current user, see the section in the docs for auth_identifier.) To make a controller that can read all records, specify with --god."
      raise(HotGlue::Error, exit_message)

    else
      exit_message = "When trying to nest #{singular_class} within #{@nested_set.last[:plural]}, check the #{singular_class} model for the #{@object_owner_sym} association: \n belongs_to :#{@object_owner_sym}"
      raise(HotGlue::Error, exit_message)
    end
  elsif @object_owner_sym && !@object_owner_eval.include?(".")
    @ownership_field = @object_owner_name + "_id"
  end
end

#include_nav_templateObject



1659
1660
1661
1662
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1659

def include_nav_template
  File.exist?("#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.html.#{@markup}") ||
    File.exist?("#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.#{@markup}")
end

#insert_into_nav_templateObject

called from somewhere in the generator



1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1726

def insert_into_nav_template # called from somewhere in the generator
  return if @no_nav_menu
  if include_nav_template
    if File.exist?("#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.html.#{@markup}")
      nav_file = "#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.html.#{@markup}"
    elsif File.exist?("#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.#{@markup}")
      nav_file = "#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.#{@markup}"
    end


    append_text = "  <li class='nav-item'>
  <%= link_to '#{@list_label_heading.humanize}', #{path_helper_plural(@nested_set.any? ? true: false)}, class: \"nav-link \#{'active' if nav == '#{plural_name}'}\" %>
</li>"
    alt_append_text = "<%= link_to '#{@list_label_heading.humanize.upcase}', #{path_helper_plural(@nested_set.any? ? true: false)}, class: \"nav-link \#{'active' if nav == '#{plural_name}'}\" %>"

    check_for_existing_append = "<%= link_to '#{@list_label_heading.humanize}', #{path_helper_plural(@nested_set.any? ? true: false)}, class: \"nav-link \#{'active' if nav == '#{plural_name}'}\" %>"

    text = File.read(nav_file)
    if text.include?(check_for_existing_append) || text.include?(alt_append_text)
      puts "SKIPPING: Nav link for #{singular_name} already exists in #{nav_file}"
    else
      puts "APPENDING: nav link for #{singular_name} #{nav_file}"

      replace = text.gsub(/\<\/ul\>/, append_text + "\n</ul>")

      File.open("#{Rails.root}/app/views/#{namespace_with_trailing_dash}_nav.html.#{@markup}", "w") { |file|
        file.puts replace
      }
    end
  end
end

#line_path_partialObject



1507
1508
1509
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1507

def line_path_partial
  "#{@namespace + "/" if @namespace}#{@controller_build_folder}/line"
end

#list_column_headingsObject



1319
1320
1321
1322
1323
1324
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1319

def list_column_headings
  @template_builder.list_column_headings(
    column_width: @layout_strategy.column_width,
    singular: @singular
  )
end

#list_labelObject



1833
1834
1835
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1833

def list_label
  @list_label_heading
end

#list_path_partialObject



1515
1516
1517
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1515

def list_path_partial
  "#{@namespace + "/" if @namespace}#{@controller_build_folder}/list"
end

#load_all_codeObject



1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1963

def load_all_code
  # the inner method definition of the load_all_* method
  res = +""
  if @search_fields
    res << @search_fields.collect{ |field|
      if !@columns_map[field.to_sym].load_all_query_statement.empty?
        @columns_map[field.to_sym].load_all_query_statement
      end
    }.compact.join("\n" + spaces(4)) + "\n"
  end

  if pundit
    res << "    @#{ plural_name } = policy_scope(#{ object_scope })#{record_scope}\n"
  else
    if !@self_auth

      res << spaces(4) + "@#{ plural_name } = #{ object_scope.gsub("@",'') }#{record_scope}#{ n_plus_one_includes }#{".all" if n_plus_one_includes.blank? && record_scope.blank? }"

      if @search_fields
        res << @search_fields.collect{ |field|
          wqs = @columns_map[field.to_sym].where_query_statement
          if !wqs.empty?
            "\n" + spaces(4) +  "@#{ plural_name } = @#{ plural_name }#{ wqs } if #{field}_query"
          end
        }.compact.join
      end



      # res << "\n    @#{plural} = @#{plural}.page(params[:page])#{ '.per(per)' if @paginate_per_page_selector }"

    elsif @nested_set[0] && @nested_set[0][:optional]
      res << "@#{ plural_name } = #{ class_name }.#{record_scope}.all"
    else
      res << "@#{ plural_name } = #{ class_name }.#{record_scope}.where(id: #{ auth_object.gsub("@",'') }.id)#{ n_plus_one_includes }"

      # res << "#{record_scope}"
    end
    res << "\n"

  end
  if @search_fields
    res << "\n"
    res << @search_fields.collect{ |field|
      spaces(4) + "@#{plural_name} = @#{plural_name}" + @columns_map[field.to_sym].where_query_statement + " if #{field}_query"
    }.join("\n") + "\n"
  end

  @phantom_search.each do |phantom_key, phantom_data|
    if phantom_data[:type] == "radio"
      phantom_data[:choices].each do |choice|
        unless choice[:scope] == ".all"
          res << "\n    @#{plural} = @#{plural}#{choice[:scope]} if @q['0'][:#{phantom_key}_search] == \"#{choice[:label].downcase.gsub(" ","_")}\""
        end
      end
    elsif phantom_data[:type] == "checkboxes"
      phantom_data[:choices].each do |choice|

        # positive case
        unless choice[:scope] == ".all"
          res << "\n    @#{plural} = @#{plural}#{choice[:scope]} if @q['0'][:#{phantom_key}_search__#{choice[:label].gsub(" ", "_").downcase}] == \"1\""
        end
        unless choice[:scope_negative] == ".all"
          res << "\n    @#{plural} = @#{plural}#{choice[:scope_negative]} if @q['0'][:#{phantom_key}_search__#{choice[:label].gsub(" ", "_").downcase}] != \"1\""
        end
      end
    end

    res << "\n"
  end


  if @pagination_style == "kaminari"
    res << "    @#{plural} = @#{plural}.page(params[:page])#{ ".per(per)" if @paginate_per_page_selector }"
  elsif @pagination_style == "will_paginate"
    res << "    @#{plural} = @#{plural}.paginate(page: params[:page], #{ ", per_page: per" if @paginate_per_page_selector })"
  elsif @pagination_style == "pagy9" || @pagination_style == "pagy43"
    res << "    @pagy, @#{plural} = pagy(@#{plural})"
  end
  res
end

#magic_button_outputObject



1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1638

def magic_button_output


  @template_builder.magic_button_output(
    path: HotGlue.optionalized_ternary( namespace: @namespace,
                                        prefix: (@controller_prefix ? controller_prefix_snake + "_" : ""),
                                        target: @singular,
                                        nested_set: @nested_set,
                                        with_params: false,
                                        put_form: true),
    big_edit: @big_edit,
    singular: singular,
    magic_buttons: @magic_buttons,
    small_buttons: @small_buttons
  )
end

#model_has_strings?Boolean

Returns:

  • (Boolean)


1821
1822
1823
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1821

def model_has_strings?
  false
end

#model_search_fieldsObject

an array of fields we can search on



1825
1826
1827
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1825

def model_search_fields # an array of fields we can search on
  []
end

#n_plus_one_includesObject



1932
1933
1934
1935
1936
1937
1938
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1932

def n_plus_one_includes
  if @associations.any? || @attachments.any?
    ".includes(" + (@associations.map { |x| x } + @attachments.collect { |k, v| "#{k}_attachment" } ).map { |x| ":#{x.to_s}" }.join(", ") + ")"
  else
    ""
  end
end

#namespace_with_dashObject



1758
1759
1760
1761
1762
1763
1764
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1758

def namespace_with_dash
  if @namespace
    "/#{@namespace}"
  else
    ""
  end
end

#namespace_with_slashObject



1888
1889
1890
1891
1892
1893
1894
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1888

def namespace_with_slash
  if @namespace
    "#{@namespace}/"
  else
    ""
  end
end

#namespace_with_trailing_dashObject



1766
1767
1768
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1766

def namespace_with_trailing_dash
  @namespace ? "#{@namespace}/" : ""
end


1655
1656
1657
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1655

def nav_template
  "#{namespace_with_trailing_dash}nav"
end

#nest_assignments_operator(top_level = false, leading_comma = false) ⇒ Object



1529
1530
1531
1532
1533
1534
1535
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1529

def nest_assignments_operator(top_level = false, leading_comma = false)
  if @nested_set.any?
    "#{", " if leading_comma}#{top_level ? nested_assignments_top_level : nested_assignments }"
  else
    ""
  end
end

#nest_pathObject



1374
1375
1376
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1374

def nest_path
  @nested_set.collect{| arg| arg[:singular]  }.join("/") + "/" if @nested_set.any?
end

#nested_arity_for_pathObject



1545
1546
1547
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1545

def nested_arity_for_path
  [@nested_set[0..-1].collect { |a| "@#{a[:singular]}" }].join(", ") # metaprgramming into arity for the Rails path helper
end

#nested_assignmentsObject



1520
1521
1522
1523
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1520

def nested_assignments
  return "" if @nested_set.none?
  @nested_set.map { |a| "#{a}: #{a}" }.join(", ") # metaprgramming into Ruby hash
end

#nested_assignments_top_levelObject

this is by accessing the instance variable– only use at top level



1525
1526
1527
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1525

def nested_assignments_top_level # this is by accessing the instance variable-- only use at top level
  @nested_set.map { |a| "#{a[:singular]}" }.join(", ") # metaprgramming into Ruby hash
end

#nested_assignments_with_leading_commaObject



1537
1538
1539
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1537

def nested_assignments_with_leading_comma
  nest_assignments_operator(false, true)
end

#nested_for_assignments_constructor(top_level = true) ⇒ Object



1952
1953
1954
1955
1956
1957
1958
1959
1960
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1952

def nested_for_assignments_constructor(top_level = true)
  instance_symbol = "@" if top_level
  instance_symbol = "" if !top_level
  if @nested_set.none?
    ""
  else
    ", \n    nested_for: \"" + @nested_set.collect { |a| "#{a[:singular]}-" + '#{' + instance_symbol + a[:singular] + ".id}" }.join("__") + "\""
  end
end

#nested_for_turbo_id_list_constructorObject



1924
1925
1926
1927
1928
1929
1930
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1924

def nested_for_turbo_id_list_constructor
  if @nested_set.any?
    '+ (((\'__\' + nested_for) if defined?(nested_for)) || "")'
  else
    ""
  end
end

#nested_for_turbo_nested_constructor(top_level = true) ⇒ Object



1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1940

def nested_for_turbo_nested_constructor(top_level = true)
  instance_symbol = "@" if top_level
  instance_symbol = "" if !top_level
  if @nested_set.none?
    "\"\""
  else
    "\"" + @nested_set.collect { |arg|
      "__#{arg[:singular]}-\#{" + "@" + arg[:singular] + ".id}"
    }.join("") + "\""
  end
end

#nested_objects_arityObject



1541
1542
1543
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1541

def nested_objects_arity
  @nested_set.map { |a| "@#{a[:singular]}" }.join(", ")
end

#nested_pathObject



1363
1364
1365
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1363

def nested_path
  @nested_set.collect{| arg| arg[:plural] + "/\#{#{arg[:singular]}.id}/" }.join("/")
end

#new_path_nameObject



1489
1490
1491
1492
1493
1494
1495
1496
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1489

def new_path_name
  HotGlue.optionalized_ternary(namespace: @namespace,
                               target: singular,
                               prefix: (@controller_prefix ? controller_prefix_snake + "_" : ""),
                               nested_set: @nested_set,
                               modifier: "new_",
                               with_params: false)
end

#new_thing_labelObject



1837
1838
1839
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1837

def new_thing_label
  @new_thing_label
end

#no_devise_installedObject



1634
1635
1636
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1634

def no_devise_installed
  !Gem::Specification.sort_by { |g| [g.name.downcase, g.version] }.group_by { |g| g.name }['devise']
end

#object_parent_mapping_as_argument_for_specsObject



1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1339

def object_parent_mapping_as_argument_for_specs

  if @self_auth
    ""
  elsif @nested_set.any? && !@nested_set.last[:optional]
    ", " + @nested_set.last[:singular] + ": " + @nested_set.last[:singular]
  elsif @auth && !@god
    ", #{@auth_identifier}: #{@auth}"
  end
end

#object_scopeObject



1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1549

def object_scope
  if @nested_set.any? && @nested_set.last[:parent_name] && !@nested_set.last[:polymorph_as]
    if @nested_set.last[:polymorph_as]
      possible_associations = [@nested_set.last[:parent_name].pluralize]
    else
      possible_associations = eval(singular_class).reflect_on_association(( @nested_set.last[:parent_name]).to_sym)
                                                  .klass.reflect_on_all_associations(:has_many)
                                                  .to_a
    end

    association = possible_associations.find{|x|
        if x.source_reflection
          x.table_name == plural
        end
    }

    if !association
      klass = eval(singular_class).reflect_on_association(@nested_set.last[:parent_name].to_sym)
                                  .klass.to_s
      raise "Could not find relation #{plural} on #{klass}; maybe add `has_many :#{plural}` "
    end
    association = association.plural_name

  else
    association = plural
  end


  if @auth && !@god
    if @nested_set.none?
      @auth + ".#{association}"
    else
      "@" + @nested_set.last[:singular] + ".#{association}"
    end
  else
    if @nested_set.none?
      @singular_class
    else
      "@" + @nested_set.last[:singular] + ".#{association}"
    end
  end
end

#objest_nest_factory_setupObject



1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1350

def objest_nest_factory_setup
  res = ""
  if @auth
    last_parent = ", #{@auth_identifier}: #{@auth}"
  end

  @nested_set.each do |arg|
    res << "  let(:#{arg[:singular]}) {create(:#{arg[:singular]} #{last_parent} )}\n"
    last_parent = ", #{arg[:singular]}: #{arg[:singular]}"
  end
  res
end

#objest_nest_params_by_id_for_specsObject



1368
1369
1370
1371
1372
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1368

def objest_nest_params_by_id_for_specs
  @nested_set.map { |arg|
    "#{arg[:singular]}_id: #{arg[:singular] }.id"
  }.join(",\n          ")
end

#omit_fields_formObject

def omit_fields_show

layout_object[:columns][:fields].each { |key, value|
  value[:show] == false
}.reduce(:&)

end



1184
1185
1186
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1184

def omit_fields_form
  layout_object[:columns][:fields].collect { |key, value| value[:form] == false ?  key : nil }.compact.reject!{|x| x.starts_with?("**")} || []
end

#paginateObject



1896
1897
1898
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1896

def paginate
  @template_builder.paginate(plural: plural)
end

#path_arityObject



1499
1500
1501
1502
1503
1504
1505
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1499

def path_arity
  res = ""
  if @nested_set.any? && @nested
    res << nested_objects_arity + ", "
  end
  res << "@" + singular
end

#path_helper_argsObject



1403
1404
1405
1406
1407
1408
1409
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1403

def path_helper_args
  if @nested_set.any? && @nested
    [(@nested_set).collect { |a| "#{a[:singular]}" }, singular].join(",")
  else
    singular
  end
end

#path_helper_plural(top_level = false) ⇒ Object



1419
1420
1421
1422
1423
1424
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1419

def path_helper_plural(top_level = false)
  HotGlue.optionalized_ternary(namespace: @namespace,
                               target: @controller_build_folder,
                               nested_set: @nested_set,
                               top_level: top_level)
end

#path_helper_singularObject



1411
1412
1413
1414
1415
1416
1417
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1411

def path_helper_singular
  if @nested
    "#{@namespace + "_" if @namespace}#{(@nested_set.collect { |x| x[:singular] }.join("_") + "_" if @nested_set.any?)}#{@controller_build_folder_singular}_path"
  else
    "#{@namespace + "_" if @namespace}#{@controller_build_folder_singular}_path"
  end
end

#plural_nameObject



1382
1383
1384
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1382

def plural_name
  plural
end

#regenerate_me_codeObject



1335
1336
1337
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1335

def regenerate_me_code
  "bin/rails generate hot_glue:scaffold #{ @meta_args[0][0] } #{@meta_args[1].collect { |x| x.gsub(/\s*=\s*([\S\s]+)/, '=\'\1\'') }.join(" ")}"
end

#setup_attachmentsObject



1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1013

def setup_attachments
  @attachments = {}

  if options["attachments"]

    options['attachments'].split(",").each do |attachment_entry|
      # format is: avatar{thumbnail|field_for_original_filename}

      if attachment_entry.include?("{")
        num_params = attachment_entry.split("|").count
        if num_params == 1
          attachment_entry =~ /(.*){(.*)}/
          key, thumbnail = $1, $2
        elsif num_params == 2
          attachment_entry =~ /(.*){(.*)\|(.*)}/
          key, thumbnail, field_for_original_filename = $1, $2, $3
        elsif num_params > 2
          if num_params == 3
            attachment_entry =~ /(.*){(.*)\|(.*)\|(.*)}/
            key, thumbnail, field_for_original_filename, direct_upload = $1, $2, $3, $4
          elsif num_params > 3
            attachment_entry =~ /(.*){(.*)\|(.*)\|(.*)\|(.*)}/
            key, thumbnail, field_for_original_filename, direct_upload, dropzone = $1, $2, $3, $4, $5
          end

          field_for_original_filename = nil if field_for_original_filename == ""

          if thumbnail == ''
            thumbnail = nil
          end

          if !direct_upload.nil? && direct_upload != "direct"
            raise HotGlue::Error, "received 3rd parameter in attachment long form specification that was not 'direct'; for direct uploads, just use 'direct' or leave off to disable"
          end

          if !dropzone.nil? && dropzone != "dropzone"
            raise HotGlue::Error, "received 4th parameter in attachme long form specification that was not 'dropzone'; for dropzone, just use 'dropzone' or leave off to disable"
          end

          if dropzone && !direct_upload
            raise HotGlue::Error, "dropzone requires direct_upload"
          end

          if field_for_original_filename && direct_upload
            raise HotGlue::Error, "Unfortunately orig filename extraction doesn't work with direct upload; please set 2nd parameter to empty string to disable"
          end

          direct_upload = !!direct_upload
          dropzone = !!dropzone
        end
      else
        key = attachment_entry

        if !(eval("#{singular_class}.reflect_on_attachment(:#{attachment_entry})"))
          raise HotGlue::Error, "Could not find #{attachment_entry} attachment on #{singular_class}"
        end

        if Rails.version.to_f >= 7.1
          thumb = eval("#{singular_class}.reflect_on_attachment(:#{attachment_entry}).named_variants.include?(:thumb)")
        else
          thumb = eval("#{singular_class}.reflect_on_attachment(:#{attachment_entry}).variants.include?(:thumb)")
        end

        if thumb
          thumbnail = "thumb"
        else
          thumbnail = nil
        end

        direct_upload = nil
        field_for_original_filename = nil
        dropzone = nil
      end

      if thumbnail
        if Rails.version.to_f >= 7.1
          check_for_missing_variant = !eval("#{singular_class}.reflect_on_attachment(:#{key}).named_variants.include?(:#{thumbnail})")
        else
          check_for_missing_variant = !eval("#{singular_class}.reflect_on_attachment(:#{key}).variants.include?(:#{thumbnail})")
        end
        if  check_for_missing_variant
        raise HotGlue::Error, "you specified to use #{thumbnail} as the thumbnail but could not find any such variant on the #{key} attachment; add to your #{singular}.rb file:
has_one_attached :#{key} do |attachable|
  attachable.variant :#{thumbnail}, resize_to_limit: [100, 100]
end
"
        end
      end

      @attachments[key.to_sym] = { thumbnail: thumbnail,
                                   field_for_original_filename: field_for_original_filename,
                                   direct_upload: direct_upload,
                                   dropzone: dropzone }
    end

    puts "ATTACHMENTS: #{@attachments}"
  end
end

#setup_fieldsObject



1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1136

def setup_fields
  if !@include_fields
    @exclude_fields.push :id, :created_at, :updated_at, :encrypted_password,
                         :reset_password_token,
                         :reset_password_sent_at, :remember_created_at,
                         :confirmation_token, :confirmed_at,
                         :confirmation_sent_at, :unconfirmed_email


    # TODO: this should exclude any nested parents
    @exclude_fields.push(@ownership_field.to_sym) if !@ownership_field.nil?

    @columns = @the_object.columns.map(&:name).map(&:to_sym).reject { |field| @exclude_fields.include?(field) }

  else
    @columns = @the_object.columns.map(&:name).map(&:to_sym).reject { |field| !@include_fields.include?(field) }
  end


  @columns = @columns - @nested_set.collect { |set| (set[:singular] + "_id").to_sym  }

  if @attachments.any?
    puts "Adding attachments-as-columns: #{@attachments}"
    @attachments.keys.each do |attachment|
      @columns << attachment if !@columns.include?(attachment)
    end

    check_if_sample_file_is_present
  end

  if @related_sets.any?
    if !@pundit
      puts "********************\nWARNING: You are using --related-sets without using Pundit. This makes the set fully accessible. Use Pundit to prevent a privileged escalation vulnerability\n********************\n"
    end
    @related_sets.each do |key, related_set|
      @columns << related_set[:name] if !@columns.include?(related_set[:name])
      puts "Adding related set :#{related_set[:name]} as-a-column"
    end
  end
end

#setup_hawk_keysObject



954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 954

def setup_hawk_keys
  @hawk_keys = {}

  if options["hawk"]
    options['hawk'].split(",").each do |hawk_entry|

      # format is: abc_id[thing]
      if hawk_entry.include?("{")
        hawk_entry =~ /(.*){(.*)}/
        key, hawk_to = $1, $2
      else
        key = hawk_entry
        hawk_to = @auth
      end


      hawk_scope = key.gsub("_id", "").pluralize
      reflection = eval(singular_class + ".reflect_on_association(:#{key.gsub('_id', '')})")
      raise "Could not find `#{key.gsub('_id', '')}` association; add this to the #{singular_class} class: \nbelongs_to :#{key.gsub('_id', '')} " if reflection.nil?

      optional = reflection.options[:optional]

      # if hawk_to.include?(" ")
      #   @hawk_keys[key.to_sym] = { bind_to: [hawk_to.gsub(" ", ",")], 
      #   polymorphic: true,
      #   optional: optional }

      #   # hawk_to.start_with?("[")
      #   # # Polymorphic hawk: space-separated scopes inside brackets
      #   # # e.g. [account.companies account.vc_firms]
      #   # raise "#{key} is not a polymorphic association; add `polymorphic: true` to belongs_to :#{key.gsub('_id', '')} in #{singular_class}" unless reflection.options[:polymorphic]
      #   # scopes = hawk_to.gsub(/^\[|\]$/, "").split(" ")
      #   # @hawk_keys[key.to_sym] = { bind_to: scopes, polymorphic: true, optional: optional }
      # else
      # 
      if hawk_to.include?(" ")
        hawk_to.gsub!(" ", ",")
        polymorphic = true
      else
        polymorphic = false
      end

      @hawk_keys[key.to_sym] = { bind_to: [hawk_to],
        optional: optional , 
        polymorphic: polymorphic}
      
      
      use_shorthand = !options["hawk"].include?("{")
      if use_shorthand # only include the hawk scope if using the shorthand
        @hawk_keys[key.to_sym][:bind_to] << hawk_scope
      end
      # end

    end

    puts "HAWKING: #{@hawk_keys}"
  end
end

#show_path_partialObject



1511
1512
1513
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1511

def show_path_partial
  "#{@namespace + "/" if @namespace}#{@controller_build_folder}/show"
end

#spec_foreign_association_merge_hashObject



1297
1298
1299
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1297

def spec_foreign_association_merge_hash
  ", #{testing_name}: #{testing_name}1"
end


1313
1314
1315
1316
1317
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1313

def spec_related_column_lets
  @columns_map.collect { |col, col_object|
    col_object.spec_related_column_lets
  }.join("\n")
end

#testing_nameObject



1301
1302
1303
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1301

def testing_name
  singular_class.gsub("::", "_").underscore
end

#turbo_stream_viewsObject



1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
# File 'lib/generators/hot_glue/scaffold_generator.rb', line 1796

def turbo_stream_views
  res = []
  unless @no_delete
    res << 'destroy'
  end

  unless @no_create
    res << 'create'
  end

  unless @no_edit
    res << 'edit'

    unless @big_edit
      res << 'update'
    end
  end

  res
end