Sha256: 7e92910c5f1bffad9c282c49230337d5d54a7355ba1b0e5dcc55930881e2870b

Contents?: true

Size: 1.67 KB

Versions: 7

Compression:

Stored size: 1.67 KB

Contents

module ForestLiana
  class LineStatGetter
    attr_accessor :record

    def initialize(resource, params)
      @resource = resource
      @params = params
      @populates = {}
    end

    def perform
      value = @resource

      @params[:filters].try(:each) do |filter|
        operator, filter_value = OperatorValueParser.parse(filter[:value])
        value = value.where("#{filter[:field]} #{operator} '#{filter_value}'")
      end

      value = value.send(time_range, @params[:group_by_date_field])
      value = value.group(group_by_field || :id) if group_by_field

      value = value.send(@params[:aggregate].downcase, @params[:aggregate_field])
        .map do |k, v|
          if k.kind_of?(Array)
            {
              label: k[0],
              values: {
                key: populate(k[1]),
                value: v
              }
            }
          else
            {
              label: k,
              values: {
                value: v
              }
            }
          end
        end

      @record = Stat.new(value: value)
    end

    private

    def group_by_field
      field_name = @params[:group_by_field]
      association = @resource.reflect_on_association(field_name)

      if association
        association.foreign_key
      else
        field_name
      end
    end

    def populate(id)
      @populates[id] ||= begin
        field_name = @params[:group_by_field]
        association = @resource.reflect_on_association(field_name)

        if association
          association.klass.find(id)
        else
          id
        end
      end
    end

    def time_range
      "group_by_#{@params[:time_range].try(:downcase) || 'month'}"
    end

  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
forest_liana-1.1.12 app/services/forest_liana/line_stat_getter.rb
forest_liana-1.1.11 app/services/forest_liana/line_stat_getter.rb
forest_liana-1.1.10 app/services/forest_liana/line_stat_getter.rb
forest_liana-1.1.8 app/services/forest_liana/line_stat_getter.rb
forest_liana-1.1.7 app/services/forest_liana/line_stat_getter.rb
forest_liana-1.1.6 app/services/forest_liana/line_stat_getter.rb
forest_liana-1.1.5 app/services/forest_liana/line_stat_getter.rb