Class: Aspen::CLI::Commands::BuildSteps::DownloadAttachedResources

Inherits:
BuildStep
  • Object
show all
Defined in:
lib/aspen/cli/commands/build_steps.rb

Instance Method Summary collapse

Methods inherited from BuildStep

#config, #manifest

Instance Method Details

#cache_expired?Boolean

Returns:

  • (Boolean)


61
62
63
64
65
66
67
68
# File 'lib/aspen/cli/commands/build_steps.rb', line 61

def cache_expired?
  if manifest["cache_seconds"]
    last = File.read('build/last-download').to_i       # Last download time
    time_since_last_download = (Time.now - last).to_i  # Time since last download
    threshhold = manifest['cache_seconds'].to_i        # Cache threshhold
    time_since_last_download > threshhold
  end
end

#callObject



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/aspen/cli/commands/build_steps.rb', line 43

def call(*)
  super
  return false unless manifest['attached']
  check_for_save_file
  if cache_expired?
    download
    update_save_file!
  else
    puts "----> Skipping download, cache is still good."
  end
end

#check_for_save_fileObject



55
56
57
58
59
# File 'lib/aspen/cli/commands/build_steps.rb', line 55

def check_for_save_file
  unless @files.exist?('build/last-download')
    File.open('build/last-download', 'w') { |f| f << 0 }
  end
end

#downloadObject



74
75
76
77
78
79
80
81
82
# File 'lib/aspen/cli/commands/build_steps.rb', line 74

def download
  puts '----> Downloading attached resources'
  manifest['attached'].each do |resource|
    puts "      > Downloading #{resource["name"]} (#{resource["source"].capitalize})"
    case resource["source"]
    when "airtable" then download_airtable_resource(resource)
    end
  end
end

#download_airtable_resource(resource) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/aspen/cli/commands/build_steps.rb', line 84

def download_airtable_resource(resource)
  client = Airtable::Client.new(config.dig('airtable', 'api_key'))
  table = client.table(resource['app_id'], resource['table'])
  out_path = "src/#{resource["name"].downcase.gsub(" ", "_")}.csv"
  CSV.open(out_path, 'w') do |file|
    columns = Array(resource['columns'])
    file << columns
    table.records.each do |record|
      file << columns.map { |col| record[col] }
    end
  end
end

#update_save_file!Object



70
71
72
# File 'lib/aspen/cli/commands/build_steps.rb', line 70

def update_save_file!
  File.open('build/last-download', 'w') { |f| f << Time.now.to_i }
end