Sha256: 3054d36ff4357940b61ece2136a3d6f76bbd7adc9bcdba7ef2b10d2cb06568fa

Contents?: true

Size: 1012 Bytes

Versions: 2

Compression:

Stored size: 1012 Bytes

Contents

# frozen_string_literal: true

require 'active_support'

module Influxer
  # Add `has_metrics` method to AR::Base
  module Model
    extend ActiveSupport::Concern

    module ClassMethods # :nodoc:
      # rubocop:disable Style/PredicateName
      # rubocop:disable Metrics/MethodLength
      # rubocop:disable Metrics/AbcSize
      def has_metrics(*args, **params)
        metrics_name = args.empty? ? "metrics" : args.first.to_s

        klass = params[:class_name].present? ? params[:class_name] : "#{self}Metrics"
        klass = klass.constantize

        attrs = params[:inherits] if params[:inherits].present?

        foreign_key = params.fetch(:foreign_key, to_s.foreign_key)

        define_method(metrics_name) do
          rel_attrs = foreign_key ? { foreign_key => id } : {}

          unless attrs.nil?
            attrs.each do |key|
              rel_attrs[key] = send(key)
            end
          end
          Relation.new klass, attributes: rel_attrs
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
influxer-1.1.1 lib/influxer/model.rb
influxer-1.1.0 lib/influxer/model.rb