lib/og/enchant.rb in og-0.11.0 vs lib/og/enchant.rb in og-0.12.0

- old
+ new

@@ -8,58 +8,69 @@ # Enchant a managed class. Add useful DB related methods # to the class and its instances. def enchant(klass) - klass.module_eval <<-"end_eval", __FILE__, __LINE__ + + # Generate standard methods. + + klass.module_eval %{ def self.create(*params, &block) obj = #{klass}.new(*params, &block) obj.save! end def self.save(obj) - Og.db << obj + @@og_db << obj end def self.load(oid_or_name) - Og.db.load(oid_or_name, #{klass}) + @@og_db.load(oid_or_name, #{klass}) end def self.get(oid_or_name) - Og.db.load(oid_or_name, #{klass}) + @@og_db.load(oid_or_name, #{klass}) end def self.[](oid_or_name) - Og.db.load(oid_or_name, #{klass}) + @@og_db.load(oid_or_name, #{klass}) end def self.load_all(extra_sql = nil) - Og.db.load_all(#{klass}, extra_sql) + @@og_db.load_all(#{klass}, extra_sql) end def self.all(extra_sql = nil) - Og.db.load_all(#{klass}, extra_sql) + @@og_db.load_all(#{klass}, extra_sql) end def self.count(sql = "SELECT COUNT(*) FROM #{klass::DBTABLE}") - Og.db.count(sql, #{klass}) + @@og_db.count(sql, #{klass}) end def self.select(sql) - Og.db.select(sql, #{klass}) + @@og_db.select(sql, #{klass}) end + + def self.find(sql) + @@og_db.select(sql, #{klass}) + end def self.select_one(sql) - Og.db.select_one(sql, #{klass}) + @@og_db.select_one(sql, #{klass}) end + def self.find_one(sql) + @@og_db.select_one(sql, #{klass}) + end + def self.one(sql) - Og.db.select_one(sql, #{klass}) + @@og_db.select_one(sql, #{klass}) end def self.delete(obj_or_oid) - Og.db.delete(obj_or_oid, #{klass}) + @@og_db.delete(obj_or_oid, #{klass}) end def self.properties_and_relations @@__meta[:props_and_relations] end @@ -68,23 +79,46 @@ all.each(&block) end include Enumerable def save - Og.db << self + @@og_db << self return self end alias_method :save!, :save def update_properties(updatesql) - Og.db.pupdate(updatesql, self.oid, #{klass}) + @@og_db.pupdate(updatesql, self.oid, #{klass}) end alias_method :pupdate!, :update_properties def delete! - Og.db.delete(@oid, #{klass}) + @@og_db.delete(@oid, #{klass}) end - end_eval + } + + # Generate finder methods. + + code = '' + + for p in klass.__props + code << %{ + def self.find_by_#{p.name}(val, operator = '=', extra_sql = nil) + } + + val = klass.og_db.adapter.typecast[p.klass].gsub(/\:s\:/, 'val') + + if p.meta[:unique] + code << %{@@og_db.select_one("#{p.name}\#\{operator\}#{val} \#\{extra_sql\}", #{klass})} + else + code << %{@@og_db.select("#{p.name}\#\{operator\}#{val} \#\{extra_sql\}", #{klass})} + end + code << %{ + end; + } + end + + klass.module_eval(code) end end end