Class: Effective::LiveGenerator

Inherits:
Object
  • Object
show all
Defined in:
app/models/effective/live_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ LiveGenerator

Returns a new instance of LiveGenerator.



7
8
9
10
11
12
13
14
15
# File 'app/models/effective/live_generator.rb', line 7

def initialize(obj)
  @resource = (obj.kind_of?(Effective::Resource) ? obj: Effective::Resource.new(obj))

  unless @resource.respond_to?(:model) && @resource.model.present?
    raise 'expected effective_resource or klass to have an effective_resource do ... end block defined'
  end

  true
end

Instance Attribute Details

#resourceObject

The class level effective_resource do … end object



5
6
7
# File 'app/models/effective/live_generator.rb', line 5

def resource
  @resource
end

Instance Method Details

#generate!Object

Writes database migrations automatically based on effective_resources do … end block



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/models/effective/live_generator.rb', line 18

def generate!
  table_attributes = resource.table_attributes
  model_attributes = resource.model_attributes

  table_keys = table_attributes.keys
  model_keys = model_attributes.keys

  # Create table
  if table_keys.blank?
    Rails.logger.info "effective_developer migrate #{resource.plural_name}: create table"
    return rails_migrate("create_#{resource.plural_name}", model_attributes)
  end

  # Fields are not in database, but present in model.rb
  if(add_keys = (model_keys - table_keys)).present?
    Rails.logger.info "effective_developer migrate #{resource.plural_name}: add #{add_keys.to_sentence}"
    rails_migrate("add_ATTRIBUTES_to_#{resource.plural_name}", model_attributes.slice(*add_keys))
  end

  # Fields are in database, but no longer in our effective_resource do block
  if (remove_keys = (table_keys - model_keys)).present?
    Rails.logger.info "effective_developer migrate #{resource.plural_name}: remove #{remove_keys.to_sentence}"
    rails_migrate("remove_ATTRIBUTES_from_#{resource.plural_name}", table_attributes.slice(*remove_keys))
  end
end