Sha256: 5caa1b1742ea7ba7045f366e4bdefd8b8e3af9d38bc69e6438c3723a9eb9e0e3

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

require 'json'

module Mks
  module Common
    class MethodResponse
      attr_accessor :success, :message, :data, :errors, :total

      def initialize(success = nil, message = nil, data = nil, errors = [], total = nil)
        @success = success
        @message = message
        @data = data
        @errors = errors
        @total = total
      end

      def self.success_response(data, msg = nil)
        names = %w(ActiveRecord::Relation ActiveRecord::Associations::CollectionProxy)
        return MethodResponse.new(true, msg, nil, nil, nil) if data.nil?
        if data.kind_of?(Array) || names.include?(data.class.name)
          return MethodResponse.new(true, msg, [], nil, nil) if data.count.zero?
          return MethodResponse.new(true, msg, data[0].json(data), nil, data.count)
        else
          return MethodResponse.new(true, msg, data.json, nil, nil)
        end
      end

      def self.error_response(data)
        errors = data.is_a?(String) ? data : data.errors
        return MethodResponse.new(false,nil, nil, errors, nil)
      end

      def self.failure_response(data)
        data.errors.details
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mks_common-1.0.9 lib/mks/common/methodresponse.rb