Module: Dynomite::Item::MagicFields

Extended by:
ActiveSupport::Concern
Defined in:
lib/dynomite/item/magic_fields.rb

Instance Method Summary collapse

Instance Method Details

#generate_random_key_schema_value(key_type) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dynomite/item/magic_fields.rb', line 29

def generate_random_key_schema_value(key_type)
  attribute_name = key_schema.find { |a| a.key_type == key_type }.attribute_name
  attribute_type = attribute_definitions.find { |a| a.attribute_name == attribute_name }.attribute_type
  case attribute_type
  when "N" # number
    # 40 digit number that does not start with 0
    first_digit = rand(1..9) # Generate a random digit from 1 to 9
    rest_of_digits = Array.new(39) { rand(0..9) }.join # Generate the remaining 39 digits
    random_number = "#{first_digit}#{rest_of_digits}"
    random_number.to_i
  when "S" # string
    # 40 character string
    Digest::SHA1.hexdigest([Time.now, rand].join) # IE: fead3c000892e9e8c78e821411bbaa9dc3cb938c
  end
end

#set_created_atObject



45
46
47
# File 'lib/dynomite/item/magic_fields.rb', line 45

def set_created_at
  self.created_at ||= Time.now
end

#set_partition_keyObject



20
21
22
23
24
25
26
27
# File 'lib/dynomite/item/magic_fields.rb', line 20

def set_partition_key
  return if @attrs[partition_key_field]
  if partition_key_field.to_s == "id"
    @attrs.merge!(partition_key_field => generate_id) # IE: post-0GKjo3Ck0OBL6nAi
  else
    @attrs.merge!(partition_key_field => generate_random_key_schema_value("HASH")) # HASH is the partition key
  end
end

#set_sort_keyObject



14
15
16
17
18
# File 'lib/dynomite/item/magic_fields.rb', line 14

def set_sort_key
  return unless sort_key_field
  return if @attrs[sort_key_field]
  @attrs.merge!(sort_key_field => generate_random_key_schema_value("RANGE")) # RANGE is the sort key
end

#set_updated_atObject



49
50
51
# File 'lib/dynomite/item/magic_fields.rb', line 49

def set_updated_at
  self.updated_at = Time.now if changed?
end