lib/nephos-server/server/responder.rb in nephos-server-0.1.7 vs lib/nephos-server/server/responder.rb in nephos-server-0.1.8
- old
+ new
@@ -1,29 +1,74 @@
module Nephos
module Responder
- CT_CHARSET_ = '; charset=UTF-8'
- CT_TP = {'Content-type' => 'text/plain' + CT_CHARSET_}
- CT_TJ = {'Content-type' => 'text/javascript' + CT_CHARSET_}
- CT_TH = {'Content-type' => 'text/html' + CT_CHARSET_}
+ class InvalidContentType < StandardError; end
- # @params params [Hash, Symbol]
- def self.render params
- if params == :empty
- return [204, CT_TP, [""]]
- elsif params[:status] == 404
- return [404, CT_TP, ['Error 404 : Not found !']]
- elsif params[:status] == 500
- return [500, CT_TP, ['Error 5OO : Internal Server Error !']]
- elsif params[:status].is_a? Fixnum
- return [params[:status], CT_TP, ["Error #{params[:status]}"]]
- elsif params[:json]
- return [200, CT_TJ, [params[:json].to_json]]
- elsif params[:plain]
- return [200, CT_TJ, [params[:plain].to_s]]
+ CT_CHARSET_PREFIX = '; charset='
+
+ def self.content_type(kind, type, charset='UTF-8')
+ {'Content-type' => "#{kind}/#{type}" + CT_CHARSET_PREFIX + charset}
+ end
+ def self.ct_plain
+ content_type(:text, :plain)
+ end
+ def self.ct_html
+ content_type(:text, :html)
+ end
+ def self.ct_json
+ content_type(:text, :javascript)
+ end
+ # @param params [Hash] containing :type => "kind/type", example: "text/html"
+ def self.ct_specific(params)
+ kind, type = params[:type].match(/^(\w+)\/(\w+)$/)[1..2]
+ if kind.nil? or type.nil?
+ raise InvalidContentType, "params[:type] must match with \"kind/type\""
+ end
+ content_type(kind, type)
+ end
+
+ # Fill params with default parameters (status, plain errors)
+ def self.set_default_params params
+ if (params.keys & [:status]).empty?
+ params[:status] ||= 200
+ end
+ if (params.keys & [:plain, :html, :json, :type]).empty?
+ if params[:status].to_s.match(/^[345]\d\d$/)
+ params[:plain] ||= "Error: #{params[:status]} code"
+ else
+ params[:plain] ||= "ok"
+ end
+ end
+ params
+ end
+
+ # @return [Symbol, nil] :plain, :html, :json, or nil
+ # search the content type
+ def self.params_content_type params
+ (params.keys & [:plain, :html, :json]).first
+ end
+
+ # search the content to render from the params,
+ # based on content_type (plain, html, ...).
+ # If not, check for specific type
+ def self.params_content_type_value params
+ type = params_content_type(params)
+ if type
+ self.send("ct_#{type}")
else
- render(:empty)
+ self.send("ct_specific", params)
end
+ end
+
+ # @param params [Hash, Symbol]
+ def self.render params
+ return [204, plain(), [""]] if params == :empty
+ params = set_default_params(params)
+ return [
+ params[:status],
+ params_content_type_value(params),
+ [params[params_content_type(params) || :content]],
+ ]
end
end
end