Sha256: 5580a1c2e6877ead8b6fa57f1e975fe1b3f6767c3d28f44945acecb35ef9fa5a

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

require 'active_record'

module Fields
  module Serializer
    module ActiveRecord
      extend ActiveSupport::Concern

      class_methods do
        def fields_to_includes(fields)
          flatten_fields = Array(fields).map { |str| str.to_s.split(",").map(&:strip) }.flatten
          nested_fields  = flatten_fields.map { |field| nested_field(field.split(".")) }.compact
          nested_fields.inject([{}]) do |result, attribute_structure|
            if attribute_structure.is_a?(Hash)
              result.first.deep_merge!(attribute_structure) { |_, u, v| [u, v] } && result
            else
              result << attribute_structure
            end
          end.map(&:presence).compact
        end

        def nested_field(attribute_stack)
          parent = attribute_stack.first
          return unless association?(parent)
          parent_klass = reflections[parent].class_name.constantize
          { parent => parent_klass.nested_field(attribute_stack[1..-1]) }.compact.presence || parent
        end

        private

        def association?(key)
          reflections.keys.include?(key)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fields-serializer-0.1.1 lib/fields/serializer/active_record.rb