Class: Ez::Settings::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/ez/settings/store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(group, backend, options = {}) ⇒ Store

Returns a new instance of Store.



13
14
15
16
17
18
19
20
21
22
# File 'lib/ez/settings/store.rb', line 13

def initialize(group, backend, options = {})
  @group     = group
  @errors    = ActiveModel::Errors.new(self)
  @backend   = backend
  @on_change = options.fetch(:on_change, nil)

  define_accessors

  keys.each { |key| default_or_exists_value(data, key) }
end

Instance Attribute Details

#backendObject (readonly)

Returns the value of attribute backend.



11
12
13
# File 'lib/ez/settings/store.rb', line 11

def backend
  @backend
end

#errorsObject (readonly)

Returns the value of attribute errors.



11
12
13
# File 'lib/ez/settings/store.rb', line 11

def errors
  @errors
end

#groupObject (readonly)

Returns the value of attribute group.



11
12
13
# File 'lib/ez/settings/store.rb', line 11

def group
  @group
end

#on_changeObject (readonly)

Returns the value of attribute on_change.



11
12
13
# File 'lib/ez/settings/store.rb', line 11

def on_change
  @on_change
end

Instance Method Details

#invalid?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/ez/settings/store.rb', line 36

def invalid?
  !valid?
end

#schemaObject



53
54
55
56
57
58
59
# File 'lib/ez/settings/store.rb', line 53

def schema
  {
    group.name => group.keys.map(&:name).each_with_object({}) do |key_name, schema|
      schema[key_name] = send(key_name)
    end
  }
end

#update(params) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ez/settings/store.rb', line 40

def update(params)
  params.each { |key, value| public_send("#{key}=", value) }

  validate
  return self unless errors.empty?

  on_change&.call(changes(params))

  backend.write(schema)

  self
end

#valid?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/ez/settings/store.rb', line 32

def valid?
  errors.empty?
end

#validateObject



24
25
26
27
28
29
30
# File 'lib/ez/settings/store.rb', line 24

def validate
  @errors = ActiveModel::Errors.new(self)

  group.keys.select(&:required?).each do |key|
    errors.add(key.name, "can't be blank") if send(key.name).blank?
  end
end