Class: Flunky::Snapshot

Inherits:
Object
  • Object
show all
Defined in:
lib/flunky/snapshot.rb

Overview

A reduced, model-readable view of the current page: the page’s url and title plus the list of elements the agent can act on, each carrying its ref.

Constant Summary collapse

JS_PATH =
File.expand_path("js/snapshot.js", __dir__)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, title:, elements:) ⇒ Snapshot

Returns a new instance of Snapshot.



34
35
36
37
38
# File 'lib/flunky/snapshot.rb', line 34

def initialize(url:, title:, elements:)
  @url = url
  @title = title
  @elements = elements
end

Instance Attribute Details

#elementsObject (readonly)

Returns the value of attribute elements.



9
10
11
# File 'lib/flunky/snapshot.rb', line 9

def elements
  @elements
end

#titleObject (readonly)

Returns the value of attribute title.



9
10
11
# File 'lib/flunky/snapshot.rb', line 9

def title
  @title
end

#urlObject (readonly)

Returns the value of attribute url.



9
10
11
# File 'lib/flunky/snapshot.rb', line 9

def url
  @url
end

Class Method Details

.capture(driver, max_elements: Flunky.configuration.max_elements) ⇒ Object

Run the snapshot script against a live driver and wrap the result.



12
13
14
15
16
# File 'lib/flunky/snapshot.rb', line 12

def self.capture(driver, max_elements: Flunky.configuration.max_elements)
  driver.evaluate("window.__AI_MAX__ = #{Integer(max_elements)}")
  data = driver.evaluate(script)
  from_h(data)
end

.from_h(data) ⇒ Object

Build a Snapshot from a plain hash (string or symbol keys). Handy for the capture path and for testing without a browser.



20
21
22
23
# File 'lib/flunky/snapshot.rb', line 20

def self.from_h(data)
  h = symbolize(data)
  new(url: h[:url], title: h[:title], elements: (h[:elements] || []).map { |e| symbolize(e) })
end

.scriptObject



25
26
27
# File 'lib/flunky/snapshot.rb', line 25

def self.script
  @script ||= File.read(JS_PATH)
end

Instance Method Details

#to_hObject



48
49
50
# File 'lib/flunky/snapshot.rb', line 48

def to_h
  { url: url, title: title, elements: elements }
end

#to_promptObject

Compact block the model reads. Numbered refs map straight to the integers tools expect, so the model can copy a number into a click/type call.



42
43
44
45
46
# File 'lib/flunky/snapshot.rb', line 42

def to_prompt
  lines = ["PAGE: #{title} (#{url})", "ELEMENTS:"]
  lines.concat(elements.map { |el| element_line(el) })
  lines.join("\n")
end