Sha256: 5c50085695ad307c9407f7c40da46c2fba1c38ef7330442ca6d5a2f0f2795ae5

Contents?: true

Size: 1.79 KB

Versions: 6

Compression:

Stored size: 1.79 KB

Contents

module Spree::Preferences
  module PreferableClassMethods
    def preference(name, type, *args)
      options = args.extract_options!
      options.assert_valid_keys(:default, :deprecated)
      default = options[:default]
      default = -> { options[:default] } unless default.is_a?(Proc)
      deprecated = options[:deprecated]

      # cache_key will be nil for new objects, then if we check if there
      # is a pending preference before going to default
      define_method preference_getter_method(name) do
        preferences.fetch(name) do
          default.call
        end
      end

      define_method preference_setter_method(name) do |value|
        value = convert_preference_value(value, type)
        preferences[name] = value

        Spree::Deprecation.warn("`#{name}` is deprecated. #{deprecated}") if deprecated

        # If this is an activerecord object, we need to inform
        # ActiveRecord::Dirty that this value has changed, since this is an
        # in-place update to the preferences hash.
        preferences_will_change! if respond_to?(:preferences_will_change!)
      end

      define_method preference_default_getter_method(name), &default

      define_method preference_type_getter_method(name) do
        type
      end

      define_method preference_deprecated_getter_method(name) do
        deprecated
      end
    end

    def preference_getter_method(name)
      "preferred_#{name}".to_sym
    end

    def preference_setter_method(name)
      "preferred_#{name}=".to_sym
    end

    def preference_default_getter_method(name)
      "preferred_#{name}_default".to_sym
    end

    def preference_deprecated_getter_method(name)
      "preferred_#{name}_deprecated".to_sym
    end

    def preference_type_getter_method(name)
      "preferred_#{name}_type".to_sym
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spree_core-4.8.3 lib/spree/core/preferences/preferable_class_methods.rb
spree_core-4.8.2 lib/spree/core/preferences/preferable_class_methods.rb
spree_core-4.7.3 lib/spree/core/preferences/preferable_class_methods.rb
spree_core-4.7.2 lib/spree/core/preferences/preferable_class_methods.rb
spree_core-4.7.1 lib/spree/core/preferences/preferable_class_methods.rb
spree_core-4.7.0 lib/spree/core/preferences/preferable_class_methods.rb