Class: Speq::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/speq/values.rb,
lib/speq/string_fmt.rb

Overview

Carries expression context for evaluation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject: nil, message: nil, arguments: nil) ⇒ Context

Returns a new instance of Context.



87
88
89
90
91
# File 'lib/speq/values.rb', line 87

def initialize(subject: nil, message: nil, arguments: nil)
  @subject = subject
  @message = message
  @arguments = arguments
end

Instance Attribute Details

#argumentsObject

Returns the value of attribute arguments.



85
86
87
# File 'lib/speq/values.rb', line 85

def arguments
  @arguments
end

#messageObject

Returns the value of attribute message.



85
86
87
# File 'lib/speq/values.rb', line 85

def message
  @message
end

#subjectObject

Returns the value of attribute subject.



85
86
87
# File 'lib/speq/values.rb', line 85

def subject
  @subject
end

Instance Method Details

#evaluateObject



105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/speq/values.rb', line 105

def evaluate
  obj = subject&.value
  msg = message&.value
  args = arguments&.args
  block = arguments&.block

  val = get_value(obj, msg, args, block)

  SomeValue.new(val)
rescue StandardError => e
  SomeValue.new(e)
end

#get_value(obj, msg, args, block) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
# File 'lib/speq/values.rb', line 118

def get_value(obj, msg, args, block)
  if !msg
    obj
  elsif !args
    obj&.public_send(msg) || send(msg)
  elsif !block
    obj&.public_send(msg, *args) || send(msg, *args)
  else
    obj&.public_send(msg, *args, &block) || send(msg, *args, &block)
  end
end

#merge(context) ⇒ Object



93
94
95
# File 'lib/speq/values.rb', line 93

def merge(context)
  Context.new(**to_h.merge(context.to_h))
end

#to_hObject



97
98
99
100
101
102
103
# File 'lib/speq/values.rb', line 97

def to_h
  output = {}
  %i[subject message arguments].each do |val|
    output[val] = send(val) if send(val)
  end
  output
end

#to_sObject



86
87
88
89
90
91
# File 'lib/speq/string_fmt.rb', line 86

def to_s
  [arguments && !message ? "with #{arguments}" : nil,
   arguments && message ? "#{message}(#{arguments})" : message,
   message && subject ? 'on' : nil,
   subject].reject(&:nil?).join(' ')
end