Skip to content

Instantly share code, notes, and snippets.

@tatat
Created October 13, 2012 10:24
Show Gist options
  • Save tatat/3884074 to your computer and use it in GitHub Desktop.
Save tatat/3884074 to your computer and use it in GitHub Desktop.
for responding with JSON
module Result
::R = ::Result
def self.create(result = nil, error = nil, code = 0)
Data.new(result, error, code)
end
def self.create_error(error = nil, code = 1)
Data.new(nil, error, code)
end
class Data
attr_accessor :result, :error, :code
def initialize(result = nil, error = nil, code = 0)
@result = result
@error = error
@code = code
end
def error(message = nil, code = 1, reset = false)
if message.nil?
@error
else
@result = nil if reset
@error = message
@code = code
end
end
def <<(value)
if value.is_a?(Hash)
@result = {} unless @result.is_a?(Hash)
@result.merge! value
else
@result = value
end
self
end
def []=(key, value)
@result = {} if @result.nil?
@result[key] = value;
end
def [](key)
@result = {} if @result.nil?
@result[key]
end
def set(key, value)
instance_variable_set to_instance_variable_symbol(key), value
end
def get(key)
key = to_instance_variable_symbol key
instance_variable_defined?(key) ? instance_variable_get(key) : nil
end
def to_hash
Hash[instance_variables.map {|variable|
[variable.to_s[1..-1].to_sym, instance_variable_get(variable)]
}]
end
protected
def to_instance_variable_symbol(value)
value = value.to_s if value.is_a?(Symbol)
'@'.concat(value).to_sym
end
end
class HTTPError < StandardError
attr_accessor :data, :status
def initialize(status = 500, message = nil, data = nil)
super message
@status = status
if data.nil?
@data = R.create_error(message)
elsif data.is_a?(Data)
@data = data
@data.error = message if not message.nil? and @data.error.nil?
else
@data = R.create(data, message, 1)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment