Class: DropletKit::BaseModel

Inherits:
Object
  • Object
show all
Defined in:
lib/droplet_kit/models/base_model.rb

Constant Summary collapse

DO_NAMESPACE =
'do'
UNSUPPORTED_COLLECTIONS =
['space']

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_identifier(identifier) ⇒ Object


61
62
63
# File 'lib/droplet_kit/models/base_model.rb', line 61

def self.from_identifier(identifier)
  new(id: identifier)
end

.from_urn(urn) ⇒ Object


48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/droplet_kit/models/base_model.rb', line 48

def self.from_urn(urn)
  DropletKit::Error.new("Invalid urn: #{urn}") unless valid_urn?(urn)

  parts = urn.split(':')
  collection = parts[1]
  identifier = parts[2]

  return nil if UNSUPPORTED_COLLECTIONS.include?(collection)

  klass = const_get("DropletKit::#{DropletKit::Utils.camelize(collection)}")
  klass.from_identifier(identifier)
end

.valid_urn?(urn) ⇒ Boolean

Returns:

  • (Boolean)

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/droplet_kit/models/base_model.rb', line 32

def self.valid_urn?(urn)
  parts = urn.split(':')
  return false if parts.size != 3 || parts[0] != DO_NAMESPACE

  collection = parts[1]
  return true if UNSUPPORTED_COLLECTIONS.include?(collection)

  begin
    const_get "DropletKit::#{DropletKit::Utils.camelize(collection)}"
  rescue NameError
    return false
  end

  true
end

Instance Method Details

#collection_nameObject


21
22
23
# File 'lib/droplet_kit/models/base_model.rb', line 21

def collection_name
  DropletKit::Utils.underscore self.class.name.split('::').last
end

#identifierObject

Raises:


25
26
27
28
29
30
# File 'lib/droplet_kit/models/base_model.rb', line 25

def identifier
  identifier = attributes[:id] || attributes[:uuid] || attributes[:slug]
  raise DropletKit::Error.new("#{self.class.name} doesn't support URNs") if identifier.nil?

  identifier
end

#inspectObject


12
13
14
15
# File 'lib/droplet_kit/models/base_model.rb', line 12

def inspect
  values = Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
  "<#{self.class.name} #{values}>"
end

#urnObject


17
18
19
# File 'lib/droplet_kit/models/base_model.rb', line 17

def urn
  "#{DO_NAMESPACE}:#{collection_name}:#{identifier}"
end