Class: Mara::PrimaryKey
- Inherits:
-
Object
- Object
- Mara::PrimaryKey
- Defined in:
- lib/mara/primary_key.rb
Overview
Wraps a primary key.
Instance Attribute Summary collapse
-
#class_name ⇒ String
readonly
The classname of the model that the primary key represents.
-
#partition_key ⇒ String
readonly
The partion key.
-
#sort_key ⇒ String
readonly
The sort key.
Class Method Summary collapse
-
.generate(model) ⇒ String
Create a primary key from a model.
-
.parse(key_str) ⇒ Mara::PrimaryKey
Parse a primary key string.
Instance Method Summary collapse
-
#initialize(opts) ⇒ PrimaryKey
constructor
Create a new primary key.
-
#to_s ⇒ String
Convert the primary key into a URL safe representation.
Constructor Details
#initialize(opts) ⇒ PrimaryKey
Note:
If :model
is not present the other three options are required.
Create a new primary key.
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/mara/primary_key.rb', line 82 def initialize(opts) if (model = opts.delete(:model)).present? @class_name = model.class.name @partition_key = if model.class.partition_key.present? model.partition_key end @sort_key = if model.class.sort_key.present? model.sort_key end else @class_name = opts.fetch(:class_name).camelize @partition_key = opts.fetch(:partition_key) @sort_key = opts.fetch(:sort_key, nil).presence end end |
Instance Attribute Details
#class_name ⇒ String (readonly)
The classname of the model that the primary key represents.
58 59 60 |
# File 'lib/mara/primary_key.rb', line 58 def class_name @class_name end |
#partition_key ⇒ String (readonly)
The partion key
64 65 66 |
# File 'lib/mara/primary_key.rb', line 64 def partition_key @partition_key end |
#sort_key ⇒ String (readonly)
The sort key
70 71 72 |
# File 'lib/mara/primary_key.rb', line 70 def sort_key @sort_key end |
Class Method Details
.generate(model) ⇒ String
Create a primary key from a model.
19 20 21 22 23 24 25 26 27 28 |
# File 'lib/mara/primary_key.rb', line 19 def generate(model) case model when Mara::PrimaryKey model.to_s when Mara::Model::Base new(model: model).to_s else raise ArgumentError, "The value passed into generate isn't expected <#{model}>" end end |
.parse(key_str) ⇒ Mara::PrimaryKey
Parse a primary key string.
36 37 38 39 40 41 42 43 |
# File 'lib/mara/primary_key.rb', line 36 def parse(key_str) parts = JSON.parse(decode(key_str)) new( class_name: parts[0], partition_key: parts[1], sort_key: parts[2] ) end |
Instance Method Details
#to_s ⇒ String
Convert the primary key into a URL safe representation.
102 103 104 105 106 107 108 109 |
# File 'lib/mara/primary_key.rb', line 102 def to_s payload = JSON.dump([ (class_name.presence || '').underscore, partition_key.presence || '', sort_key.presence || '' ]) encode(payload) end |