Method: CustomTable::ApplicationHelper#custom_table_totals

Defined in:
app/helpers/custom_table/application_helper.rb

#custom_table_totals(collection, fields, totals = {}, fields_totals = {}) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'app/helpers/custom_table/application_helper.rb', line 119

def custom_table_totals collection, fields, totals = {}, fields_totals = {}

  out = {}
  totals = {} if totals.nil?
  fields_totals = {} if fields_totals.nil?

  fields.keys.each do |field|

    # We only work if field total is enabled explicitly with definition or totals
    next if !fields[field][:total] && !totals.has_key?(field)

    # Taking pre-defined value if available
    if !totals[field].nil?
      out[field] = totals[field]
    else
      model_class = collection.model
      # Trying to find helper first
      model_name = model_class.model_name.singular
      helper = "#{model_name}_#{field}_total"

      if self.class.method_defined?(helper)
        # Better use helper!
        out[field] = self.send(helper, collection.except(:limit, :offset, :order, :group))
      else
        if collection.respond_to?(:total_pages) && (!model_class.columns_hash[field.to_s].nil? || !fields[field][:total_scope].nil?) 
          # We can try to sum value from database

          if fields[field][:total_scope].nil?
            out[field] = collection.except(:limit, :offset, :order, :group).distinct(false).sum(field)
          else
            out[field] = collection.except(:limit, :offset, :order, :group).distinct(false).send(fields[field][:total_scope])
          end
        else
          # Taking simple summed value because all data is shown
          out[field] = fields_totals[field]
        end

      end

    end
  end

  out

end