lib/traxis/controller_helpers.rb in traxis-0.0.1 vs lib/traxis/controller_helpers.rb in traxis-0.0.2
- old
+ new
@@ -1,11 +1,17 @@
module Traxis
module ControllerHelpers
protected
def association_chain
- @association_chain ||= begin_of_association_chain.all
+ @association_chain ||= begin
+ if begin_of_association_chain.kind_of?(::ActiveRecord::Relation)
+ begin_of_association_chain.all
+ else
+ begin_of_association_chain
+ end
+ end
end
def assign_object_attributes(object, attribute_hash)
attribute_hash.each_pair do |k,v|
object.__send__("#{k}=", v)
@@ -16,22 +22,51 @@
def begin_of_association_chain
self.class.resource_options[:class]
end
+ def build_resource
+ if association_chain != resource_class
+ association_chain.__send__(collection_relation_name).new(payload_attributes)
+ else
+ association_chain.new(payload_attributes)
+ end
+ end
+
+
+ ### If begin of association chain is an instance of ar model, i.e. current_user
+ ### send the collection relation name, i.e. current_user.posts.all
def collection
- @collection ||= association_chain
+ @collection ||= begin
+ unless begin_of_association_chain.respond_to?(:all)
+ association_chain.__send__(collection_relation_name).all
+ else
+ association_chain.all
+ end
+ end
end
+ def collection_relation_name
+ @collection_relation_name ||= resource_class.name.demodulize.underscore.pluralize
+ end
+
def collection_serializer_class
collection_options[:serializer]
end
def create_resource
save_resource
end
+ def end_of_association_chain
+ :all
+ end
+
+ def method_for_find
+ resource_options[:finder]
+ end
+
def params
@params ||= request.params.attributes
end
def payload_attributes
@@ -43,25 +78,28 @@
end
def resource
@resource ||= begin
if request.action.name == :create
- association_chain.new(payload_attributes)
+ build_resource
elsif request.action.name == :update
assign_object_attributes(resource_query_result, payload_attributes)
else
- association_chain.__send__(resource_options[:finder], params[resource_options[:finder_param]])
+ resource_query_result
end
end
end
- def resource_finder
- :find
- end
-
def resource_query_result
- @resource_query_result ||= association_chain.__send__(resource_options[:finder], params[resource_options[:finder_param]])
+ @resource_query_result ||= begin
+ unless association_chain.respond_to?(method_for_find)
+ association_chain.__send__(collection_relation_name)
+ .__send__(method_for_find, params[resource_options[:finder_param]])
+ else
+ association_chain.__send__(method_for_find, params[resource_options[:finder_param]])
+ end
+ end
end
def serialized_collection
collection_serializer_class.new(scoped_collection)
end
@@ -79,9 +117,11 @@
return collection if request.query.blank?
request.query.map do |k,v|
collection.__send__("#{k}", *v)
end
+
+ collection.__send__(end_of_association_chain)
end
end
def save_resource
resource.save