Module: Schemer::ActiveRecord::ClassMethods

Defined in:
lib/schemer/active_record.rb

Instance Method Summary collapse

Instance Method Details

#create_tableObject

Create the underlying table for this class



42
43
44
45
46
# File 'lib/schemer/active_record.rb', line 42

def create_table
  ::ActiveRecord::Migration.suppress_messages do
    ::ActiveRecord::Migration.create_table(table_name) do |t|;end;
  end
end

#migrate_quietly(&block) ⇒ Object



75
76
77
78
79
# File 'lib/schemer/active_record.rb', line 75

def migrate_quietly(&block)
  ::ActiveRecord::Migration.suppress_messages do
    yield
  end
end

#protected_columnsObject

Columns which we don’t touch regardless of not being defined in schema (and are ignored if they are defined in schema)



37
38
39
# File 'lib/schemer/active_record.rb', line 37

def protected_columns
  %w( id )
end

#update_methodsObject

Update ActiveRecord’s automatically generated methods so we don’t have to reload for schema changes to take effect



50
51
52
53
# File 'lib/schemer/active_record.rb', line 50

def update_methods
  undefine_attribute_methods
  @columns = @column_names = @columns_hash = @generated_methods = nil
end

#update_schemaObject

Update the underlying schema as defined by schema call



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/schemer/active_record.rb', line 56

def update_schema
  create_table unless table_exists?

  columns.reject{ |column| protected_columns.include?(column.name) }.each do |column|
    if !schema_columns.has_key?(column.name)
      # remove any extraneous columns
      migrate_quietly{ ::ActiveRecord::Migration.remove_column(table_name, column.name) }
    elsif column.type != schema_columns[column.name]
      # change any columns w/ wrong type
      migrate_quietly{ ::ActiveRecord::Migration.change_column(table_name, column.name, schema_columns[column.name]) }
    end
  end

  # add any missing columns
  (schema_columns.keys - column_names).each do |column|
    migrate_quietly{ ::ActiveRecord::Migration.add_column(table_name, column, schema_columns[column]) }
  end
end