Module: Sandra

Defined in:
lib/sandra.rb,
lib/sandra/list.rb,
lib/sandra/key_validator.rb

Defined Under Namespace

Modules: ClassMethods Classes: KeyValidator, List

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sandra.rb', line 7

def self.included(base)
  base.extend(ClassMethods)
  base.extend(ActiveModel::Naming)
  base.extend(ActiveModel::Callbacks)
  base.class_eval do
    include ActiveModel::Validations
    include ActiveModel::Conversion
    include ActiveModel::SecurePassword
    define_model_callbacks :create, :update, :save, :destroy
    attr_accessor :attributes, :new_record

    def initialize(attrs = {})
      @attributes = attrs.stringify_keys
      @unregistered_attrs = @attributes.keys - self.class.registered_columns.map(&:to_s)
      @unregistered_attrs.each do |attr|
        self.send("#{attr}=", @attributes[attr])
        @attributes.delete(attr)
      end
      @new_record = true
    end
  end
end

Instance Method Details

#idObject



34
35
36
# File 'lib/sandra.rb', line 34

def id
  key
end

#keyObject



30
31
32
# File 'lib/sandra.rb', line 30

def key
  attributes[self.class.key.to_s]
end

#new_record?Boolean

Returns:

  • (Boolean)


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

def new_record?
  new_record
end

#persisted?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/sandra.rb', line 46

def persisted?
  !new_record
end

#saveObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sandra.rb', line 50

def save
  callback_target = self.new_record? ? :create : :update
  run_callbacks callback_target do
    run_callbacks :save do
      attrs = attributes.dup
      key = attrs.delete(self.class.key.to_s)
      if key && valid?
        self.class.insert(key, attrs)
        new_record = false
        true
      else
        false
      end
    end
  end
end

#to_modelObject



38
39
40
# File 'lib/sandra.rb', line 38

def to_model
  self
end