Class: Inform::Link

Inherits:
Sequel::Model show all
Defined in:
lib/story_teller/inform/relational/link.rb

Overview

class Link

Constant Summary collapse

LinkTemplate =
'%<link_name>s -> %<to_name>s [%<to_identity>s]'.freeze
LinkMethods =
%w[from_id to_id].freeze
MethodWriterTemplate =
'%<method_name>s='.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Sequel::Model

implicit_table_name

Methods included from StoryTeller::InheritanceListener

included

Constructor Details

#initialize(values = {}, &block) ⇒ Link

Returns a new instance of Link.



67
68
69
# File 'lib/story_teller/inform/relational/link.rb', line 67

def initialize(values = {}, &block)
  super(self.class.relational_values(values), &block)
end

Class Method Details

.persisted_object_id(object) ⇒ Object

rubocop: disable Metrics/CyclomaticComplexity



83
84
85
86
87
88
89
90
91
# File 'lib/story_teller/inform/relational/link.rb', line 83

def self.persisted_object_id(object)
  return nil if object.nil?
  return object.id if object.respond_to?(:id) && object.id
  object.save_changes if object.respond_to?(:save_changes)
  return object.id if object.respond_to?(:id) && object.id
  return object.pk if object.respond_to?(:pk)

  nil
end

.relational_values(values) ⇒ Object



71
72
73
74
75
76
77
78
79
80
# File 'lib/story_teller/inform/relational/link.rb', line 71

def self.relational_values(values)
  return values unless values.is_a?(Hash)

  values = values.dup
  from = values.delete(:from)
  to = values.delete(:to)
  values[:from_id] ||= persisted_object_id(from)
  values[:to_id] ||= persisted_object_id(to)
  values
end

Instance Method Details

#<=>(other) ⇒ Object



108
109
110
# File 'lib/story_teller/inform/relational/link.rb', line 108

def <=>(other)
  self.name <=> other.name
end

#after_saveObject



99
100
101
102
# File 'lib/story_teller/inform/relational/link.rb', line 99

def after_save
  super
  self.modified_at = Time.now.utc
end

#before_createObject

rubocop: enable Metrics/CyclomaticComplexity



94
95
96
97
# File 'lib/story_teller/inform/relational/link.rb', line 94

def before_create
  self.created_at ||= Time.now
  super
end

#init_with(coder) ⇒ Object



112
113
114
115
116
117
118
# File 'lib/story_teller/inform/relational/link.rb', line 112

def init_with(coder)
  LinkMethods.each do |method_name|
    method_symbol = format(MethodWriterTemplate, method_name: method_name).to_sym
    self.send(method_symbol, coder[method_name]) if self.respond_to? method_symbol
  end
  self
end

#to_sObject



104
105
106
# File 'lib/story_teller/inform/relational/link.rb', line 104

def to_s
  format(LinkTemplate, link_name: name, to_name: to&.name, to_identity: to&.identity)
end