<commit_before>require 'spree/localized_number'

module Calculator
  class Weight < Spree::Calculator
    extend Spree::LocalizedNumber
    preference :per_kg, :decimal, default: 0.0
    attr_accessible :preferred_per_kg
    localize_number :preferred_per_kg

    def self.description
      I18n.t('spree.weight')
    end

    def compute(object)
      line_items = line_items_for object
      total_weight(line_items) * preferred_per_kg
    end

    def total_weight(line_items)
      line_items.sum do |line_item|
        if line_item.final_weight_volume.present?
          line_item.final_weight_volume / 1000
        else
          (line_item.variant.andand.weight || 0) * line_item.quantity
        end
      end
    end
  end
end<commit_msg>Further improve weight calculator code<commit_after>require 'spree/localized_number'

module Calculator
  class Weight < Spree::Calculator
    extend Spree::LocalizedNumber
    preference :per_kg, :decimal, default: 0.0
    attr_accessible :preferred_per_kg
    localize_number :preferred_per_kg

    def self.description
      I18n.t('spree.weight')
    end

    def compute(object)
      line_items = line_items_for object
      total_weight(line_items) * preferred_per_kg
    end

    def total_weight(line_items)
      line_items.sum do |line_item|
        line_item_weight(line_item)
      end
    end

    def line_item_weight(line_item)
      if line_item.final_weight_volume.present?
        # Divided by 1000 because grams is the base weight unit and the calculator price is per_kg
        line_item.final_weight_volume / 1000
      else
        (line_item.variant.andand.weight || 0) * line_item.quantity
      end
    end
  end
end
{'fraction_non_alphanumeric': 0.06335109532267615, 'fraction_numerical': 0.013025458851391355, 'mean_word_length': 3.0334128878281623, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5372024', 'n_tokens_mistral': 563, 'n_tokens_neox': 526, 'n_words': 119}