lib/sequel/model.rb in sequel-0.1.1 vs lib/sequel/model.rb in sequel-0.1.2

- old
+ new

@@ -7,10 +7,13 @@ def self.db @db ||= ((superclass != Object) && (superclass.db)) || nil end def self.db=(db); @db = db; end + def self.database_opened(db) + @db = db if self == Model && !@db + end def self.table_name @table_name ||= ((superclass != Model) && (superclass.table_name)) || nil end def self.set_table_name(t); @table_name = t; end @@ -88,10 +91,14 @@ def self.recreate_table drop_table if table_exists? create_table end + def self.subset(name, *args, &block) + meta_def(name) {filter(*args, &block)} + end + ONE_TO_ONE_PROC = "proc {i = @values[:%s]; %s[i] if i}".freeze ID_POSTFIX = "_id".freeze FROM_DATASET = "db[%s]".freeze def self.one_to_one(name, opts) @@ -124,29 +131,41 @@ def run_hooks(key) self.class.get_hooks(key).each {|h| instance_eval(&h)} end + def self.before_save(&block) + get_hooks(:before_save).unshift(block) + end + def self.before_create(&block) get_hooks(:before_create).unshift(block) end def self.before_destroy(&block) get_hooks(:before_destroy).unshift(block) end - def self.after_destroy(&block) - get_hooks(:after_destroy).unshift(block) + def self.after_save(&block) + get_hooks(:after_save) << block end def self.after_create(&block) get_hooks(:after_create) << block end + def self.after_destroy(&block) + get_hooks(:after_destroy).unshift(block) + end + def self.find(cond) dataset[cond.is_a?(Hash) ? cond : {primary_key => cond}] end + + def self.find_or_create(cond) + find(cond) || create(cond) + end class << self; alias_method :[], :find; end ############################################################################ @@ -175,12 +194,12 @@ self end def self.each(&block); dataset.each(&block); end def self.all; dataset.all; end - def self.filter(*arg); dataset.filter(*arg); end - def self.exclude(*arg); dataset.exclude(*arg); end + def self.filter(*arg, &block); dataset.filter(*arg, &block); end + def self.exclude(*arg, &block); dataset.exclude(*arg, &block); end def self.order(*arg); dataset.order(*arg); end def self.first(*arg); dataset.first(*arg); end def self.count; dataset.count; end def self.map(*arg, &block); dataset.map(*arg, &block); end def self.hash_column(column); dataset.hash_column(primary_key, column); end @@ -250,17 +269,17 @@ def id; @values[:id]; end def save run_hooks(:before_save) if @pkey - # run_hooks(:before_update) + run_hooks(:before_update) model.dataset.filter(primary_key => @pkey).update(@values) - # run_hooks(:after_update) + run_hooks(:after_update) else - # run_hooks(:before_create) + run_hooks(:before_create) @pkey = model.dataset.insert(@values) refresh - # run_hooks(:after_create) + run_hooks(:after_create) end run_hooks(:after_save) end def ==(obj)