Sha256: 8b2916056bced70b00f71a018479aaf7f34a9f0cee91c2ddcc09386111960abc

Contents?: true

Size: 1.55 KB

Versions: 2

Compression:

Stored size: 1.55 KB

Contents

module LatoBlog
  class Api::CategoriesController < Api::ApiController

    def index
      categories = LatoBlog::Category.all

      # order categories
      order = (params[:order] && params[:order] == 'ASC') ? 'ASC' : 'DESC'
      categories = categories.order("title #{order}")

      # filter language
      categories = categories.where(meta_language: params[:language]) if params[:language]
      # filter search
      categories = categories.where('title like ?', "%#{params[:search]}%") if params[:search]

      # save total categories
      total = categories.length

      # manage pagination
      page = params[:page] ? params[:page].to_i : 1
      per_page = params[:per_page] ? params[:per_page].to_i : 20
      categories = core__paginate_array(categories, per_page, page)

      # render response
      core__send_request_success(
        categories: (categories && !categories.empty?) ? categories.map(&:serialize) : [],
        page: page,
        per_page: per_page,
        order: order,
        total: total
      )
    end

    def show
      # check parameters
      core__send_request_fail('Uncorrect parameters') && return unless params[:id] || params[:permalink]

      # find post
      if params[:id]
        category = LatoBlog::Category.find_by(id: params[:id].to_i)
      else
        category = LatoBlog::Category.find_by(meta_permalink: params[:permalink])
      end

      # render respnse
      core__send_request_fail('Category not found') && return unless category
      core__send_request_success(category: category.serialize)
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lato_blog-2.1.1 app/controllers/lato_blog/api/categories_controller.rb
lato_blog-2.1 app/controllers/lato_blog/api/categories_controller.rb