Module: Hippo::API::FormattedReply

Included in:
ControllerBase
Defined in:
lib/hippo/api/formatted_reply.rb

Instance Method Summary collapse

Instance Method Details

#json_status_str(record, type, success) ⇒ Object


47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/hippo/api/formatted_reply.rb', line 47

def json_status_str(record, type, success)
    if success
        type + " succeeded"
    elsif record
        msg = type + " failed"
        if record.is_a?(ActiveRecord::Base)
            msg += ": " + record.errors.full_messages.join("; ")
        end
    else
        return "Record not found"
    end
end

#record_active_record_errors(model, json = {}) ⇒ Object


27
28
29
30
31
32
33
34
35
# File 'lib/hippo/api/formatted_reply.rb', line 27

def record_active_record_errors(model, json = {})
    return if model.errors.none?
    json[:success] = false
    json[:errors] ||= {}
    model.errors.each{ | attr, message |
        json[:errors][attr] = message
    }
    json
end

#records_for_reply(data, type, options) ⇒ Object


38
39
40
41
42
43
44
45
# File 'lib/hippo/api/formatted_reply.rb', line 38

def records_for_reply(data, type, options)
    return [] if :destroy == type
    if options[:format] == 'array'
        data.pluck(*requested_fields)
    else
        data.as_json(options)
    end
end

#std_api_reply(type, data, options = {}) ⇒ Object

json methods constructs a Hash with success, messages, and data keys and populates them appropriately


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/hippo/api/formatted_reply.rb', line 8

def std_api_reply(type, data, options = {})
    json = {
        success: options[:success].nil? ? true : options[:success],
    }
    json[:errors] = options[:errors] if options[:errors]

    if data.is_a?(ActiveRecord::Base)
        record_active_record_errors(data, json)
    end
    if options[:total_count]
        json[:total] = options.delete(:total_count)
    end
    json.merge(
        message: options[:message] || json_status_str(data, type.to_s.capitalize, json[:success]),

        data: json[:success] ? records_for_reply(data, type, options) : []
    )
end