Class: Shiftable::Single

Inherits:
Module
  • Object
show all
Defined in:
lib/shiftable/single.rb

Overview

Inheriting from Module is a powerful pattern. If you like it checkout the debug_logging gem!

Defined Under Namespace

Modules: ShiftSingleModulizer

Instance Method Summary collapse

Constructor Details

#initialize(belongs_to:, has_one:, method_prefix: nil, precheck: true, before_shift: nil, wrapper: nil) ⇒ Single

Returns a new instance of Single.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/shiftable/single.rb', line 24

def initialize(belongs_to:, has_one:, method_prefix: nil, precheck: true, before_shift: nil, wrapper: nil)
  # Ruby's Module initializer doesn't take any arguments
  super()

  @signature = ModSignature.new(
    # For the following, imagine you are a Spaceship Captain, the Spaceship belongs_to you, and it has only one Captain.
    # But you have to sell it to your nemesis!
    associations: {
      # The name of the belongs_to association, defined on the shifting model, e.g. Spaceship
      # Normally a camel-cased, symbolized, version of the class name.
      # In the case where Spaceship belongs_to: :captain, this is :captain.
      belongs_to: belongs_to.to_s.to_sym,
      # The name of the has_one association, defined on the shift_to/shift_from model, e.g. Captain.
      # Normally a camel-cased, symbolized, version of the class name.
      # In the case where Captain has_one: :spaceship, this is :spaceship.
      has_one: has_one.to_s.to_sym
    },
    options: {
      # Do not move record if a record already exists (we are shifting a "has_one" association, after all)
      precheck: precheck,
      method_prefix: method_prefix,
      # will prevent the save if it returns false
      # allows for any custom logic to be run, such as setting attributes, prior to the shift (save).
      before_shift: before_shift,
      wrapper: wrapper
    },
    type: :sg
  )
end

Instance Method Details

#extended(base) ⇒ Object

NOTE: Possible difference in how inheritance works when using extend vs include

with Shiftable::Single.new


56
57
58
59
# File 'lib/shiftable/single.rb', line 56

def extended(base)
  shift_single_modulizer = ShiftSingleModulizer.to_mod(@signature.add_base(base))
  base.singleton_class.send(:prepend, shift_single_modulizer)
end

#included(base) ⇒ Object

NOTE: Possible difference in how inheritance works when using extend vs include

with Shiftable::Single.new


63
64
65
66
# File 'lib/shiftable/single.rb', line 63

def included(base)
  shift_single_modulizer = ShiftSingleModulizer.to_mod(@signature.add_base(base))
  base.send(:prepend, shift_single_modulizer)
end