Created
April 13, 2020 18:13
-
-
Save StefSchenkelaars/b249ee9aaeb17c9f0a9ca802a932538d to your computer and use it in GitHub Desktop.
Idea for refactor acts_as_list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
before_create :set_default_position | |
before_save :prepare_new_position | |
after_save :cleanup_new_position | |
after_save :cleanup_old_position | |
def set_default_position | |
return if self[position_column] | |
bottom_item = | |
acts_as_list_class | |
.unscope(:select, :where) | |
.where(scope_condition) | |
.where.not(position_column => nil) | |
.reorder(position_column => :desc) | |
.limit(1) | |
.pluck(position_column) | |
.try(:first) | |
if bottom_item | |
self[position_column] = bottom_item + 1 | |
else | |
self[position_column] = acts_as_list_top | |
end | |
# Don't halt the callback chain | |
true | |
end | |
def prepare_new_position | |
old_position, new_position = changes[position_column] | |
new_position ||= self[position_column] | |
scope = | |
acts_as_list_class | |
.unscope(:select, :where) | |
.where(scope_condition) | |
.where(self.class.arel_table[position_column].gteq(new_position)) | |
scope = scope.where(self.class.arel_table[position_column].lt(old_position)) if old_position | |
scope.update_all("#{position_column} = (#{position_column} + 1) * -1") | |
end | |
def cleanup_new_position | |
old_position, new_position = changes[position_column] | |
new_position ||= self[position_column] | |
acts_as_list_class | |
.unscope(:select, :where) | |
.where(scope_condition) | |
.where(self.class.arel_table[position_column].lt(0)) | |
.update_all("#{position_column} = #{position_column} * -1") | |
end | |
def cleanup_old_position | |
old_position, _new_position = saved_changes[position_column] | |
old_scope_value, new_scope_value = saved_changes[scope_name.to_s] | |
return unless old_scope_value && old_scope_value != new_scope_value | |
acts_as_list_class | |
.unscope(:select, :where) | |
.where(scope_name => old_scope_value) | |
.where(self.class.arel_table[position_column].gteq(old_position)) | |
.update_all("#{position_column} = #{position_column} - 1") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment