Sha256: aac08369a3b199f945d1273d7101d859d03661b797f31872bf4f86d4c2c407ea

Contents?: true

Size: 1.49 KB

Versions: 6

Compression:

Stored size: 1.49 KB

Contents

class Lux::Api::Response
  def self.error text
    response = new
    response.error text
    response.render
  end

  ###

  attr_accessor :data
  attr_accessor :message

  def initialize
    @meta = {}.h_wia
  end

  def status num=nil
    meta 'http_status', num.to_i if num && !@meta['http_status']
    @meta['http_status']
  end

  def meta key, value
    value = value.to_i if key == :status
    @meta[key.to_s] = value
  end

  def error key, data=nil
    unless data
      data = key
      key  = :base
    end

    key = key.to_s

    @errors ||= {}
    @errors[key] ||= []
    @errors[key].push data unless @errors[key].include?(data)
  end

  def errors?
    !!@errors
  end

  def message what
    @message = what
  end

  def redirect url
    @meta['location'] = url
  end

  def event name, opts={}
    @meta['event'] ||= []
    @meta['event'].push([name, opts])
  end

  def render
    output = {}

    if @errors
      status 400

      errors = @errors.inject({}) { |t, (k, v)| t[k] = v.join(', '); t }
      base   = errors.values.uniq

      errors.delete('base')

      output[:error]          ||= {}
      output[:error][:messages] = base
      output[:error][:hash]     = errors if errors.keys.first
    end

    output[:data]    = @data    if @data.present?
    output[:meta]    = @meta    if @meta.present?
    output[:message] = @message if @message.present?

    output
  end
  alias :to_hash :render

  def write
    Lux.current.response.status status
    Lux.current.response.body render
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
lux-fw-0.5.37 ./plugins/api/lib/response.rb
lux-fw-0.5.36 ./plugins/api/lib/response.rb
lux-fw-0.5.35 ./plugins/api/lib/response.rb
lux-fw-0.5.34 ./plugins/api/lib/response.rb
lux-fw-0.5.33 ./plugins/api/lib/response.rb
lux-fw-0.5.32 ./plugins/api/lib/response.rb