Class: Rmre::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/rmre/generator.rb

Constant Summary collapse

SETTINGS_ROOT =
File.expand_path('../../../../db', __FILE__)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, out_path, include, custom_inflections) ⇒ Generator

Returns a new instance of Generator.



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rmre/generator.rb', line 13

def initialize(options, out_path, include, custom_inflections)
  @connection_options = options
  @connection = nil
  @output_path = out_path
  @include_prefixes = include
  ActiveSupport::Inflector.inflections do |inflect|
    custom_inflections.each do |ci|
      inflect.plural(/#{ci[:plural].first}/, ci[:plural].second)
      inflect.singular(/#{ci[:singular].first}/, ci[:singular].second)
    end if custom_inflections.is_a? Array
  end
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



8
9
10
# File 'lib/rmre/generator.rb', line 8

def connection
  @connection
end

#output_pathObject (readonly)

Returns the value of attribute output_path.



9
10
11
# File 'lib/rmre/generator.rb', line 9

def output_path
  @output_path
end

Instance Method Details

#connectObject



26
27
28
29
30
31
# File 'lib/rmre/generator.rb', line 26

def connect
  return if @connection_options.empty?

  ActiveRecord::Base.establish_connection(@connection_options)
  @connection = ActiveRecord::Base.connection
end

#create_model(table_name) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rmre/generator.rb', line 47

def create_model(table_name)
  File.open(File.join(output_path, "#{table_name.tableize.singularize}.rb"), "w") do |file|
    constraints = []

    foreign_keys.each do |fk|
      src = constraint_src(table_name, fk)
      constraints << src unless src.nil?
    end

    file.write generate_model_source(table_name, constraints)
  end
end

#create_models(tables) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/rmre/generator.rb', line 33

def create_models(tables)
  return unless tables.is_a? Array

  FileUtils.mkdir_p(@output_path) if !Dir.exists?(@output_path)

  tables.each do |table_name|
    create_model(table_name) if process?(table_name)
  end
end

#dump_schema(stream) ⇒ Object



43
44
45
# File 'lib/rmre/generator.rb', line 43

def dump_schema(stream)
  ActiveRecord::SchemaDumper.dump_with_fk(connection, foreign_keys, stream)
end

#foreign_keysObject



70
71
72
# File 'lib/rmre/generator.rb', line 70

def foreign_keys
  @foreign_keys ||= fetch_foreign_keys
end

#process?(table_name) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
63
64
65
66
67
68
# File 'lib/rmre/generator.rb', line 60

def process?(table_name)
  return true if @include_prefixes.nil? || @include_prefixes.empty?

  @include_prefixes.each do |prefix|
    return true if table_name =~ /^#{prefix}/
  end

  false
end