Module: Babik::QuerySet::Clonable

Included in:
AbstractBase
Defined in:
lib/babik/queryset/mixins/clonable.rb

Overview

Clone operation for the QuerySet

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &_block) ⇒ QuerySet

Check if the called method has a modifying version (a bang method). If that is the case it will be called on a clone of this instance. Otherwise, super will be called.

Parameters:

  • name (String)

    method name

  • args (String)

    method arguments

  • _block (Proc)

    Proc that could be passed to the method. Not used.

Returns:

  • (QuerySet)

    Clone of this QuerySet (with method ‘name’ called on ), an empty QuerySet.



36
37
38
39
40
# File 'lib/babik/queryset/mixins/clonable.rb', line 36

def method_missing(name, *args, &_block)
  modifying_method = "#{name}!"
  return mutate_clone(modifying_method.to_sym, args) if self.respond_to?(modifying_method)
  super
end

Instance Method Details

#cloneQuerySet

Clone the queryset using ruby_deep_clone https://github.com/gmodarelli/ruby-deepclone.

Returns:

  • (QuerySet)

    Deep copy of this QuerySet.



12
13
14
# File 'lib/babik/queryset/mixins/clonable.rb', line 12

def clone
  DeepClone.clone(self)
end

#mutate_clone(mutator_method, parameters = []) ⇒ QuerySet

Clone this QuerySet and apply the ‘mutator_method’ to it.

Parameters:

  • mutator_method (Symbol)

    Name of the method.

  • parameters (Array) (defaults to: [])

    Parameters passed to the method

Returns:

  • (QuerySet)

    The resultant QuerySet of applying the mutator to the clone of the caller object.



20
21
22
23
24
25
26
27
28
# File 'lib/babik/queryset/mixins/clonable.rb', line 20

def mutate_clone(mutator_method, parameters = [])
  clone_ = clone
  if parameters.empty?
    clone_.send(mutator_method)
  else
    clone_.send(mutator_method, *parameters)
  end
  clone_
end

#respond_to_missing?(name, *_args, &_block) ⇒ Boolean

Check if the called method has a modifying version (a bang method).

Returns:

  • (Boolean)

    True if there is a modifying method with the requested method name in that case, return true, otherwise, return false.



45
46
47
48
# File 'lib/babik/queryset/mixins/clonable.rb', line 45

def respond_to_missing?(name, *_args, &_block)
  modifying_method = "#{name}!"
  self.respond_to?(modifying_method)
end