# code: # * George Moschovitis # # (c) 2004 Navel, all rights reserved. # $Id: meta.rb 124 2004-11-01 12:34:17Z gmosx $ module N # = OgMetaUtils # # Some useful meta-language utilities. # module OgMetaUtils # :nodoc: all # Conver the klass to a string representation # The leading module if available is removed. # def self.expand(klass) return klass.name.gsub(/^.*::/, "").gsub(/::/, "_").downcase end end # = OgMetaLanguage # # Implements a meta-language for manipulating og-managed objects # and defining their relationships. The original idea comes # from the excellent ActiveRecord library. # # Many more useful relations will be available soon. # module OgMetaLanguage # Implements a 'belongs_to' relation. # Automatically enchants the calling class with helper methods. # # Example: # # class MyObject # belongs_to AnotherObject, :parent # end # # creates the code: # # prop_accessor Fixnum, :parent_oid # def parent; ... end # def parent=(obj_or_oid); ... end # def belongs_to(klass, name, options = {}) module_eval %{ prop_accessor Fixnum, :#{name}_oid def #{name} $og.load_by_oid(@#{name}_oid, #{klass}) end def #{name}=(obj_or_oid) @#{name}_oid = obj_or_oid.to_i end } end # Implements a 'has_many' relation. # Automatically enchants the calling class with helper methods. # # NOT IMPLEMENTED. # # Example: # # class MyObject # has_many AnotherObject, :children # end # # creates the code: # # def children; ... end # def has_one(klass, name, options = {}) module_eval %{ def #{name}(extrasql = nil) $og.select_one("article_oid=\#\@oid \#\{extrasql\}", #{klass}) end } end # Implements a 'has_many' relation. # Automatically enchants the calling class with helper methods. # # Example: # # class MyObject # has_many AnotherObject, :children # end # # creates the code: # # def children; ... end # def has_many(klass, name, options = {}) # linkback is the property of the child object that 'links back' # to this object. linkback = options[:linkback] || "#{N::OgMetaUtils.expand(self)}_oid" module_eval %{ @@og_descendants ||= {} @@og_descendants[#{klass}] = :#{linkback} unless defined?(og_descendants) def self.og_descendants @@og_descendants end end def #{name}(extrasql = nil) $og.select("#{linkback}=\#\@oid \#\{extrasql\}", #{klass}) end } end end end # module class Module # :nodoc: all include N::OgMetaLanguage end