Class: Corpshort::Link

Inherits:
Object
  • Object
show all
Defined in:
lib/corpshort/link.rb

Defined Under Namespace

Classes: NoBackendError, ValidationError

Constant Summary collapse

NAME_REGEXP =
%r{\A[a-zA-Z0-9./\-_]+\z}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, backend: nil) ⇒ Link

Returns a new instance of Link.



15
16
17
18
19
20
21
22
23
24
# File 'lib/corpshort/link.rb', line 15

def initialize(data, backend: nil)
  @backend = backend

  @name = data[:name] || data['name']
  @url = data[:url] || data['url']
  @parsed_url_point = nil
  self.updated_at = data[:updated_at] || data['updated_at']

  validate!
end

Instance Attribute Details

#backendObject (readonly)

Returns the value of attribute backend.



40
41
42
# File 'lib/corpshort/link.rb', line 40

def backend
  @backend
end

#nameObject (readonly)

Returns the value of attribute name.



41
42
43
# File 'lib/corpshort/link.rb', line 41

def name
  @name
end

#updated_atObject

Returns the value of attribute updated_at.



41
42
43
# File 'lib/corpshort/link.rb', line 41

def updated_at
  @updated_at
end

#urlObject

Returns the value of attribute url.



42
43
44
# File 'lib/corpshort/link.rb', line 42

def url
  @url
end

Class Method Details

.validate_name(name) ⇒ Object

Raises:



11
12
13
# File 'lib/corpshort/link.rb', line 11

def self.validate_name(name)
  raise ValidationError, "@name should satisfy #{NAME_REGEXP}" unless name.match?(NAME_REGEXP)
end

Instance Method Details

#as_jsonObject



73
74
75
76
77
# File 'lib/corpshort/link.rb', line 73

def as_json
  to_h.tap do |h|
    h[:updated_at] = h[:updated_at].iso8601 if h[:updated_at]
  end
end

#parsed_urlObject



44
45
46
47
48
49
50
# File 'lib/corpshort/link.rb', line 44

def parsed_url
  @parsed_url = nil if @parsed_url_point != url
  @parsed_url ||= url.yield_self do |u|
    @parsed_url_point = u
    URI.parse(u)
  end
end

#save!(backend = nil, create_only: false) ⇒ Object

Raises:



32
33
34
35
36
37
38
# File 'lib/corpshort/link.rb', line 32

def save!(backend = nil, create_only: false)
  @backend = backend if backend
  raise NoBackendError unless @backend
  validate!
  self.updated_at = Time.now
  @backend.put_link(self, create_only: create_only)
end

#to_hObject



65
66
67
68
69
70
71
# File 'lib/corpshort/link.rb', line 65

def to_h
  {
    name: name,
    url: url,
    updated_at: updated_at,
  }
end

#to_jsonObject



79
80
81
# File 'lib/corpshort/link.rb', line 79

def to_json
  as_json.to_json
end

#validate!Object

Raises:



26
27
28
29
30
# File 'lib/corpshort/link.rb', line 26

def validate!
  raise ValidationError, "@name, @url are required" unless name && url
  raise ValidationError, "invalid @url (URL needs scheme and host to be considered valid)" unless parsed_url.scheme && parsed_url.host
  self.class.validate_name(name)
end