Sha256: cb85ead4a1380a432d7586fa837d82d16c35dc487e379a22f5536b69c4d47ff1

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

module MakeRestful::Loaders

  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 = 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

    if @collection.empty?
      @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 = if finder && @resource.respond_to?(:where)
       @resource.where(finder.to_sym => finder_value).first
    else
       @resource.find(finder_value)
    end
    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

  alias :verify_action! :verify_method!

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
make_restful-0.1.4 lib/make_restful/loaders.rb