Sha256: 67f0eb3528f40978d55a68a6a8bf731197565c15e91263376eadb9aa5ba10d86

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

module FlexibleFeeds
  module PolymorphicJoin
    extend ActiveSupport::Concern

    module ClassMethods
      def polymorphically_joined_through(join_table, params)
        association = params[:association_name]
        singular_association = params[:singular_association_name]
        define_association(join_table, association, singular_association)
        define_include(join_table, association, singular_association)
        define_add(join_table, association, singular_association)
        define_remove(join_table, association, singular_association)
      end

      def define_association(join_table, association, singular_association)
        define_method association do
          send(join_table).collect { |join| join.send(singular_association) }
        end
      end

      def define_include(join_table, association, singular_association)
        define_method "#{association}_include?".to_sym do |instance|
          send(join_table).where(singular_association => instance).exists?
        end
      end

      def define_add(join_table, association, singular_association)
        define_method "add_#{singular_association}".to_sym do |instance|
          result = send(join_table).create(singular_association => instance)
          self.reload()
          result
        end
      end

      def define_remove(join_table, association, singular_association)
        define_method "remove_#{singular_association}".to_sym do |instance|
          return false unless send("#{association}_include?", instance)
          result = send(join_table).
            find_by(singular_association => instance).destroy
          self.reload()
          result
        end
      end
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flexible_feeds-0.2.1 lib/flexible_feeds/polymorphic_join.rb