Sha256: d3fa69f6044faa19e0f54d61adf5b166dd88c29db5fc998c7dfc5336629d9b5f

Contents?: true

Size: 1.61 KB

Versions: 6

Compression:

Stored size: 1.61 KB

Contents

module Light
  module Decorator
    module Concerns
      module Relation
        extend ActiveSupport::Concern

        # Decorate ActiveRecord::Relation
        #
        # @param [Hash] options
        # @return [ActiveRecord::Relation] decorated collection
        def decorate(options = {})
          @decorated = true

          override_exec_queries(options)

          self
        end

        # Check current ActiveRecord::Relation is decorated or not
        #
        # @return [Bool]
        def decorated?
          !@decorated.nil?
        end

        private

        def override_exec_queries(options)
          define_singleton_method :exec_queries do
            super()

            @records = @records.map do |record|
              decorate_associations(record, options.reverse_merge(soft: true))
              record.decorate(options)
            end
          end
        end

        def decorate_associations(record, options)
          record.instance_variable_get(:@association_cache).each do |_, association|
            next if association.inversed || association.target.blank?

            if association.target.is_a?(Array)
              targets = association.target.map do |target|
                decorate_associations(target, options)
                target.decorate(options)
              end

              association.instance_variable_set(:@target, targets)
            else
              decorate_associations(association.target, options)
              association.instance_variable_set(:@target, association.target.decorate(options))
            end
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
light-decorator-1.0.1 lib/light/decorator/concerns/relation.rb
light-decorator-1.0.0 lib/light/decorator/concerns/relation.rb
light-decorator-0.5.3 lib/light/decorator/concerns/relation.rb
light-decorator-0.5.2 lib/light/decorator/concerns/relation.rb
light-decorator-0.5.1 lib/light/decorator/concerns/relation.rb
light-decorator-0.5.0 lib/light/decorator/concerns/relation.rb