Skip to content

Instantly share code, notes, and snippets.

@arieliten
Created December 19, 2014 20:34
Show Gist options
  • Save arieliten/51a3d752645bb08e2267 to your computer and use it in GitHub Desktop.
Save arieliten/51a3d752645bb08e2267 to your computer and use it in GitHub Desktop.
Basic structure to build API endpoint for pd_resources (search)
# app/models/pd_resource.rb
class PdResource < ActiveRecord::Base
# ...
SORT_OPTIONS = [:alpha, :popular]
SORT_CLAUSES = {
alpha: "pd_resources.title ASC",
popular: "pd_resources.views DESC",
}
#...
end
# app/controllers/api/v1/pd_resources_controller.rb
class Api::V1::PdResourcesController < ApplicationController
# GET "/api/v1/pd_resources"
#
# Params supported as query string:
# + query: free text used as the search string to query Elastic Search.
# + pd_type[]: array of pd type's ids to filter pd_resources by pd type.
# + language[]: array of language's ids to filter pd_resources by language.
# + age_level[]: array of age_level's ids to filter pd_resources by age_level.
# + domain[]: array of domain's ids to filter pd_resources by domain.
# + dimension[]: array of dimension's ids to filter pd_resources by dimension.
# + sort_by: string that defines how results should be sorted: ['alpha', 'popular']. Defaults: 'alpha'
# + page: page number used for pagination. Default: 1.
# + per_page: number of items returned on each page. Default: 25.
#
def index
filter = build_es_filter(params)
sorting = calculate_sorting(params[:sort_by])
page = params[:page] || 1
per_page = params[:page] || 25
@pd_resources = PdResource.search(filter)
@pd_resources.order(order).page(page).per_page(per_page)
end
private
def build_es_filter(params)
# TODO: logic to create the filter hash needed by Elastic Search
# taking in count the following params:
# => params[query]
# => params[pd_type]
# => params[language]
# => params[age_level]
# => params[domain]
# => params[dimension]
end
def calculate_sorting_clause(sort_str)
sort_option = PdResource::SORT_OPTIONS.include?(sort_str) ? sort_str : PdResource::SORT_OPTIONS.first
PdResource::SORT_CLAUSES[sort_option]
end
end
# app/views/api/v1/pd_resources/index.json.jbuilder
json.partial! 'pd_resource', collection: @pd_resources, as: :pd_resource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment