-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
static_model_preferences.rb
54 lines (44 loc) · 1.3 KB
/
static_model_preferences.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# frozen_string_literal: true
module Spree
module Preferences
class StaticModelPreferences
class Definition
attr_reader :preferences
def initialize(klass, hash)
hash = hash.symbolize_keys
hash.keys.each do |key|
if !klass.defined_preferences.include?(key)
raise "Preference #{key.inspect} is not defined on #{klass}"
end
end
@preferences = hash
end
def fetch(key, &block)
@preferences.fetch(key, &block)
end
def []=(key, value)
# ignores assignment
end
def to_hash
@preferences.deep_dup
end
end
def initialize
@store = Hash.new do |data, klass|
data[klass] = {}
end
end
def add(klass, name, preferences)
constantized_klass = klass.try(:constantize) || klass
# We use class name instead of class to allow reloading in dev
if @store[constantized_klass.to_s][name]
raise "Static model preference '#{name}' on #{constantized_klass} is already defined"
end
@store[constantized_klass.to_s][name] = Definition.new(constantized_klass, preferences)
end
def for_class(klass)
@store[klass.to_s]
end
end
end
end