Sha256: 6f6d657ebdb60d0376afc38991e6874ffc449cc40726e66630cbebec90aa506f

Contents?: true

Size: 1.2 KB

Versions: 1

Compression:

Stored size: 1.2 KB

Contents

module ActsAsBelongable
    module Belongable

        extend ActiveSupport::Concern

        module ClassMethods
            def acts_as_belongable
                has_many :belongers, through: :belongable_belongings, source: :belonger
                has_many :belongable_belongings, as: :belongable, class_name: 'Belonging', dependent: :destroy
            end

            def belongable name, source_type
                has_many name.to_sym, through: :belongable_belongings, source: :belonger, source_type: source_type.to_s
            end
        end

        def add_to_belonger belonger, options = {}
            options[:belonger] = belonger
            self.belongable_belongings.create options
        end
        def add_to_belonger! belonger, options = {}
            options[:belonger] = belonger
            self.belongable_belongings.create! options
        end

        def create_belonger class_name, options = {}
            object = class_name.constantize.create options
            self.add_to_belonger object
        end
        def create_belonger! class_name, options = {}
            object = class_name.constantize.create! options
            self.add_to_belonger! object
        end

    end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
acts_as_belongable-1.0.0 app/models/concerns/acts_as_belongable/belongable.rb