Sha256: 8505975677cd845b37bc43b14aabe6dce24492da9be67606a457d7ba760d0bfd

Contents?: true

Size: 896 Bytes

Versions: 1

Compression:

Stored size: 896 Bytes

Contents

require 'active_support'

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

    module ClassMethods # :nodoc:
      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 = nil

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

        foreign_key = params.key?(:foreign_key) ? params[: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

1 entries across 1 versions & 1 rubygems

Version Path
influxer-0.2.4 lib/influxer/model.rb