Module: Lanes::API::FormattedReply

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

Instance Method Summary collapse

Instance Method Details

#json_status_str(record, type, success) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/lanes/api/formatted_reply.rb', line 42

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



22
23
24
25
26
27
28
29
30
# File 'lib/lanes/api/formatted_reply.rb', line 22

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



33
34
35
36
37
38
39
40
# File 'lib/lanes/api/formatted_reply.rb', line 33

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
# File 'lib/lanes/api/formatted_reply.rb', line 8

def std_api_reply(type, data, options = {})
    json = { success: options[:success].nil? ? true : options[:success] }
    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[:messsage] || json_status_str(data, type.to_s.capitalize, json[:success]),
      data: json[:success] ? records_for_reply(data, type, options) : []
    )
end