Module: Schemer::Sequel::ClassMethods
- Defined in:
- lib/schemer/sequel.rb
Instance Method Summary collapse
- #protected_columns ⇒ Object
-
#schema(*args) ⇒ Object
Define a schema on your Sequel model.
- #schema_columns ⇒ Object
-
#update_schema ⇒ Object
Update the underlying schema as defined by schema call.
Instance Method Details
#protected_columns ⇒ Object
32 33 34 |
# File 'lib/schemer/sequel.rb', line 32 def protected_columns @protected_columns = [ :id ].freeze end |
#schema(*args) ⇒ Object
Define a schema on your Sequel model.
schema :name, { :age => :integer }, { :birthdate => :datetime }, :summary
Table + columns will be added automatically based on your definition.
If you remove a column, it will be removed from the table the next time the class is loaded.
If you change the type of a column, it will be also be updated the next time the class is loaded.
Likewise, adding a new column will add the column to your schema on the next class load.
Columns with no types are assumed to be strings.
22 23 24 25 26 27 28 29 30 |
# File 'lib/schemer/sequel.rb', line 22 def schema(*args) @schema_columns = {} args.collect{ |a| a.is_a?(Hash) ? a : { a => String } }.each do |column| self.schema_columns.merge!(column) end update_schema end |
#schema_columns ⇒ Object
36 37 38 |
# File 'lib/schemer/sequel.rb', line 36 def schema_columns @schema_columns end |
#update_schema ⇒ Object
Update the underlying schema as defined by schema call
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 |
# File 'lib/schemer/sequel.rb', line 41 def update_schema db.create_table?(self.table_name) do primary_key :id end get_db_schema.reject{ |column, definition| protected_columns.include?(column) }.each do |column, definition| if !schema_columns.has_key?(column) # remove any extraneous columns db.drop_column(table_name, column) # remove the accessors (sequel doesn't appear to have a facility # for this) [ "#{column}", "#{column}=" ].each do |method| overridable_methods_module.send(:undef_method, method) if public_instance_methods.include?(method) end elsif (definition[:type] || definition[:db_type]) != schema_columns[column] # change any columns w/ wrong type db.set_column_type(table_name, column, schema_columns[column]) end end # add any missing columns (schema_columns.keys - columns).each do |column| db.add_column(table_name, column, schema_columns[column]) def_column_accessor column end end |