Module: ActsInRelation::Source

Defined in:
lib/acts_in_relation/source.rb

Instance Method Summary collapse

Instance Method Details

#defineObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/acts_in_relation/source.rb', line 3

def define
  with.each do |action|
    action.extend ActsInRelation::Supports::Verb

    class_object.class_eval <<-RUBY
      has_many :"#{action.pluralize}",
        foreign_key: :"#{source}_id",
        dependent: :destroy

      has_many :"#{action.progressize}",
        through: :"#{action.pluralize}",
        source: :"target_#{target}"

      def #{action}(target)
        return if #{action.progressize}?(target) || (self == target)

        #{action.pluralize}.create(target_#{target}_id: target.id)
      end

      def un#{action}(target)
        return unless #{action.progressize}?(target)

        #{action.pluralize}.find_by(target_#{target}_id: target.id).destroy
      end

      def #{action.progressize}?(target)
        #{action.pluralize}.exists?(target_#{target}_id: target.id)
      end
    RUBY
  end
end