Sha256: ebda11dac5267992fd95906724fe65a28a13b8e5f4bfb9169493e5f43094ce6c

Contents?: true

Size: 1.54 KB

Versions: 4

Compression:

Stored size: 1.54 KB

Contents

class RestModel
  class Embeddable
    module Sender
      def to_source!(value, resource, options = {})
        return {} if value.nil?

        fields ? to_multiple_source(value, options)
               : to_single_source(value, options)
      end

      private

      def to_single_source(value, options)
        source = {}
        path = source_path

        if path.any?
          last = path.pop
          key_source = path.inject(source) {|buffer, key| buffer[key] = {}; buffer[key]}
          key_source[last] = raw? ? value
                                  : one? ? embeds_one_source(value, options)
                                         : embeds_many_source(value, options)
        else
          source.merge!(value.to_source!(options))
        end

        source
      end

      def to_multiple_source(value, options)
        input = {}
        mapped_fields = convert_input_keys.call(fields)

        value.each_with_index do |item, index|
          input[mapped_fields[index]] = item
        end

        input
      end

      def embeds_one_source(value, options)
        value.to_source!(options)
      end

      def embeds_many_source(value, options)
        errors = {}

        source = value.each_with_index.map do |item, index|
          begin
            item.to_source!(options)
          rescue RestModel::SourceError => e
            errors[self.name] ||= {}
            errors[self.name][index] = e.message
          end
        end

        fail RestModel::SourceError, errors unless errors.empty?

        source
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rest_model-0.3.1 lib/rest_model/key/embeddable/sender.rb
rest_model-0.3.0 lib/rest_model/key/embeddable/sender.rb
rest_model-0.2.3 lib/rest_model/key/embeddable/sender.rb
rest_model-0.2.1 lib/rest_model/key/embeddable/sender.rb