lib/ably/modules/model_common.rb in ably-0.8.15 vs lib/ably/modules/model_common.rb in ably-1.0.0

- old
+ new

@@ -6,10 +6,14 @@ # Common model functionality shared across many {Ably::Models} module ModelCommon include Conversions include MessagePack + def self.included(base) + base.extend(ClassMethods) + end + # Provide a normal Hash accessor to the underlying raw message object # # @return [Object] def [](key) attributes[key] @@ -30,41 +34,29 @@ # @return [String] def to_json(*args) as_json.to_json(*args) end - # Like to_json but encodes all binary fields to hex - def to_safe_json(*args) - as_json. - each_with_object({}) do |(key, val), obj| - obj[key] = to_safe_jsonable_val(val) - end.to_json(*args) - end - # @!attribute [r] hash # @return [Integer] Compute a hash-code for this hash. Two hashes with the same content will have the same hash code def hash attributes.hash end - private - def to_safe_jsonable_val(val) - case val - when Array - val.map { |array_val| to_safe_jsonable_val(array_val) } - when Hash - val.each_with_object({}) { |(key, hash_val), obj| obj[key] = to_safe_jsonable_val(hash_val) } - when String - if val.encoding == Encoding::ASCII_8BIT - val.unpack("H*").first + module ClassMethods + # Return a new instance of this object using the provided JSON-like object or JSON string + # @param [Hash, String] JSON-like object or JSON string + # @return a new instance o this object + def from_json(json_like_object) + if json_like_object.kind_of?(String) + new(JSON.parse(json_like_object)) else - val + new(json_like_object) end - else - val end end + private def ensure_utf8_string_for(attribute, value) if value raise ArgumentError, "#{attribute} must be a String" unless value.kind_of?(String) raise ArgumentError, "#{attribute} cannot use ASCII_8BIT encoding, please use UTF_8 encoding" unless value.encoding == Encoding::UTF_8 end