Module: APIResourceSortable::HelperMethods

Defined in:
app/api/concerns/api_resource_sortable.rb

Instance Method Summary collapse

Instance Method Details

#sortObject

Helper to get the sort data


69
70
71
# File 'app/api/concerns/api_resource_sortable.rb', line 69

def sort
  @sort
end

#sortable(default_order: {}) ⇒ Object

Gets the `sort` parameter with the format 'resourses?sort=-created_at,name', verify and converts it into an safe Hash that can be passed into the .order method.

Params:

default_order

Hash the default value to return if the sort parameter is not provided


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'app/api/concerns/api_resource_sortable.rb', line 46

def sortable(default_order: {})
  # get the parameter
  sort_by = params[:sort] || params[:sort_by]

  if sort_by.is_a? String    # split it

    sort_by_attrs = sort_by.gsub(/[^a-zA-Z0-9\-_,]/, '').split(',')

    # save it
    @sort = {}
    sort_by_attrs.each do |attrb|
      if attrb.match(/^-/)
        @sort[attrb.gsub(/^-/, '')] = :desc
      else
        @sort[attrb] = :asc
      end
    end
  else
    @sort = default_order
  end
end