lib/plaza/models/restful_model.rb in plaza-0.0.4 vs lib/plaza/models/restful_model.rb in plaza-0.1.0
- old
+ new
@@ -57,23 +57,38 @@
# Class Configuration
#
def has_many(*relations)
relations.each do |r|
- define_method(r) do
- class_name = Plaza::Inflector.classify(r.to_s)
- Plaza.const_get(class_name).collection(adapter.has_many(self.id,r))
+ define_method(sym = has_many_symbol_for(r)) do
+ class_for(r).collection(adapter.has_many(self.id,sym))
end
end
end
def plaza_config(config = nil)
@plaza_config ||= :default
config ? @plaza_config = config : @plaza_config
end
alias_method :plaza_config=, :plaza_config
+
+ private
+
+ def has_many_symbol_for(identifier)
+ if identifier.kind_of? Class
+ identifier.plural_name
+ elsif identifier.kind_of? String
+ Inflector.tableize(identifier.split('::').last)
+ elsif identifier.kind_of? Symbol
+ identifier
+ else
+ raise TypeError.new("Can't convert to has_many symbol")
+ end
+ end
+
+
end
def plaza_config
self.class.plaza_config
end
@@ -130,9 +145,23 @@
obj_id = self.send(method_name + '_id')
class_name = Plaza::Inflector.classify(method_name)
return Plaza.const_get(class_name).find(obj_id)
else
raise NoMethodError.new "undefined method '#{method_name}' for #{self.class}"
+ end
+ end
+
+ protected
+
+ def class_for(identifier)
+ if identifier.kind_of?(Symbol)
+ klass = Plaza.const_get(Plaza::Inflector.classify(identifier.to_s))
+ elsif identifier.kind_of?(String)
+ klass = Object.const_get(identifier)
+ elsif identifier.kind_of?(Class)
+ klass = identifier
+ else
+ raise TypeError.new("Can't convert to has_many relation")
end
end
end
end