Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'rubygems'
- require 'activerecord'
- class ActiveRecord::Base
- alias_method '__initialize__', 'initialize'
- def initialize options = nil, &block
- returning( __initialize__(options, &block) ) do
- options ||= {}
- options.to_options!
- defaults = self.class.defaults || self.defaults || Hash.new
- (defaults.keys - options.keys).each do |key|
- value = defaults[key]
- case value
- when Proc
- value = instance_eval &value
- when Symbol
- value = send value
- end
- send "#{ key }=", value
- end
- end
- end
- def self.defaults *argv
- @defaults = argv.shift.to_hash if argv.first
- return @defaults if defined? @defaults
- end
- def defaults *argv
- @defaults = argv.shift.to_hash if argv.first
- return @defaults if defined? @defaults
- end
- module UnQuoted
- def quoted_id()
- STDERR.puts "CALLED quoted_id"
- self
- end ### hackity hack hack
- end
- unless defined? DEFAULT
- STDERR.puts "CREATING DEFAULT"
- DEFAULT = 'DEFAULT'
- DEFAULT.extend UnQuoted
- DEFAULT.freeze
- end
- before_create :force_default_where_necessary
- # force the sql keyword DEFAULT into those columns where there must be a
- # default value, that is, columns with a default that are not nullable, those
- # should have the DEFAULT keyword set⋅
- def force_default_where_necessary
- STDERR.puts "force default_where_necessary"
- @attributes.each_pair do |name, value|
- STDERR.puts "Checking on #{self.class.name}::#{name} with value #{value.inspect}"
- unless value
- column = column_for_attribute(name)
- STDERR.puts "checking column type -> #{column.type.inspect}, sql_type -> #{column.sql_type.inspect}, default -> #{column.default.inspect}"
- STDERR.puts "checking column has_default? -> #{column.has_default?.inspect}, null -> #{column.null.inspect}"
- if (name == 'created_time') or (column.has_default? and !column.null) then
- STDERR.puts "Setting #{self.class.name}##{name.inspect} to #{DEFAULT}"
- send "#{name}=", DEFAULT
- end
- end
- end
- end
- end
- class Datetest < ActiveRecord::Base
- defaults 'created_time' => DEFAULT
- end
- DbConfig = { :username => 'postgres', :password => "", :database => 'mcore', :adapter => "postgresql" }
- ActiveRecord::Base.establish_connection( DbConfig )
- ActiveRecord::Base.connection.execute(<<-table)
- CREATE TABLE DateTests(
- id serial not null primary key ,
- created_time timestamp not null default current_timestamp
- )
- table
- dt = Datetest.create!
- ActiveRecord::Base.connection.execute("DROP TABLE DateTests")
Add Comment
Please, Sign In to add comment