Skip to content

Instantly share code, notes, and snippets.

@scottmessinger
Created August 20, 2010 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottmessinger/540368 to your computer and use it in GitHub Desktop.
Save scottmessinger/540368 to your computer and use it in GitHub Desktop.
Sorting sequences
# from sequences_controller.rb
def sort
sequence_groups = []
#turn hash into array
if params[:sequence_groups]
params[:sequence_groups].each do |k, v|
sequence_groups << v
end
array = Sequence.assign_group_id(sequence_groups)
elsif params[:sequences]
array = []
params[:sequences].each do |s|
sequence_id = s.to_s.gsub("sequence_", "")
array << sequence_id
end
end
#assign group_ids, then reorder the sequences
sequences = Sequence.find_sequences_from_array(array)
Sequence.reorder_siblings(sequences)
@course = Course.find(sequences[0].course_id)
render :nothing => true
end
# from sequence.rb
def self.assign_group_id(sequence_groups)
sequence_ids_array = []
sequence_groups.each do |sg|
group_id = sg.keys[0].to_s.gsub('sequence_group_', '')
sg.values[0].each do |s|
sequence_id = s.to_s.gsub("sequence_", "")
Sequence.set(sequence_id, :sequence_group_id => group_id )
sequence_ids_array << sequence_id
end
end
return sequence_ids_array
end
def self.find_sequences_from_array(sequence_ids_array)
sequence_array = []
sequence_ids_array.each do |r|
sequence_array << Sequence.find(r)
end
return sequence_array
end
def self.reorder_siblings(siblings)
if siblings.first.parent.nil?
siblings.each_with_index do |s, i|
Sequence.set(s.id, :root_position => i + 1 )
end
siblings.group_by(&:unit_type_id).each do |unit_type, sequences|
sequences.each_with_index do |s, i|
Sequence.set(s.id, :position => i + 1)
end
end
else
siblings.each_with_index do |s,i|
Sequence.set(s.id, :position => i + 1)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment