airbased 0.0.1.pre.alpha

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 81a62f187752dc1b866554329511e2f03904917caa67e85e16b6a03bc0a063fa
4
+ data.tar.gz: a7ed8eb8455da778e511aea3385fe603700b2aa837f3a57766594f01156013af
5
+ SHA512:
6
+ metadata.gz: a053f69c8b323542f072155b8e537d61fe1f52ff027310a9706671e28202b7e8559d847de7a35d3bd0fe70bf2d11bb35a17fa27d6b467a3df5db072fc43f0910
7
+ data.tar.gz: b4fbf93726016e55e80c932cb34d9c0a7db9644e811ad3b9ad4b93008f8689e09aaf216c5dba9d1bb8d01ef91fba7a6d9b70438fe2149e1ee4f659c303073653
data/.rubocop.yml ADDED
@@ -0,0 +1,15 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+ SuggestExtensions: false
4
+ NewCops: enable
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/StringLiteralsInInterpolation:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Layout/LineLength:
15
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1 @@
1
+ ## [Unreleased]
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at 43987794+alokhmutov@users.noreply.github.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Aleks Lokhmutov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # Airbased
2
+
3
+ Ruby interface to the Airtable’s API.
4
+
5
+ ## Note
6
+
7
+ The library is in early development, so breaking changes are possible. It implements all records API methods (including
8
+ batch operations), except Sync CSV data and attachment upload.
9
+
10
+ Feedback and contributions are most welcome!
11
+
12
+ ## Start using Airbased
13
+
14
+ # Install the gem.
15
+
16
+ `gem install airbased --pre`
17
+
18
+ Or in a Gemfile:
19
+
20
+ `gem 'airbased', '0.0.1-alpha'`
21
+
22
+ # Define an API key, then define a base.
23
+
24
+ ```ruby
25
+ Airbased.api_key = "patxxx"
26
+
27
+ # define a new base
28
+ MyBase = Airbased::Base.new("appxxxxxxxxxxxxxx")
29
+
30
+ # define a table from the base's schema
31
+ MyTable = MyBase["Table 1"] # you can use table name or id
32
+
33
+ # ... or though an ad-hoc definition
34
+ MyTable = Airbased.table(Airbased.api_key, "appxxxxxxxxxxxxxx", "tblxxxxxxxxxxxxxx")
35
+
36
+ # create a record
37
+ new_record = MyTable.create({"Name" => "a new name"})
38
+
39
+ # ... or many records at once, Airbased will take care of batching!
40
+ fields = [{ "Name" => "a new name 2" }, {"Name" => "a new name 3"}]
41
+ records = MyTable.create(fields)
42
+
43
+ # delete a record
44
+ new_record.delete
45
+
46
+ # fetch records
47
+ records = MyTable.all
48
+
49
+ # update records
50
+ record = records[0]
51
+ record["Name"] = "newer name"
52
+ record.save
53
+
54
+ # upsert records
55
+ records = MyTable.upsert(fields, merge_on: ["Name"])
56
+
57
+ # if something goes wrong...
58
+ Airbased.debug = true
59
+ # will write requests info into stdout
60
+ ```
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ task default: %i[test]
data/airbased.gemspec ADDED
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/airbased/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "airbased"
7
+ spec.version = Airbased::VERSION
8
+ spec.authors = ["Aleks Lokhmutov"]
9
+ spec.email = ["43987794+alokhmutov@users.noreply.github.com"]
10
+
11
+ spec.summary = "Ruby interface to the Airtable’s API."
12
+ spec.homepage = "https://github.com/alokhmutov/airbased"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 3.0.0"
15
+
16
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
17
+
18
+ spec.metadata["homepage_uri"] = spec.homepage
19
+ spec.metadata["source_code_uri"] = "https://github.com/alokhmutov/airbased"
20
+ spec.metadata["changelog_uri"] = "https://github.com/alokhmutov/airbased/CHANGELOG.md"
21
+
22
+ # Specify which files should be added to the gem when it is released.
23
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
24
+ spec.files = Dir.chdir(__dir__) do
25
+ `git ls-files -z`.split("\x0").reject do |f|
26
+ (File.expand_path(f) == __FILE__) ||
27
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile])
28
+ end
29
+ end
30
+
31
+ spec.require_paths = ["lib"]
32
+
33
+ # Dependencies
34
+ spec.add_dependency "httparty"
35
+
36
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "httparty"
4
+
5
+ module Airbased
6
+ # The Airtable class is an HTTParty client for Airtable API.
7
+ # It handles headers (incl. authorization), rate limits, error handling,
8
+ # and basic request/response parsing.
9
+ class Airtable
10
+ include HTTParty
11
+ include Errors
12
+ base_uri 'https://api.airtable.com/v0/'
13
+ headers 'User-Agent' => "Airbased Ruby Gem/#{Airbased::VERSION}",
14
+ 'Content-Type' => 'application/json'
15
+
16
+ class << self
17
+ attr_accessor :requests
18
+
19
+ def with_rate_limit
20
+ # Keep only the timestamps within the last second
21
+ @requests.reject! { |timestamp| Time.now - timestamp > 1 }
22
+
23
+ if @requests.size >= 5
24
+ sleep_time = 1 - (Time.now - @requests.first)
25
+ sleep(sleep_time) if sleep_time.positive?
26
+ end
27
+
28
+ response = yield
29
+
30
+ request_time =
31
+ begin
32
+ Time.parse(response.headers["date"])
33
+ rescue
34
+ Time.now
35
+ end
36
+
37
+ @requests << request_time
38
+
39
+ response
40
+ end
41
+
42
+ # sets an authorization header with a custom, if passed, or general api key
43
+ def authorization(options)
44
+ api_key = (options.dig(:api_key) && options.delete(:api_key)) || Airbased.api_key
45
+ options[:headers] ||= { Authorization: "Bearer #{api_key}" }
46
+ end
47
+
48
+ # formating request body to json
49
+ def process_data(data)
50
+ processed_data = data.compact
51
+ processed_data = deep_transform_keys(processed_data) { |key| from_snake(key) }
52
+
53
+ JSON.dump(processed_data)
54
+ end
55
+
56
+ # formating response body to be accessible with conventional snake-case symbols
57
+ def process_result(result)
58
+ deep_transform_keys(result) { |key| to_snake(key) }
59
+ end
60
+
61
+ # recursively transforms keys of a payload, except for field names
62
+ def deep_transform_keys(obj, &block)
63
+ case obj
64
+ when Hash
65
+ obj.each_with_object({}) do |(key, value), result|
66
+ new_key = yield(key.to_s).to_sym
67
+ result[new_key] = if key.to_s == "fields"
68
+ value
69
+ else
70
+ deep_transform_keys(value, &block)
71
+ end
72
+ end
73
+ when Array
74
+ obj.map { |e| deep_transform_keys(e, &block) }
75
+ else
76
+ obj
77
+ end
78
+ end
79
+
80
+ def to_snake(str)
81
+ str.gsub(/([A-Z])/, '_\1').downcase
82
+ end
83
+
84
+ def from_snake(str)
85
+ str.gsub(/_(.)/) { Regexp.last_match(1).upcase }
86
+ end
87
+ end
88
+
89
+ @requests = []
90
+
91
+ # processing a custom api key and debug options, formatting data, then making request
92
+ [:get, :post, :patch, :put, :delete].each do |method|
93
+ define_singleton_method(method) do |path, data = nil, options = {}, &block|
94
+ # setting API key in request
95
+ authorization(options)
96
+
97
+ # formatting data to json
98
+ options[:body] = process_data(data) if data
99
+
100
+ # would output request info if enabled
101
+ options[:debug_output] = $stdout if Airbased.debug
102
+
103
+ response = with_error_handling do
104
+ with_rate_limit do # processes rate limits
105
+ super(path, options, &block) # then delegates to the HTTParty method
106
+ end
107
+ end
108
+ process_result(response.parsed_response)
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ class Airtable
5
+ module Errors
6
+ class AirtableError < StandardError; end
7
+
8
+ class BadRequest < AirtableError; end
9
+ class Unauthorized < AirtableError; end
10
+ class Forbidden < AirtableError; end
11
+ class NotFound < AirtableError; end
12
+ class PayloadTooLarge < AirtableError; end
13
+ class InvalidRequest < AirtableError; end
14
+ class TooManyRequests < AirtableError; end
15
+ class InternalServerError < AirtableError; end
16
+ class BadGateway < AirtableError; end
17
+ class ServiceUnavailable < AirtableError; end
18
+
19
+ def Airtable.with_error_handling
20
+ response = yield
21
+
22
+ case response.code
23
+ when 200
24
+ response
25
+ when 400
26
+ raise BadRequest, response["error"]["message"]
27
+ when 401
28
+ raise Unauthorized, response["error"]["message"]
29
+ when 403
30
+ raise Forbidden, response["error"]["message"]
31
+ when 404
32
+ raise NotFound, response["error"]["message"]
33
+ when 413
34
+ raise PayloadTooLarge, response["error"]["message"]
35
+ when 422
36
+ raise InvalidRequest, response["error"]["message"]
37
+ when 429
38
+ raise TooManyRequests, response["error"]["message"]
39
+ when 500
40
+ raise InternalServerError, response["error"]["message"]
41
+ when 502
42
+ raise BadGateway, response["error"]["message"]
43
+ when 503
44
+ raise ServiceUnavailable, response["error"]["message"]
45
+ end
46
+ rescue Net
47
+ puts "retrying"
48
+ retry
49
+ rescue BadGateway
50
+ puts "retrying bad gateway"
51
+ retry
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,51 @@
1
+ module Airbased
2
+ # The `Airbased::Base` class represents an Airtable base and
3
+ # provides methods to interact with the base.
4
+ #
5
+ # @attr_accessor [String] :base_id the unique identifier for the base
6
+ # @attr_accessor [Array<Table>] :tables the tables associated with the base
7
+ # @attr_accessor [String] :api_key the API key used for authentication
8
+ class Base
9
+ attr_accessor :base_id, :tables, :api_key
10
+
11
+ # Initializes a new instance of the Base class.
12
+ #
13
+ # @param base_id [String] the unique identifier for the base
14
+ # @param api_key [String, nil] the API key used for authentication (optional)
15
+ def initialize(base_id, api_key: nil)
16
+ @base_id = base_id
17
+ @api_key = api_key || Airbased.api_key
18
+ end
19
+
20
+ # Fetches the schema of the Airtable base and updates the @tables variable.
21
+ #
22
+ # @return [Array<Airbased::Table>] the tables associated with the base
23
+ def schema
24
+ response = Airtable.get("/meta/bases/#{@base_id}/tables")
25
+ @tables = response[:tables].map { |table| Airbased::Table.new(**table, base_id: @base_id) }
26
+ end
27
+
28
+ # Retrieves a table from the base by its id or name. Makes an API request to fetch the schema if tables have not been loaded yet.
29
+ #
30
+ # @param table_key [String] the key of the table to retrieve. This can be either the table's ID or name.
31
+ # @return [Airbased::Table, nil] the table with the specified key, or nil if no such table exists.
32
+ def [](table_key)
33
+ schema if @tables.nil?
34
+ table = @tables.find { |table| table.id == table_key || table.name == table_key }
35
+ raise Airbased::Error.new("Table with '#{table_key}' not found in schema") if table.nil?
36
+
37
+ table
38
+ end
39
+
40
+ # Creates a new table in the Airtable base.
41
+ #
42
+ # @param name [String] the name of the new table
43
+ # @param fields [Array<Hash>] the fields of the new table
44
+ # @param description [String, nil] an optional description for the new table
45
+ # @return [Airbased::Table] the newly created table
46
+ def create_table(name:, fields:, description: nil)
47
+ response = Airbased::Airtable.post("/meta/bases/#{@base_id}/tables", { name:, fields:, description: })
48
+ Table.new(**response, base_id: @base_id)
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ class Record
5
+ # API methods for Airtable records.
6
+ module Persistence
7
+ # Deletes a record from an Airtable table.
8
+ #
9
+ # @return a frozen [Record] of the deleted record
10
+ def delete
11
+ Airtable.delete("/#{@table.base_id}/#{@table.table_key}/#{@id}", nil, table.options)
12
+ @destroyed = true
13
+ freeze
14
+ self
15
+ end
16
+
17
+ # Updates the fields of a record in an Airtable table.
18
+ #
19
+ # @param fields [Hash] The fields to update.
20
+ # @param overwrite [Boolean] Whether to overwrite the existing fields (default: false).
21
+ # @param typecast [Boolean] Whether to enable typecasting for the fields (default: false).
22
+ # @return [Record] The updated record.
23
+ def update(fields, overwrite: false, typecast: false)
24
+ response = if overwrite
25
+ Airtable.put("/#{@table.base_id}/#{@table.table_key}/#{@id}", { fields:, typecast: }, table.options)
26
+ else
27
+ Airtable.patch("/#{@table.base_id}/#{@table.table_key}/#{@id}", { fields:, typecast: }, table.options)
28
+ end
29
+ self.fields = response[:fields]
30
+ self
31
+ end
32
+
33
+ # Saves the record to the Airtable table.
34
+ #
35
+ # @param typecast [Boolean] Whether to enable typecasting for the fields (default: false).
36
+ # @return [Record] Returns the saved record.
37
+ def save(typecast: false)
38
+ if new_record?
39
+ record = @table.create(@fields, typecast:)
40
+ self.fields = record.fields
41
+ @created_time = record.created_time
42
+ @id = record.id
43
+ self
44
+ else
45
+ update(@fields, typecast:)
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ # The Record class represents an individual record within an Airtable table.
5
+ class Record
6
+ include Record::Persistence
7
+ attr_reader :id, :fields, :created_time, :table, :destroyed
8
+
9
+ # Initializes a new Record instance.
10
+ #
11
+ # @param id [String] The ID of the record.
12
+ # @param fields [Hash] The fields of the record.
13
+ # @param created_time [String] The creation time of the record.
14
+ # @param table [Table] The table object to which the record belongs, expected to have `base_id` and `id` attributes.
15
+ def initialize(fields:, table:, id: nil, created_time: nil)
16
+ @id = id
17
+ @created_time = Time.parse(created_time) if created_time
18
+ self.fields = fields
19
+ @table = table
20
+ end
21
+
22
+ # Overwrites the fields of the record, transforming the keys to strings.
23
+ #
24
+ # @param fields [Hash] The fields to set, with keys that will be transformed to strings.
25
+ # @return [void]
26
+ def fields=(fields)
27
+ @fields = Hash.new { |hash, key| hash[key.to_s] if key.is_a?(Symbol) }
28
+ fields.each do |key, value|
29
+ @fields[key.to_s] = value
30
+ end
31
+ end
32
+
33
+ # Assigns new values to the record's fields, transforming the keys to strings.
34
+ #
35
+ # @param new_fields [Hash] The new values to assign to the record's fields.
36
+ # @return [void] Always returns nil.
37
+ def assign(new_fields)
38
+ @fields.update(new_fields.transform_keys(&:to_s))
39
+ nil
40
+ end
41
+
42
+ # Checks if the record is new (i.e., does not have an id).
43
+ #
44
+ # @return [Boolean] True if the record is new, false otherwise.
45
+ def new_record?
46
+ !id
47
+ end
48
+
49
+ # Checks if the record has been destroyed.
50
+ #
51
+ # @return [Boolean] True if the record is destroyed, false otherwise.
52
+ def destroyed?
53
+ !!destroyed
54
+ end
55
+
56
+ # Retrieves the value of the specified field.
57
+ #
58
+ # @param field [String, Symbol] The field name to retrieve the value for.
59
+ # @return [Object] The value of the specified field.
60
+ def [](field)
61
+ @fields[field]
62
+ end
63
+
64
+ # Sets the value of the specified field.
65
+ #
66
+ # @param key [String, Symbol] The field name to set the value for.
67
+ # @param value [Object] The value to set for the specified field.
68
+ # @return [void]
69
+ def []=(key, value)
70
+ @fields[key.to_s] = value
71
+ end
72
+
73
+ # Compares the current record with another object for equality.
74
+ #
75
+ # @param other [Object] The object to compare with.
76
+ # @return [Boolean] True if the other object is a Record and has the same id and fields, false otherwise.
77
+ def ==(other)
78
+ other.is_a?(Record) && id == other.id && fields == other.fields
79
+ end
80
+
81
+ # Converts the record to a hash representation.
82
+ #
83
+ # @return [Hash] A hash containing the record's id, fields, created_time, table key, and base id.
84
+ def to_h
85
+ {
86
+ id: @id,
87
+ fields: @fields,
88
+ created_time: @created_time,
89
+ table: @table.table_key,
90
+ base: @table.base_id
91
+ }
92
+ end
93
+
94
+ def to_api_hash
95
+ {
96
+ "id" => @id,
97
+ "fields" => @fields
98
+ }.compact
99
+ end
100
+
101
+ # Generates a link to the record in the Airtable table.
102
+ #
103
+ # @raise [Airbased::Error] If the table does not have an id (name only won't work in this case), or if a record does not have an id.
104
+ # @return [String] The URL link to the record.
105
+ def link
106
+ raise Airbased::Error.new("Record's table needs a table id to generate a link") unless @table.id
107
+ raise Airbased::Error.new("Record does not have an id to generate a link, it must be saved first") unless @id
108
+
109
+ "https://airtable.com/#{@table.base_id}/#{@table.id}/#{@id}"
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ class Table
5
+ # Persistence API methods for Airtable tables
6
+ module Persistence
7
+ include Airbased::Validation
8
+ # Creates new records in the Airtable base.
9
+ #
10
+ # The records parameter can either be a single hash or an array of hashes, where each hash represents a record.
11
+ #
12
+ # @param record_or_records [Hash, Array<Hash>] The records to be created. Must be a hash or an array of hashes.
13
+ # @param typecast [Boolean] (false) Whether to automatically typecast values. Defaults to false.
14
+ # @return [Record, Array<Record>] The created record(s). Returns a single record if one record is created, otherwise returns an array of records.
15
+ def create(record_or_records, typecast: false)
16
+ records = record_or_records.is_a?(Hash) ? [record_or_records.dup] : record_or_records.dup
17
+ records = hash_or_record_to_hash(records, id_required: false)
18
+
19
+ returned_records = records.each_slice(10).map do |slice|
20
+ create_slice(slice, typecast:)
21
+ end.flatten
22
+ returned_records.size == 1 ? returned_records.first : returned_records
23
+ end
24
+
25
+ # Updates existing records in the Airtable base.
26
+ #
27
+ # The records parameter can either be an array of Record objects or an array of hashes, where each hash represents a record.
28
+ #
29
+ # @param records [Array<Record, Hash>] The records to be updated. Must be an array of Record objects or hashes.
30
+ # @param overwrite [Boolean] (false) Whether to overwrite existing records. If true, will clear the fields not in the request. Defaults to false.
31
+ # @param typecast [Boolean] (false) Whether to automatically typecast values. Defaults to false.
32
+ # @return [Array<Record>] The updated records.
33
+ # @raise [Airbased::Error] If a record is missing an ID, since it is mandatory for update.
34
+ def update(records, overwrite: false, typecast: false)
35
+ record_hashes = hash_or_record_to_hash(records, id_required: true)
36
+
37
+ record_hashes.each_slice(10).flat_map do |slice|
38
+ update_slice(slice, overwrite:, typecast:)
39
+ end
40
+ end
41
+
42
+ # Upserts records in the Airtable base.
43
+ #
44
+ # The records parameter can either be an array of Record objects or an array of hashes, where each hash represents a record.
45
+ #
46
+ # @param records [Array<Record, Hash>] The records to be upserted. Must be an array of Record objects or hashes.
47
+ # @param merge_on [Array<String>] The fields to merge on. Must be an array of 1 to 3 field names.
48
+ # @param overwrite [Boolean] (false) Whether to overwrite existing records. If true, will clear the fields not in the request. Defaults to false.
49
+ # @param typecast [Boolean] (false) Whether to automatically typecast values. Defaults to false.
50
+ # @raise [Airbased::Error] If merge_on is not an array of 1 to 3 field names.
51
+ def upsert(records, merge_on:, overwrite: false, typecast: false)
52
+ raise Airbased::Error.new("merge_on must be an array of 1 to 3 field names") unless
53
+ merge_on.is_a?(Array) && merge_on.size.between?(1, 3)
54
+
55
+ record_hashes = hash_or_record_to_hash(records)
56
+
57
+ record_hashes.each_slice(10).flat_map do |slice|
58
+ upsert_slice(slice, merge_on:, overwrite:, typecast:)
59
+ end
60
+ end
61
+
62
+ # Deletes records from the Airtable base.
63
+ #
64
+ # The records_or_record_ids parameter can either be an array of Record objects or an array of record IDs.
65
+ #
66
+ # @param records_or_record_ids [Array<Record, String>] The records or record IDs to be deleted.
67
+ # @return [Array<Record>] The IDs of the deleted records.
68
+ # @raise [Airbased::Error] if an element in the array is neither a Record object nor a String.
69
+ def delete(records_or_record_ids)
70
+ responses = records_or_record_ids.each_slice(10).flat_map do |slice|
71
+ ids = slice.map do |record|
72
+ if record.is_a?(Record)
73
+ record.id
74
+ elsif record.is_a?(String)
75
+ record
76
+ else
77
+ raise Airbased::Error.new("You need to pass an array of records or a record ids but #{record} is a #{record.class}.")
78
+ end
79
+ end
80
+ Airtable.delete("/#{@base_id}/#{table_key}?" + URI.encode_www_form("records[]": ids), options)[:records]
81
+ end
82
+ responses.map { |r| r[:id] }
83
+ end
84
+
85
+ private
86
+
87
+ # Creates new records in the Airtable base in slices of up to 10 records
88
+ # from an array of hashes, where each hash represents a record.
89
+ #
90
+ # @param slice [Array<Hash>] The slice of records to be created. Each record is represented as a hash.
91
+ # @return [Array<Record>] An array of Record objects created from the response of the Airtable API.
92
+ def create_slice(slice, typecast:)
93
+ records = Airtable.post("/#{@base_id}/#{table_key}", { records: slice, typecast: }, options)[:records]
94
+ records.map do |record|
95
+ Record.new(id: record[:id], fields: record[:fields], created_time: record[:created_time], table: self)
96
+ end
97
+ end
98
+
99
+ def update_slice(slice, overwrite:, typecast:)
100
+ records = if overwrite
101
+ Airtable.put("/#{@base_id}/#{table_key}", { records: slice, typecast: }, options)[:records]
102
+ else
103
+ Airtable.patch("/#{@base_id}/#{table_key}", { records: slice, typecast: }, options)[:records]
104
+ end
105
+
106
+ records.map do |record|
107
+ Record.new(id: record[:id], fields: record[:fields], created_time: record[:created_time], table: self)
108
+ end
109
+ end
110
+
111
+ def upsert_slice(slice, merge_on:, overwrite:, typecast:)
112
+ records = if overwrite
113
+ Airtable.put("/#{@base_id}/#{table_key}", { perform_upsert: { fields_to_merge_on: merge_on }, records: slice, typecast: }, options)[:records]
114
+ else
115
+ Airtable.patch("/#{@base_id}/#{table_key}", { perform_upsert: { fields_to_merge_on: merge_on }, records: slice, typecast: }, options)[:records]
116
+ end
117
+
118
+ records.map do |record|
119
+ Record.new(id: record[:id], fields: record[:fields], created_time: record[:created_time], table: self)
120
+ end
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ class Table
5
+ # Methods for querying tables.
6
+ module Query
7
+ # Fetches a specific record from an Airtable table.
8
+ #
9
+ # @param record_id [String] The ID of the record to retrieve.
10
+ # @return [Record] A record instance with the record data.
11
+ def find(record_id)
12
+ # TODO: cellFormat and returnFieldsByFieldId
13
+ response = Airtable.get("/#{@base_id}/#{table_key}/#{record_id}", nil, options)
14
+ Record.new(id: response[:id], fields: response[:fields], created_time: response[:created_time], table: self)
15
+ end
16
+ alias :get_record :find
17
+
18
+ # Fetches the first record from an Airtable table.
19
+ #
20
+ # @return [Record, nil] The first record if available, otherwise nil.
21
+ def first
22
+ all(page_size: 1, max_records: 1).first
23
+ end
24
+
25
+ def all(
26
+ offset: nil,
27
+ page_size: nil,
28
+ max_records: nil,
29
+ fields: nil,
30
+ view: nil,
31
+ sort: nil,
32
+ filter_by_formula: nil,
33
+ time_zone: nil,
34
+ user_locale: nil,
35
+ cell_format: nil,
36
+ return_fields_by_field_id: nil,
37
+ record_metadata: nil
38
+ )
39
+
40
+ # TODO: required params
41
+
42
+ records = []
43
+
44
+ loop do
45
+ result = records_page(
46
+ offset:, page_size:, max_records:, fields:, view:, sort:, filter_by_formula:,
47
+ time_zone:, user_locale:, cell_format:, return_fields_by_field_id:, record_metadata:
48
+ )
49
+
50
+ offset = result[:offset]
51
+ page_records = result[:records]
52
+ records.concat(page_records)
53
+ break if offset.nil?
54
+ end
55
+ records
56
+ end
57
+
58
+ private
59
+
60
+ def records_page(
61
+ offset: nil,
62
+ page_size: nil,
63
+ max_records: nil,
64
+ fields: nil,
65
+ view: nil,
66
+ sort: nil,
67
+ filter_by_formula: nil,
68
+ time_zone: nil,
69
+ user_locale: nil,
70
+ cell_format: nil,
71
+ return_fields_by_field_id: nil,
72
+ record_metadata: nil
73
+ )
74
+
75
+ response = Airtable.post("/#{@base_id}/#{table_key}/listRecords", {
76
+ offset:, page_size:, max_records:, fields:, view:, sort:, filter_by_formula:,
77
+ time_zone:, user_locale:, cell_format:, return_fields_by_field_id:, record_metadata:
78
+ }, options)
79
+ records = response[:records].map do |record|
80
+ Record.new(id: record[:id], fields: record[:fields], created_time: record[:created_time], table: self)
81
+ end
82
+
83
+ { offset: response[:offset], records: }
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ # Represents a table in the Airtable base, and provides a way to interact with it.
5
+ class Table
6
+ include Query
7
+ include Persistence
8
+
9
+ attr_accessor :id, :name, :base_id, :api_key, :fields, :primary_field_id, :views, :description
10
+
11
+ TABLE_MATCHER = /^tbl[[:alnum:]]+$/
12
+
13
+ # Initializes a new Table object.
14
+ #
15
+ # @param base_id [String] The ID of the base containing the table.
16
+ # @param id [String, nil] The ID of the table.
17
+ # @param name [String, nil] The name of the table.
18
+ # @param api_key [String, nil] The API key to access the table.
19
+ # @param fields [Array<Hash>, nil] The list of fields in the table.
20
+ # @param primary_field_id [String, nil] The ID of the primary field in the table.
21
+ # @param views [Array<Hash>, nil] The list of views in the table.
22
+ # @param description [String, nil] The description of the table.
23
+ #
24
+ # @raise [Airbased::Error] if both id and name are nil.
25
+ #
26
+ # @return [Airbased::Table] A new Table object.
27
+ def initialize(
28
+ base_id:,
29
+ id: nil,
30
+ name: nil,
31
+ api_key: nil,
32
+ fields: nil,
33
+ primary_field_id: nil,
34
+ views: nil,
35
+ description: nil
36
+ )
37
+ raise Airbased::Error.new("You need to pass an id or a name for the table") if id.nil? && name.nil?
38
+
39
+ @id = id
40
+ @name = name
41
+ @base_id = base_id
42
+ @fields = fields
43
+ @primary_field_id = primary_field_id
44
+ @views = views
45
+ @description = description
46
+
47
+ # only define api_key if passed specifically for this table, will otherwise use module's api key
48
+ @api_key = api_key if api_key
49
+ end
50
+
51
+ # Creates a new record instance associated with the table.
52
+ #
53
+ # @param fields [Hash] The fields of the new record.
54
+ # @return [Record] A new Record object with the provided fields and associated with the current table.
55
+ def new_record(fields:, id: nil, created_time: nil)
56
+ Record.new(fields:, id:, created_time:, table: self)
57
+ end
58
+
59
+ def table_key
60
+ @id || CGI.escape_uri_component(@name)
61
+ end
62
+
63
+ # A shortcut for a hash with a table's api key in requests.
64
+ #
65
+ # @return [Hash] Hash with API key, or with nil value if no special api key set for table.
66
+ def options
67
+ { api_key: }
68
+ end
69
+
70
+ # Airrecord-style shorthand table definition.
71
+ # Creates a new Table instance with the provided API key, base ID, and table key (table id or name).
72
+ #
73
+ # @param [String] api_key The API key to access the Airtable API.
74
+ # @param [String] base_id The ID of the Airtable base.
75
+ # @param [String] table_key The name or id of the table within the base.
76
+ # @return [Table] A new Table instance.
77
+ def Airbased.table(api_key, base_id, table_key)
78
+ table_id = nil
79
+ table_name = nil
80
+
81
+ # Deducing whether the passed key is a name or id.
82
+ if table_key.match?(TABLE_MATCHER)
83
+ table_id = table_key
84
+ else
85
+ table_name = table_key
86
+ end
87
+
88
+ Table.new(api_key:, base_id:, id: table_id, name: table_name)
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,29 @@
1
+ module Airbased
2
+ # The Validation module provides methods for validating Airtable-related values.
3
+ module Validation
4
+ # Converts a hash or record to a hash representation.
5
+ #
6
+ # @param value [Array<Hash, Record>] The array of hashes or records to convert.
7
+ # @param id_required [Boolean] Whether an ID is required for each record.
8
+ # @return [Array<Hash>] An array of hashes representing the records.
9
+ # @raise [Airbased::Error] If a record is missing an ID when id_required is true.
10
+ def hash_or_record_to_hash(value, id_required: false)
11
+ built_records = value.map do |record_object|
12
+ if id_required && ((record_object.is_a?(Hash) && record_object&.dig(:id).nil? && record_object&.dig("id").nil?) || (record_object.is_a?(Record) && record_object.new_record?))
13
+ raise Airbased::Error.new("id in records are mandatory for update. Use upsert with merge_on: for records not yet persisted")
14
+ end
15
+
16
+ if record_object.is_a?(Hash) && (record_object.dig(:fields) || record_object.dig("fields"))
17
+ new_record(**record_object)
18
+ elsif record_object.is_a?(Hash)
19
+ new_record(fields: record_object)
20
+ elsif record_object.is_a?(Airbased::Record)
21
+ record_object
22
+ else
23
+ raise Airbased::Error.new("You need to pass an array of records or a record hashes but #{record_object} is a #{record_object.class}.")
24
+ end
25
+ end
26
+ built_records.map(&:to_api_hash)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airbased
4
+ VERSION = "0.0.1-alpha"
5
+ end
data/lib/airbased.rb ADDED
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ require_relative "airbased/version"
6
+
7
+ require_relative "airbased/airtable/errors"
8
+ require_relative "airbased/airtable/airtable"
9
+
10
+ require_relative "airbased/validation"
11
+
12
+ require_relative "airbased/base"
13
+
14
+ require_relative "airbased/table/query"
15
+ require_relative "airbased/table/persistence"
16
+ require_relative "airbased/table/table"
17
+
18
+ require_relative "airbased/record/persistence"
19
+ require_relative "airbased/record"
20
+
21
+ # Airbased is a module for interfacing with the Airtable API.
22
+ module Airbased
23
+ extend self
24
+ attr_accessor :api_key, :debug
25
+
26
+ class Error < StandardError; end
27
+ end
data/sig/airbased.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Airbased
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: airbased
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1.pre.alpha
5
+ platform: ruby
6
+ authors:
7
+ - Aleks Lokhmutov
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-08-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: httparty
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description:
28
+ email:
29
+ - 43987794+alokhmutov@users.noreply.github.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rubocop.yml"
35
+ - CHANGELOG.md
36
+ - CODE_OF_CONDUCT.md
37
+ - LICENSE.txt
38
+ - README.md
39
+ - Rakefile
40
+ - airbased.gemspec
41
+ - lib/airbased.rb
42
+ - lib/airbased/airtable/airtable.rb
43
+ - lib/airbased/airtable/errors.rb
44
+ - lib/airbased/base.rb
45
+ - lib/airbased/record.rb
46
+ - lib/airbased/record/persistence.rb
47
+ - lib/airbased/table/persistence.rb
48
+ - lib/airbased/table/query.rb
49
+ - lib/airbased/table/table.rb
50
+ - lib/airbased/validation.rb
51
+ - lib/airbased/version.rb
52
+ - sig/airbased.rbs
53
+ homepage: https://github.com/alokhmutov/airbased
54
+ licenses:
55
+ - MIT
56
+ metadata:
57
+ allowed_push_host: https://rubygems.org
58
+ homepage_uri: https://github.com/alokhmutov/airbased
59
+ source_code_uri: https://github.com/alokhmutov/airbased
60
+ changelog_uri: https://github.com/alokhmutov/airbased/CHANGELOG.md
61
+ post_install_message:
62
+ rdoc_options: []
63
+ require_paths:
64
+ - lib
65
+ required_ruby_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 3.0.0
70
+ required_rubygems_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ requirements: []
76
+ rubygems_version: 3.5.17
77
+ signing_key:
78
+ specification_version: 4
79
+ summary: Ruby interface to the Airtable’s API.
80
+ test_files: []