Class: ScaffoldPlus::Generators::ManyToManyGenerator

Inherits:
ActiveRecord::Generators::Base
  • Object
show all
Defined in:
lib/generators/scaffold_plus/many_to_many/many_to_many_generator.rb

Instance Method Summary collapse

Instance Method Details

#add_counterObject



36
37
38
39
# File 'lib/generators/scaffold_plus/many_to_many/many_to_many_generator.rb', line 36

def add_counter
  return unless options.counter?
  migration_template 'counter_migration.rb', "db/migrate/#{counter_migration}.rb"
end

#add_migrationObject



31
32
33
34
# File 'lib/generators/scaffold_plus/many_to_many/many_to_many_generator.rb', line 31

def add_migration
  return unless options.migration?
  migration_template 'many_to_many_migration.rb', "db/migrate/#{migration_name}.rb"
end

#add_to_modelsObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/generators/scaffold_plus/many_to_many/many_to_many_generator.rb', line 41

def add_to_models
  [[one, two], [two, one]].each do |pair|
    current, partner = pair
    inject_into_class "app/models/#{current}.rb", current.camelize do
      text = before_array.include?(current) ? "\n" : ""
      text << "  has_many :#{table_name}"
      text << ", dependent: :#{dependent}" if options.dependent.present?
      text << "\n"
      text << "  has_many :#{partner.pluralize}, through: :#{table_name}\n"
      if current == one
        text << "  accepts_nested_attributes_for :#{table_name}\n" if options.nested.present?
      end
      text << "\n" if after_array.include?(current)
      text
    end
  end

  template 'many_to_many_model.rb', "app/models/#{name}.rb"
end

#add_to_permitObject



61
62
63
64
65
66
67
68
69
# File 'lib/generators/scaffold_plus/many_to_many/many_to_many_generator.rb', line 61

def add_to_permit
  return unless options.nested.present?
  list = options.nested.map{|n| ":#{n}"}.join(', ')
  text = "#{table_name}_attributes: [ #{list} ]"
  file = "app/controllers/#{one.pluralize}_controller.rb"
  gsub_file file, /(permit\(.*)\)/, "\\1, #{text})"
  # Special case: no previous permit
  gsub_file file, /^(\s*params)\[:#{name}\]$/, "\\1.require(:#{name}).permit(#{text})"
end