Sha256: 7512f10da2e84042c9ffb85a5bb2551eea0769dffecbb9e6927160d8ece9724c

Contents?: true

Size: 1.6 KB

Versions: 2

Compression:

Stored size: 1.6 KB

Contents

# frozen_string_literal: true

module Cookbook
  module Mixins
    # ActsAsUseIn Mixin, for things like Recipes or HowTos
    module ActsAsUseOf
      extend ActiveSupport::Concern

      def acts_as_use_of(*model_symbols)
        extend ClassMethods
        include InstanceMethods

        self.used_in = model_symbols

        # Relationships
        has_many :uses, as: :use_in, class_name: 'Cookbook::Use'
        associate_used_in
      end

      # Extended by has_cookbook mixin
      module ClassMethods
        attr_accessor(:used_in)

        def associate_used_in
          tables = used_in
          tables.each do |table_sym|
            model = table_sym.to_s.classify.constantize
            name = model.model_name.to_s
            uses_symbol = "#{model.model_name.param_key}_uses".to_sym

            has_many uses_symbol, lambda {
              where(use_of_type: name)
            }, as: :use_in, class_name: 'Cookbook::Use'
            accepts_nested_attributes_for uses_symbol, reject_if: :all_blank, allow_destroy: true

            has_many table_sym, through: :uses, source: :use_of, source_type: name

            if defined?(RailsAdmin)
              rails_admin do
                field :uses do
                  visible false
                end
                tables.each do |table_sym|
                  field table_sym do # We don't want these associations to show
                    visible false
                  end
                end
              end
            end
          end
        end
      end

      # Included by has_cookbook mixin
      module InstanceMethods
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cookbook-0.1.2 lib/cookbook/mixins/acts_as_use_of.rb
cookbook-0.1.1 lib/cookbook/mixins/acts_as_use_of.rb