Class: Backframe::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/backframe/response.rb,
lib/backframe/response/fields.rb,
lib/backframe/response/record.rb,
lib/backframe/response/collection.rb,
lib/backframe/response/adapter/csv.rb,
lib/backframe/response/adapter/xml.rb,
lib/backframe/response/adapter/json.rb,
lib/backframe/response/adapter/xlsx.rb

Defined Under Namespace

Modules: Adapter Classes: Collection, Fields, Record

Constant Summary collapse

FIELDS_REGEX =
/^[A-Za-z0-9\_,]*$/
PAGE_REGEX =
/^[0-9]*$/

Class Method Summary collapse

Class Method Details

.failure(message, status) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/backframe/response.rb', line 43

def failure(message, status)
  {
    json: {
      error: {
        message: message,
        status: status
      }
    },
    content_type: 'application/json',
    status: status
  }
end

.render(records, params = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/backframe/response.rb', line 12

def render(records, params = {})
  begin
    fields = Backframe::Response::Fields.new(records, params[:fields])
    collection = Backframe::Response::Collection.new(records, params[:page], params[:per_page])
    if params[:format] == 'json'
      data = Backframe::Response::Adapter::Json.render(collection, fields)
      success(json: data, content_type: 'application/json')
    elsif params[:format] == 'xml'
      data = Backframe::Response::Adapter::Xml.render(collection, fields)
      success(xml: data, content_type: 'application/xhtml+xml')
    elsif params[:format] == 'csv'
      data = Backframe::Response::Adapter::Csv.render(collection, fields, ",")
      success(text: data, content_type: 'text/plain')
    elsif params[:format] == 'tsv'
      data = Backframe::Response::Adapter::Csv.render(collection, fields, "\t")
      success(text: data, content_type: 'text/plain')
    elsif params[:format] == 'xlsx'
      data = Backframe::Response::Adapter::Xlsx.render(collection, fields)
      success(text: data, content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    else
      failure('Unknown Format', 404)
    end
  rescue Exception => e
    failure('Application Error', 500)
  end
end

.success(*response) ⇒ Object



39
40
41
# File 'lib/backframe/response.rb', line 39

def success(*response)
  response[0].merge(status: 200)
end