Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/composite_primary_keys/base.rb

Defined Under Namespace

Modules: CompositeClassMethods, CompositeInstanceMethods

Constant Summary collapse

INVALID_FOR_COMPOSITE_KEYS =
'Not appropriate for composite primary keys'
NOT_IMPLEMENTED_YET =
'Not implemented for composite primary keys yet'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.composite?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/composite_primary_keys/base.rb', line 33

def composite?
  false
end

.set_primary_keys(*keys) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/composite_primary_keys/base.rb', line 10

def set_primary_keys(*keys)
  keys = keys.first if keys.first.is_a?(Array)

  if keys.length == 1
    set_primary_key(keys.first)
    return
  end

  cattr_accessor :primary_keys
  self.primary_keys = keys.map { |k| k.to_sym }

  class_eval <<-EOV
    extend CompositeClassMethods
    include CompositeInstanceMethods
    include CompositePrimaryKeys::ActiveRecord::AssociationPreload
  EOV

  class << unscoped
    include CompositePrimaryKeys::ActiveRecord::FinderMethods::InstanceMethods
    include CompositePrimaryKeys::ActiveRecord::Relation::InstanceMethods
  end
end

Instance Method Details

#[](attr_name) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/composite_primary_keys/base.rb', line 42

def [](attr_name)
  # CPK
  if attr_name.is_a?(String) and attr_name != attr_name.split(CompositePrimaryKeys::ID_SEP).first
    attr_name = attr_name.split(CompositePrimaryKeys::ID_SEP)
  end

  # CPK
  if attr_name.is_a?(Array)
    attr_name.map {|name| read_attribute(name)}
  else
    read_attribute(attr_name)
  end
end

#[]=(attr_name, value) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/composite_primary_keys/base.rb', line 56

def []=(attr_name, value)
  # CPK
  if attr_name.is_a?(String) and attr_name != attr_name.split(CompositePrimaryKeys::ID_SEP).first
    attr_name = attr_name.split(CompositePrimaryKeys::ID_SEP)
  end

  if attr_name.is_a? Array
    unless value.length == attr_name.length
      raise "Number of attr_names and values do not match"
    end
    [attr_name, value].transpose.map {|name,val| write_attribute(name, val)}
    value
  else
     write_attribute(attr_name, value)
  end
end

#composite?Boolean

Returns:

  • (Boolean)


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

def composite?
  self.class.composite?
end