Sha256: 6338bd2164a66f0cc2823e768647e8e6e5cd5be6762c45b72d4fa85be66574c2

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

# Poly Belongs To
# The MIT License (MIT)
# Copyright (C) 2015 by Daniel P. Clark
$: << File.join(File.dirname(__FILE__), "/poly_belongs_to")
require 'poly_belongs_to/version'
require 'active_support/concern'

module PolyBelongsTo
  extend ActiveSupport::Concern

  included do
    def self.pbt
      reflect_on_all_associations(:belongs_to).first.try(:name)
    end
    
    def self.poly?
      !!reflect_on_all_associations(:belongs_to).first.try {|i| i.options[:polymorphic] }
    end

    def self.pbt_params_name
      if poly?
        "#{table_name}_attributes".to_sym
      else
        name.downcase.to_sym
      end
    end

    def self.pbt_id_sym
      val = pbt
      val ? "#{pbt}_id".to_sym : nil
    end

    def self.pbt_type_sym
      val = pbt
      val ? "#{pbt}_type".to_sym : nil
    end
  end
  
  def pbt
    self.class.pbt
  end

  def poly?
    self.class.poly?
  end

  def pbt_id
    val = pbt
    val ? eval("self.#{val}_id") : nil
  end

  def pbt_type
    val = pbt
    val ? eval("self.#{val}_type") : nil
  end

  def pbt_id_sym
    self.class.pbt_id_sym
  end

  def pbt_type_sym
    self.class.pbt_type_sym
  end

  def pbt_params_name
    self.class.pbt_params_name
  end
end

ActiveRecord::Base.send(:include, PolyBelongsTo)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
poly_belongs_to-0.1.1 lib/poly_belongs_to.rb