Module: ModelBuilder

Defined in:
lib/model_builder.rb,
lib/model_builder/version.rb,
lib/model_builder/class_builder.rb

Defined Under Namespace

Modules: ClassBuilder

Constant Summary collapse

VERSION =
'2.1.0'

Class Method Summary collapse

Class Method Details

.build(class_full_name, opts = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/model_builder.rb', line 7

def self.build(class_full_name, opts={})
  opts.reverse_merge! get_default_options

  already_exists = Object.const_defined? class_full_name
  klass = ClassBuilder.build class_full_name, opts

  unless already_exists
    create_table class_full_name, opts
    define_validations klass, opts[:validates]
  end

  klass
end

.cleanObject



59
60
61
62
63
# File 'lib/model_builder.rb', line 59

def self.clean
  dynamic_models.map {|c| drop_table c }
  @@dynamic_models = []
  ClassBuilder.clean
end

.create_attribute(migration, key, opts) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/model_builder.rb', line 42

def self.create_attribute(migration, key, opts)
  if opts.is_a?(Hash)
    opts = opts.clone
    type = opts.delete :type
  else
    type = opts
    opts = {}
  end
  migration.send(type, key, opts)
end

.create_attributes(migration, attributes = {}) ⇒ Object



36
37
38
39
40
# File 'lib/model_builder.rb', line 36

def self.create_attributes(migration, attributes={})
  attributes.each_pair do |key, value|
    create_attribute(migration, key, value)
  end
end

.create_table(class_full_name, opts) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/model_builder.rb', line 28

def self.create_table(class_full_name, opts)
  ActiveRecord::Migration.create_table(class_full_name.tableize) do |migration|
    create_attributes(migration, opts[:attributes])
  end

  @@dynamic_models << class_full_name
end

.define_validations(klass, validations) ⇒ Object



53
54
55
56
57
# File 'lib/model_builder.rb', line 53

def self.define_validations(klass, validations)
  return if validations.nil? or !validations.kind_of?(Array) or validations.empty?
  validations = [validations] unless validations.first.kind_of? Array
  validations.each {|v| klass.validates *v}
end

.drop_table(class_full_name) ⇒ Object



69
70
71
# File 'lib/model_builder.rb', line 69

def self.drop_table(class_full_name)
  ActiveRecord::Migration.drop_table(class_full_name.tableize)
end

.dynamic_modelsObject



65
66
67
# File 'lib/model_builder.rb', line 65

def self.dynamic_models
  @@dynamic_models
end

.get_default_optionsObject



21
22
23
24
25
26
# File 'lib/model_builder.rb', line 21

def self.get_default_options
  {
    superclass: ::ActiveRecord::Base,
    attributes: {}
  }
end