Class: Preferable::Set

Inherits:
Hash
  • Object
show all
Defined in:
lib/preferable/set.rb

Constant Summary collapse

PRIVATE =
[:rehash, :fetch, :store, :shift, :delete, :delete_if, :keep_if].to_set.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner) ⇒ Set

Returns a new instance of Set.



15
16
17
18
# File 'lib/preferable/set.rb', line 15

def initialize(owner)
  super()
  @owner = owner
end

Instance Attribute Details

#ownerObject (readonly)

Returns the value of attribute owner.



13
14
15
# File 'lib/preferable/set.rb', line 13

def owner
  @owner
end

Class Method Details

.wrap(owner, value) ⇒ Object



9
10
11
# File 'lib/preferable/set.rb', line 9

def self.wrap(owner, value)
  new(owner).set(value || {})
end

Instance Method Details

#[](name) ⇒ Object



20
21
22
23
# File 'lib/preferable/set.rb', line 20

def [](name)
  field = find_field(name)
  super(field.name) || field.default if field
end

#[]=(name, value) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/preferable/set.rb', line 25

def []=(name, value)
  field = find_field(name) || return
  value = field.type_cast(value)

  if value.nil? || field.invalid?(value) || field.default?(value)
    delete field.name
  else
    super field.name, value
  end
  owner.send :write_attribute, :preferences, to_hash
end

#set(pairs) ⇒ Object



37
38
39
40
# File 'lib/preferable/set.rb', line 37

def set(pairs)
  pairs.each {|k, v| self[k] = v }
  self
end

#to_hashObject



42
43
44
# File 'lib/preferable/set.rb', line 42

def to_hash
  {}.update(self)
end