Class: Cloudflare::ScheduledEvent

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudflare_workers/scheduled.rb

Overview

Wrapper around the JS ScheduledEvent. The Workers runtime gives us:

event.cron          — String, e.g. '*/5 * * * *'
event.scheduledTime — Number (millis-since-epoch)
event.type          — String, always 'scheduled'
event.waitUntil(p)  — same shape as ctx.waitUntil(p)

We surface these as Ruby idioms so user code never needs backticks.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cron:, scheduled_time:, type: 'scheduled', raw: nil) ⇒ ScheduledEvent

Returns a new instance of ScheduledEvent.



47
48
49
50
51
52
# File 'lib/cloudflare_workers/scheduled.rb', line 47

def initialize(cron:, scheduled_time:, type: 'scheduled', raw: nil)
  @cron = cron.to_s.freeze
  @scheduled_time = scheduled_time
  @type = type.to_s.freeze
  @raw = raw
end

Instance Attribute Details

#cronObject (readonly)

Returns the value of attribute cron.



45
46
47
# File 'lib/cloudflare_workers/scheduled.rb', line 45

def cron
  @cron
end

#rawObject (readonly)

Returns the value of attribute raw.



45
46
47
# File 'lib/cloudflare_workers/scheduled.rb', line 45

def raw
  @raw
end

#scheduled_timeObject (readonly)

Returns the value of attribute scheduled_time.



45
46
47
# File 'lib/cloudflare_workers/scheduled.rb', line 45

def scheduled_time
  @scheduled_time
end

#typeObject (readonly)

Returns the value of attribute type.



45
46
47
# File 'lib/cloudflare_workers/scheduled.rb', line 45

def type
  @type
end

Class Method Details

.from_js(js_event) ⇒ Object

Build a ScheduledEvent from the native JS event. ‘js_event` may be nil during smoke tests; in that case the caller passes the cron / scheduled_time via the keyword form above.

JS undefined / null guards are written in JS land instead of delegating to ‘nil?` because Opal doesn’t always coerce a bare JS undefined into Ruby’s nil — calling ‘.nil?` on it raises TypeError.



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/cloudflare_workers/scheduled.rb', line 62

def self.from_js(js_event)
  return new(cron: '', scheduled_time: Time.now) if `#{js_event} == null`

  cron      = `(#{js_event}.cron == null ? '' : String(#{js_event}.cron))`
  type      = `(#{js_event}.type == null ? 'scheduled' : String(#{js_event}.type))`
  has_sched = `(#{js_event}.scheduledTime != null)`
  sched_t   = if has_sched
                sched_ms = `Number(#{js_event}.scheduledTime)`
                Time.at(sched_ms.to_f / 1000.0)
              else
                Time.now
              end

  new(cron: cron, scheduled_time: sched_t, type: type, raw: js_event)
end

Instance Method Details

#to_hObject



78
79
80
81
82
83
84
# File 'lib/cloudflare_workers/scheduled.rb', line 78

def to_h
  {
    'cron'           => cron,
    'scheduled_time' => scheduled_time.to_i,
    'type'           => type
  }
end