Class: NestedRecord::PrimaryKeyCheck

Inherits:
Object
  • Object
show all
Defined in:
lib/nested_record/primary_key_check.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, pkey_attributes) ⇒ PrimaryKeyCheck

Returns a new instance of PrimaryKeyCheck.



2
3
4
5
6
# File 'lib/nested_record/primary_key_check.rb', line 2

def initialize(klass, pkey_attributes)
  @klass = klass
  @pkey_attributes = pkey_attributes
  @params = [klass, pkey_attributes]
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



8
9
10
# File 'lib/nested_record/primary_key_check.rb', line 8

def params
  @params
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



14
15
16
# File 'lib/nested_record/primary_key_check.rb', line 14

def ==(other)
  self.class === other && params == other.params
end

#build_pkey(obj) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/nested_record/primary_key_check.rb', line 19

def build_pkey(obj)
  pkey = { _is_a?: @klass }
  if obj.is_a? @klass
    pkey[:_not_equal?] = obj
    @pkey_attributes.each do |name|
      pkey[name] = obj.read_attribute(name)
    end
  elsif obj.respond_to? :[]
    @pkey_attributes.each do |name|
      value = obj[name]
      if (type = @klass.type_for_attribute(name))
        value = type.cast(value)
      end
      pkey[name] = value
    end
  else
    fail
  end
  pkey
end

#hashObject



10
11
12
# File 'lib/nested_record/primary_key_check.rb', line 10

def hash
  params.hash
end

#perform!(collection, obj) ⇒ Object



40
41
42
43
# File 'lib/nested_record/primary_key_check.rb', line 40

def perform!(collection, obj)
  pkey = build_pkey(obj)
  raise NestedRecord::PrimaryKeyError if collection.exists?(pkey)
end