Class: Redstruct::Types::Script

Inherits:
Base
  • Object
show all
Defined in:
lib/redstruct/types/script.rb

Overview

It is recommended you flush your script cache on the redis server every once in a while

Constant Summary collapse

ERROR_MESSAGE_PREFIX =
'NOSCRIPT'.freeze

Instance Attribute Summary collapse

Attributes inherited from Base

#key

Instance Method Summary collapse

Methods inherited from Base

#to_h, #with

Methods included from Utils::Inspectable

#inspect, #to_s

Constructor Details

#initialize(script:, **options) ⇒ Script

Returns a new instance of Script.

Raises:



12
13
14
15
16
17
18
# File 'lib/redstruct/types/script.rb', line 12

def initialize(script:, **options)
  script = script&.strip
  raise(Redstruct::Error, 'No source script given') if script.empty?

  super(**options)
  self.script = script
end

Instance Attribute Details

#script::String

Returns The Lua script to evaluate.

Returns:

  • (::String)

    The Lua script to evaluate



10
11
12
# File 'lib/redstruct/types/script.rb', line 10

def script
  @script
end

Instance Method Details

#eval(keys:, argv:) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/redstruct/types/script.rb', line 40

def eval(keys:, argv:)
  keys = [keys] unless keys.is_a?(Array)
  argv = [argv] unless argv.is_a?(Array)
  self.connection.evalsha(self.sha1, keys, argv)
rescue Redis::CommandError => err
  raise unless err.message.start_with?(ERROR_MESSAGE_PREFIX)
  self.connection.eval(@script, keys, argv)
end

#exists?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/redstruct/types/script.rb', line 31

def exists?
  return self.connection.script(:exists, self.sha1)
end

#inspectable_attributesObject

:nocov:



50
51
52
# File 'lib/redstruct/types/script.rb', line 50

def inspectable_attributes
  return super.merge(sha1: self.sha1, script: @script.slice(0, 20))
end

#loadObject



35
36
37
38
# File 'lib/redstruct/types/script.rb', line 35

def load
  @sha1 = self.connection.script(:load, @script)
  return @sha1
end

#sha1Object



25
26
27
28
29
# File 'lib/redstruct/types/script.rb', line 25

def sha1
  return @sha1 ||= begin
    Digest::SHA1.hexdigest(@script)
  end
end