module MakeRestful::Loaders extend ActiveSupport::Concern included do before_filter :verify_method! before_filter :verify_format! collection do if pagination && !params.has_key?(:all) paginated_collection = @resource.paginate page: params[:page], per_page: (params[:per_page] || pagination[:per_page] || 25) { resource_name.to_sym => paginated_collection, pagination: { current_page: paginated_collection.current_page, per_page: paginated_collection.per_page, total_entries: paginated_collection.total_entries, total_pages: paginated_collection.total_pages } } else @resource.all end end instance do if finder && @resource.respond_to?(:where) @resource.where(finder.to_sym => finder_value).first else @resource.find(finder_value) end end end private def load_resource if (@resource = resource_class) nested_in_resources = params.select{ |param| /_id$/ =~ param } @resource = @resource.where(nested_in_resources) if nested_in_resources.present? else @response = { error: 'error when loading resource' } @status = :failed_dependency render(load_template: false) and return end end def load_collection @collection = instance_eval(&collection_loader) unless @collection.present? @response = { error: 'no results found' } @status = :not_found render(load_template: false) and return end eval("@#{resource_name} = @collection") end def load_instance(opts={}) finder = opts[:finder] || send(:finder) finder_value = params[finder] @instance = instance_eval(&instance_loader) eval "@#{instance_name} = @instance" unless @instance @response = { error: "Could not find record with #{finder}: #{finder_value}" } @status = :not_found render(load_template: false) and return end end def verify_method! return if allowed_actions.allowed?(params[:action]) || !%w{GET POST PUT PATCH}.include?(request.method) @response = { error: "Method not allowed" } @status = :method_not_allowed render(load_template: false) end def verify_format! return if allowed_formats.allowed?(request.format.symbol) @response = { error: "Format:#{request.format} is unsupported" } @status = :unsupported_media_type render(load_template: false) end alias :verify_action! :verify_method! end