Class: ModelFromSqlGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/support/model_from_sql/model_from_sql_generator.rb

Instance Method Summary collapse

Instance Method Details

#build_modelsObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/support/model_from_sql/model_from_sql_generator.rb', line 4

def build_models
  ap 'args is '
  ap args[0]
  tables = ActiveRecord::Base.connection.tables

  Rails.application.eager_load!
  in_models = ActiveRecord::Base.descendants.map(&:table_name)
  ap 'tables from database'
  ap tables
  ap in_models
  new_tables = tables - in_models - ['schema_migrations', 'ar_internal_metadata']
  if args[0]
    new_tables = new_tables.select {|table| table.include?(args[0])}
  end


  ap 'new tables'
  ap new_tables

  new_tables.each do |table_name|
    generate "model #{table_name} --skip-migration" # or whatever you want here
    model_file = "app/models/#{table_name.singularize}.rb"
    ap 'new model file'
    ap 'output columns'
    self.generate_migrate(table_name)
    ap model_file
    inject_into_file model_file, before: "end\n" do "self.table_name = \"table_name_replace\"\n    RUBY\n    end\n    gsub_file model_file, 'table_name_replace', table_name\n  end\nend\n"

#generate_migrate(table_name) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/support/model_from_sql/model_from_sql_generator.rb', line 38

def generate_migrate(table_name)
  valid_columns = ActiveRecord::Base.connection.columns(table_name).select {|column| !['id', 'created_at', 'updated_at'].include?(column.name)}
  ap valid_columns
  add_columns = valid_columns.map do |column|
    ap column
    ap column.name
    ap column.default
    ap column.comment
    ap column.
    sql = "add_column :#{column.table_name}, :#{column.name}, :#{column.sql_type_metadata.type}"
    sql += ", default: #{column.default}" if column.default && column.default.is_a?(Integer)
    sql += ", default: '#{column.default}'" if column.default && column.default.is_a?(String)
    sql += ", comment: '#{column.comment}'" if column.comment
    sql += ", null: #{column.null}"
    sql
  end
  ap add_columns
  migrate_file = "db/migrate/#{Time.now.strftime("%Y%m%d%H%M%S")}_create_#{table_name}.rb"
  run "touch #{migrate_file}"
  run "echo 'replace\n' >> #{migrate_file}"
  inject_into_file migrate_file, before: "replace\n" do "class CreateModelReplace < ActiveRecord::Migration\ndef change\n  create_table :table_replace\n  add_columns\nend\nend\n  RUBY\n  end\n  gsub_file migrate_file, 'ModelReplace', table_name.camelize\n  gsub_file migrate_file, 'add_columns', add_columns.join(\"\\n    \")\n  gsub_file migrate_file, 'table_replace', table_name.pluralize\n  gsub_file migrate_file, 'replace', ''\nend\n"