module FirstResponder::InstanceMethods
Public Class Methods
new(fmt=nil, data)
click to toggle source
Every instance must instantiate itself with a format and corresponding data. Given that information, formats are validated, data is parsed using that format, after which the attributes defined on the class are set to the hash value at the defined location.
# File lib/first_responder.rb, line 19 def initialize(fmt=nil, data) @format = ensure_format(fmt) if fmt @data = data.is_a?(Hash) ? data : deserialize(data, fmt) map_attrs end
Public Instance Methods
invalid?(execute=true)
click to toggle source
# File lib/first_responder.rb, line 31 def invalid?(execute=true) !valid?(execute) end
valid?(execute=true)
click to toggle source
Calls superclass method
# File lib/first_responder.rb, line 25 def valid?(execute=true) return true if all_attributes_valid? proc_on_invalid.call(@data, errors) if execute return no_nesting? ? super : false end
Private Instance Methods
all_attributes_valid?()
click to toggle source
# File lib/first_responder.rb, line 53 def all_attributes_valid? nested_validations.any? && nested_validations.all? { |attr| eval("#{attr}.valid?") } end
deserialize(data, format)
click to toggle source
# File lib/first_responder.rb, line 70 def deserialize(data, format) raise MissingDataError if data == '' return JSON.parse(data) if format == :json Hash.from_xml(data) if format == :xml end
ensure_format(fmt)
click to toggle source
# File lib/first_responder.rb, line 49 def ensure_format(fmt) raise UnknownFormatError unless VALID_FORMATS.include?(fmt) end
extract_attribute_value(attr_hash, attr)
click to toggle source
Currently have to use eval to access @data at nested array object attr_hash is String at this point: “[‘foo’][‘baz’]”
# File lib/first_responder.rb, line 80 def extract_attribute_value(attr_hash, attr) return @data if @data.is_a?(Array) attr_location = (attr_hash[attr] || "['#{attr.to_s}']") hash_location = self.class.first_responder_root + attr_location eval("@data.with_indifferent_access#{hash_location}") end
map_attrs()
click to toggle source
# File lib/first_responder.rb, line 41 def map_attrs required_attributes.each do |attr_hash| attr = attr_hash.keys.first value = extract_attribute_value(attr_hash, attr) send("#{attr}=", value) end end
nested_validations()
click to toggle source
# File lib/first_responder.rb, line 62 def nested_validations self.class.nested_validations end
no_nesting?()
click to toggle source
# File lib/first_responder.rb, line 37 def no_nesting? nested_validations.empty? end
proc_on_invalid()
click to toggle source
# File lib/first_responder.rb, line 66 def proc_on_invalid self.class.proc_on_invalid || Proc.new {} end
required_attributes()
click to toggle source
# File lib/first_responder.rb, line 58 def required_attributes self.class.required_attributes end