class Corpshort::Link

Constants

NAME_REGEXP

Attributes

backend[R]
name[R]
updated_at[R]
url[RW]

Public Class Methods

new(data, backend: nil) click to toggle source
# 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
validate_name(name) click to toggle source
# 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

Public Instance Methods

as_json() click to toggle source
# 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_url() click to toggle source
# 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) click to toggle source
# 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_h() click to toggle source
# File lib/corpshort/link.rb, line 65
def to_h
  {
    name: name,
    url: url,
    updated_at: updated_at,
  }
end
to_json() click to toggle source
# File lib/corpshort/link.rb, line 79
def to_json
  as_json.to_json
end
updated_at=(ts) click to toggle source
# File lib/corpshort/link.rb, line 52
def updated_at=(ts)
  @updated_at = case ts
  when Time
    ts
  when String
    Time.iso8601(ts)
  when nil
    nil
  else
    raise TypeError, "link.updated_at must be a Time or a String (ISO 8601 formatted)"
  end
end
validate!() click to toggle source
# 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