Class: AirtableBaseBuilder::BaseBuilder

Inherits:
Thor::Group
  • Object
show all
Includes:
Thor::Actions
Defined in:
lib/airtable_base_builder/base_builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, csv, delete_file) ⇒ BaseBuilder

Returns a new instance of BaseBuilder.



9
10
11
12
13
# File 'lib/airtable_base_builder/base_builder.rb', line 9

def initialize(name, csv, delete_file)
  @name = name
  @csv = csv
  @delete_file = delete_file
end

Instance Method Details

#buildObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/airtable_base_builder/base_builder.rb', line 15

def build
  csv = CSV.read(@csv, headers: true)

  csv_errors = check_for_csv_errors(csv)
  if csv_errors
    say_error(csv_errors, color = :red)
    exit
  end

  table_names = csv.by_col["Table"].uniq
  fields = csv.each.map do |row|
    { table: row["Table"], name: row["Name"], type: row["Type"], primary: row["Primary"] }
  end

  atb = Airtable::Base.new(table_names, fields)
  response = Airtable::Client.new.post(params: {
    name: @name,
    workspaceId: Config.new.workspace_id,
    tables: atb.tables
  })

  if response["errors"]
    say_error("There were errors creating the base:", color = :red)
    say_error(response["errors"].join("\n"), color = :red)
  else
    say("Base created successfully!", color = :green)
    base_link = set_color("https://airtable.com/#{response.body["id"]}", :blue, :bold)
    say("You can view it here: #{base_link}")
  end

  File.delete(@csv) if @delete_file
end

#check_for_csv_errors(csv) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/airtable_base_builder/base_builder.rb', line 48

def check_for_csv_errors(csv)
  return "CSV must have a 'Table' column defining the Table each field should be in" unless
    csv.headers.include?("Table")
  return "CSV must have a 'Name' column defining the Name of each field" unless
    csv.headers.include?("Name")
  return "CSV must have a 'Type' column defining the Type of field each should be" unless
    csv.headers.include?("Type")
end