Skip to content

Instantly share code, notes, and snippets.

@kwando
Created May 29, 2015 07:46
Show Gist options
  • Save kwando/0f75729ece0fe4e20c14 to your computer and use it in GitHub Desktop.
Save kwando/0f75729ece0fe4e20c14 to your computer and use it in GitHub Desktop.
Virtus + AM::Validations
class ApprovalsController < ApplicationController
def index
query = ApprovalQuery.new(params)
return render(json: {errors: query.errors.full_messages}, status: 422) unless query.valid?
render json: Approval.apply_query(query)
end
end
class ApprovalQuery < Query::Base
include Query::Paging
attribute :customer_id, Integer
attribute :incident_id, Integer
attribute :filter, String, default: 'all'
attribute :state, String, default: 'none'
validates :filter, inclusion: %w(pending all unhandled)
validates :state, inclusion: %w(none approved rejected postponed)
end
module Query
class Base
include ActiveModel::Model
include Virtus.model
end
end
module Query
module Paging
extend ActiveSupport::Concern
included do
attribute :page, Integer, default: 1
attribute :per_page, Integer, default: proc{ default_page_size }
validates :page, numericality: {greater_than: 0}
validates :per_page, numericality: {greater_than: 0, less_than_or_equal_to: 100}
end
def offset
(page - 1) * per_page
end
def apply(query)
query.limit(per_page).offset(offset)
end
module ClassMethods
def default_page_size
30
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment