Sha256: b538dbd24478d660bad825e0e3824a4c22fc2f83c3dad8868ee11f05d8221235

Contents?: true

Size: 1.68 KB

Versions: 19

Compression:

Stored size: 1.68 KB

Contents

module MotionPrime
  module JSON
    PARAMETRIZE_CLASSES = [Time, Date]
    class ParserError < StandardError; end

    # Parses a string or data object and converts it in data structure.
    #
    # @param [String, NSData] str_data the string or data to convert.
    # @raise [ParserError] If the parsing of the passed string/data isn't valid.
    # @return [Hash, Array, NilClass] the converted data structure, nil if the incoming string isn't valid.
    def self.parse(str_data, &block)
      return nil unless str_data
      data = str_data.respond_to?(:to_data) ? str_data.to_data : str_data
      opts = NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
      error = Pointer.new(:id)
      obj = NSJSONSerialization.JSONObjectWithData(data, options: opts, error: error)
      raise ParserError, error[0].description if error[0]
      if block_given?
        yield obj
      else
        obj
      end
    end

    # Generates a string from data structure.
    #
    # @param [String, Fixnum, Array, Hash, Nil] obj the object to serialize.
    # @param [Boolean] parametrize option to parametrize data before serialization.
    # @return [String] the serialized data json.
    def self.generate(obj, parametrize = true)
      if parametrize && obj.is_a?(Hash)
        obj.each do |key, value|
          obj[key] = value.to_s if PARAMETRIZE_CLASSES.include?(value.class)
        end
      end
      if parametrize && obj.is_a?(Array)
        obj.map! do |value|
          PARAMETRIZE_CLASSES.include?(value.class) ? value.to_s : value
        end
      end
      data = NSJSONSerialization.dataWithJSONObject(obj, options: 0, error: nil)
      data.to_str
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
motion-prime-0.4.5 motion-prime/models/json.rb
motion-prime-0.4.4 motion-prime/models/json.rb
motion-prime-0.4.3 motion-prime/models/json.rb
motion-prime-0.4.2 motion-prime/models/json.rb
motion-prime-0.4.1 motion-prime/models/json.rb
motion-prime-0.4.0 motion-prime/models/json.rb
motion-prime-0.3.3 motion-prime/models/json.rb
motion-prime-0.3.2 motion-prime/models/json.rb
motion-prime-0.3.1 motion-prime/models/json.rb
motion-prime-0.3.0 motion-prime/models/json.rb
motion-prime-0.2.1 motion-prime/models/json.rb
motion-prime-0.2.0 motion-prime/models/json.rb
motion-prime-0.1.7 motion-prime/models/json.rb
motion-prime-0.1.6 motion-prime/models/json.rb
motion-prime-0.1.5 motion-prime/models/json.rb
motion-prime-0.1.4 motion-prime/models/json.rb
motion-prime-0.1.3 motion-prime/models/json.rb
motion-prime-0.1.2 motion-prime/models/json.rb
motion-prime-0.1.1 motion-prime/models/json.rb