Class: Oort::Inserts

Inherits:
Object
  • Object
show all
Defined in:
lib/oort/inserts.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stored_in:, insert_method_name:, class_name:) ⇒ Inserts

Returns a new instance of Inserts.



11
12
13
14
15
# File 'lib/oort/inserts.rb', line 11

def initialize(stored_in:, insert_method_name:, class_name:)
  @stored_in = stored_in
  @insert_method_name = insert_method_name
  @class_name = class_name
end

Instance Attribute Details

#class_nameObject (readonly)

Returns the value of attribute class_name.



9
10
11
# File 'lib/oort/inserts.rb', line 9

def class_name
  @class_name
end

#insert_method_nameObject (readonly)

Returns the value of attribute insert_method_name.



9
10
11
# File 'lib/oort/inserts.rb', line 9

def insert_method_name
  @insert_method_name
end

#stored_inObject (readonly)

Returns the value of attribute stored_in.



9
10
11
# File 'lib/oort/inserts.rb', line 9

def stored_in
  @stored_in
end

Class Method Details

.call(stored_in:, insert_method_name:, class_name:) ⇒ Object



5
6
7
# File 'lib/oort/inserts.rb', line 5

def self.call(stored_in:, insert_method_name:, class_name:)
  new(stored_in: stored_in, insert_method_name: insert_method_name, class_name: class_name).call
end

Instance Method Details

#callObject



17
18
19
20
21
22
23
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
# File 'lib/oort/inserts.rb', line 17

def call
  class_name.class_eval(
    # def update_posts_ordering(insert:, at: 0)
    #   with_lock do
    #     current_values = public_send(stored_in.inspect)
    #     current_index = current_values.find_index(insert)
    #     insertable = current_index.blank? ? insert : current_values.delete_at(current_index)
    #     current_values.insert(at, insertable)
    #     update(stored_in.inspect => current_values)
    #   end
    # end
    <<-RUBY, __FILE__, __LINE__ + 1
      def #{insert_method_name}(insert:, at: 0, initial: nil)
        with_lock do
          current_values = public_send(#{stored_in.inspect})

          if initial == :top
            current_values.unshift(insert)
            save
          elsif initial == :bottom
            current_values << insert
            save
          else
            current_index = current_values.find_index(insert)
            insertable = current_index.blank? ? insert : current_values.delete_at(current_index)
            current_values.insert(at, insertable)
            update(#{stored_in.inspect} => current_values)
          end
        end
      end
    RUBY
  )
end