class Spree::Base < ActiveRecord::Base
  include Spree::Preferences::Preferable
  serialize :preferences, Hash

  include Spree::RansackableAttributes

  after_initialize do
    if has_attribute?(:preferences)
      self.preferences = default_preferences.merge(preferences)
    end
  end

  if Kaminari.config.page_method_name != :page
    def self.page num
      send Kaminari.config.page_method_name, num
    end
  end

  self.abstract_class = true
end

class Spree::Base < ActiveRecord::Base
  include Spree::Preferences::Preferable
  serialize :preferences, Hash

  include Spree::RansackableAttributes

  def initialize_preference_defaults
    if has_attribute?(:preferences)
      self.preferences = default_preferences.merge(preferences)
    end
  end

  # Only run preference initialization on models which requires it. Improves
  # performance of record initialization slightly.
  def self.preference(*args)
    # after_initialize can be called multiple times with the same symbol, it
    # will only be called once on initialization.
    after_initialize :initialize_preference_defaults
    super
  end

  if Kaminari.config.page_method_name != :page
    def self.page num
      send Kaminari.config.page_method_name, num
    end
  end

  self.abstract_class = true
end

Optimize init on models without preferences
Optimize init on models without preferences

This hook was run on initialization of every model (after_initialize is
run both on .new, .find, etc), but is only necessary on models which
have preferences. The hook is fairly quick, breaking out immediately
after checking has_attribute?, but object initialization is so common an
operation we should avoid any work we can.

Benchmark.ips do |x|
  x.report("building") do
    Spree::InventoryUnit.new
  end

  x.report("building and accessing") do
    Spree::InventoryUnit.new.state
  end
end

Before:

            building     16.692k (± 4.2%) i/s -     84.392k
building and accessing
                         15.554k (± 3.4%) i/s -     78.540k

After:

            building     19.819k (± 3.8%) i/s -     99.921k
building and accessing
                         19.465k (± 3.9%) i/s -     97.384k
