Class: ScaffoldPlus::Generators::CreatedByGenerator

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

Instance Method Summary collapse

Instance Method Details

#add_migrationObject



19
20
21
22
# File 'lib/generators/scaffold_plus/created_by/created_by_generator.rb', line 19

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

#add_to_controllerObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/generators/scaffold_plus/created_by/created_by_generator.rb', line 50

def add_to_controller
  file = "app/controllers/#{table_name}_controller.rb"
  inject_into_file file, after: /def update$/ do
    "\n    @#{name}.updated_by = current_#{user}.id if current_#{user}"
  end
  inject_into_file file, after: /@#{name} = #{class_name}\.new\(#{name}_params\)$/ do
    "\n    @#{name}.created_by = current_#{user}.id if current_#{user}" +
    "\n    @#{name}.updated_by = current_#{user}.id if current_#{user}"
  end
end

#add_to_modelObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/generators/scaffold_plus/created_by/created_by_generator.rb', line 24

def add_to_model
  [ "created", "updated" ].each do |action|
    user_name = "#{user.camelize}.find(#{action}_by).try('name')"
    user_email = "#{user.camelize}.find(#{action}_by).try('email')"
    lines = options.before? ? [ "" ] : []
    lines << [
      "  def #{action}_by_name",
      "    #{user_name}",
      "  end",
      ""
    ]
    lines << [ "" ] if options.after?
    inject_into_class "app/models/#{name}.rb", class_name, lines.join("\n")
    
    lines = options.before? ? [ "" ] : []
    lines << [
      "  def #{action}_by_email",
      "    #{user_name} <#{user_email}>",
      "  end",
      ""
    ]
    lines << [ "" ] if options.after?
    inject_into_class "app/models/#{name}.rb", class_name, lines.join("\n")
  end
end