Class: Preflex::Preference

Inherits:
ApplicationRecord show all
Defined in:
app/models/preflex/preference.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.currentObject



57
58
59
# File 'app/models/preflex/preference.rb', line 57

def self.current
  self.for(current_owner(Preflex::Current.controller_instance))
end

.current_owner(controller_instance) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/models/preflex/preference.rb', line 37

def self.current_owner(controller_instance)
  raise '
    Please define a class method called owner that returns the owner of this preference.
    You can use `controller_instance` to refer to things like current_user/etc.
    You can return either:
      an ActiveRecord object persisted in the DB
      or any object that responds to `id` - returning a unique id
      or a string that uniquely identifies the owner
    Example:
      def self.current_owner(controller_instance)
        controller_instance.current_user
      end
  '
end

.ensure_preference_exists(name) ⇒ Object



69
70
71
# File 'app/models/preflex/preference.rb', line 69

def self.ensure_preference_exists(name)
  raise "Preference #{name} was not defined. Make sure you define it (e.g. `preference :#{name}, :big_integer, default: 10`)" unless @preferences&.include?(name)
end

.for(owner) ⇒ Object



52
53
54
55
# File 'app/models/preflex/preference.rb', line 52

def self.for(owner)
  owner = "#{owner.class.name}-#{owner.id}" if owner.respond_to?(:id)
  PreferenceCache.for(self, owner.to_s)
end

.get(name) ⇒ Object



61
62
63
# File 'app/models/preflex/preference.rb', line 61

def self.get(name)
  current.get(name)
end

.preference(name, type, default: nil, private: false) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'app/models/preflex/preference.rb', line 27

def self.preference(name, type, default: nil, private: false)
  name = name.to_sym

  @preferences ||= Set.new
  @preferences.add(name)

  store_attribute(:data, name, type, default: default)
  store_attribute(:data, "#{name}_updated_at_epoch".to_sym, :big_integer, default: 0)
end

.set(name, value) ⇒ Object



65
66
67
# File 'app/models/preflex/preference.rb', line 65

def self.set(name, value)
  current.set(name, value)
end

Instance Method Details

#data_for_jsObject



23
24
25
# File 'app/models/preflex/preference.rb', line 23

def data_for_js
  data.to_json
end

#get(name) ⇒ Object



7
8
9
10
11
12
# File 'app/models/preflex/preference.rb', line 7

def get(name)
  name = name.to_sym
  self.class.ensure_preference_exists(name)

  send(name)
end

#set(name, value) ⇒ Object



14
15
16
17
18
19
20
21
# File 'app/models/preflex/preference.rb', line 14

def set(name, value)
  name = name.to_sym
  self.class.ensure_preference_exists(name)

  send("#{name}=", value)
  send("#{name}_updated_at_epoch=", (Time.current.to_f * 1000).round)
  save!
end