Homevideo

%w(httparty nokogiri ./homevideo.rb).map(&method(:require))

def go_web
  puts 'fetching from internet...'
  url   = %(http://www.guldpris.nu)
  xpath = %(//*[@id="ratePreUnitTwoSEK"])
  
  Nokogiri::HTML(HTTParty.get(url).body).xpath(xpath).map {|i|
    i[:value]
  }
end

# This is how the Yeger-class can be used ...
yeg = Yager.new(:data, 4.hours)
yeg.value(go_web[0]) if yeg.outdated?

puts yeg.value

Found VCR a bit.. too much.. so I wrote ‘homevideo’.
When initialized you set the filename (as symbol) and the time-limit in seconds (default 10.minuntes).

Time-stamp and limit is read from yaml-file. If time-stamp is passed limit, method outdated? returns true (and the new values are stored).


HomeVideo

require 'yaml'
require 'date'

class Integer
  def minute      = ( self * 60 )
  def hour        = ( self.minute * 60 )
  def day         = ( self.hour * 24 )
  def week        = ( self.day * 7 )
  
  alias :minutes  :minute
  alias :hours    :hour
  alias :days     :day
  alias :weeks    :week
end

class Yager
  def initialize(sym, limit = 10.minutes)
    @file, @limit = '%s.yaml' % sym, limit
    @data = (File.file?(@file) ?
      YAML.unsafe_load_file(@file) : {dt: nil, limit: nil})
  end

  def method_missing(name, value = nil)
    value.nil? ? ( @data[name] ? @data[name] : nil ) : ( @data[name] = value )
  end
  
  def write
    @data[:dt], @data[:limit] = DateTime.now, @limit
    File.open(@file, 'w') {|f| f.write @data.to_yaml}
  end

  def outdated?
    self.write if (od = ((DateTime.now - @data[:dt]) * 86400).to_i > @data[:limit])
    od
  end
end

data

---
:dt: !ruby/object:DateTime 2024-06-23 14:12:29.660378498 +02:00
:limit: 14400
:value: '798.64'