./lib/joshua/response.rb in joshua-0.2.2 vs ./lib/joshua/response.rb in joshua-0.2.4

- old
+ new

@@ -1,9 +1,19 @@ # Api response is constructed from this object class Joshua class Response + attr_reader :errors + + def self.auto_format error + response = new nil + response.error error.message, code: error.is_a?(Joshua::Error) ? 400 : 500 + response.render + end + + ### + def initialize api @api = api @out = {} @meta = {} @errors = {} @@ -21,12 +31,16 @@ @api.rack_response.header end end # human readable response message - def message value - @message = value + def message value, force=false + if force + @message = value + else + @message ||= value + end end # api meta response, any data is allowed def meta key, value = nil if value @@ -35,18 +49,23 @@ @meta[key] end end # add api response error - def error *args - return @errors unless args[0] + def error text, args={} + code = args.delete(:code) + status = args.delete(:status) - desc, code = args.reverse + raise 'Key %s is not supported' % args.keys.first if args.keys.first - @errors[:code] = code if code + @status ||= status if status + + text = text.to_s + + @errors[:code] ||= code if code @errors[:messages] ||= [] - @errors[:messages].push desc unless @errors[:messages].include?(desc) + @errors[:messages].push text unless @errors[:messages].include?(text) end def error? !!(@errors[:messages] || @errors[:details]) end @@ -56,13 +75,18 @@ @errors[:details] ||= {} @errors[:details][name] = desc end - def data value - @data ||= value + def data value=:_undefind + if value == :_undefind + @data + else + @data = value + end end + alias :data= :data def data? !@data.nil? end @@ -77,10 +101,10 @@ end out[:meta] = @meta out[:message] = @message if @message out[:data] = @data unless @data.nil? - out[:status] = error? ? 400 : 200 + out[:status] = @status || (error? ? 400 : 200) end end end end