Method: Fe::Element#previous_element

Defined in:
app/models/fe/element.rb

#previous_element(question_sheet, page = nil) ⇒ Object

assume each element is on a question sheet only once to make things simpler. if not, just take the first one NOTE: getting the previous_element isn’t an expensive operation any more because of the all_elements_id cache



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'app/models/fe/element.rb', line 105

def previous_element(question_sheet, page = nil)
  return false unless question_sheet
  page ||= pages_on.detect{ |p| p.question_sheet == question_sheet }

  index = page.all_element_ids_arr.index(self.id)
  unless index
    # this can happen for yesno options, since they're rendered as elements but aren't on the page or in a grid
    # but just in case self is an element on the page and the element_ids got out of sync, rebuild the all_element_ids
    # and try again
    page.rebuild_all_element_ids
    index = page.all_element_ids_arr.index(self.id)
  end
  if index && index > 0 && prev_el_id = page.all_element_ids_arr[index-1]
    # occasionally the all_elements_ids_arr can get out of sync here, resulting in no element found
    el = Fe::Element.find_by(id: prev_el_id)
    unless el
      page.rebuild_all_element_ids
      index = page.all_element_ids_arr.index(self.id)
      prev_el_id = page.all_element_ids_arr[index-1]
      el = Fe::Element.find(prev_el_id) # give an error at this point if it's not found
    end

    return el
  end
end