arena 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f3371aa0176ae4b8281424c96411818c2148a94577064b82028d74d2c0b3a25b
4
- data.tar.gz: 95896b4182c13238e273aea03e07d4268672d62b2769886f16d03bf989d2bc72
3
+ metadata.gz: d88f264f978e497efe19a732dc80737c8c7c760b7e7d75b79556e492bfa95043
4
+ data.tar.gz: 3576f335e878df9c6e0a9d9ac723ed5d6245f0f17a6389bce4acab2dd4fe4793
5
5
  SHA512:
6
- metadata.gz: 51ada54286c9ecc23b53cb0d585c287785373770a37eefce33708d8593ee953985c8e9e4721389cb94442499bee56f4fcfa494f5335a342ccd19e892bd9f4989
7
- data.tar.gz: 1bec6fc4a24221ab8a9e4a7fda5e20db5ebafb2e49f226f136e682620f65964548612dc6a0a10ea26a6a79546fbcc704af277754bd0fbf71a2406b6747bcf5a4
6
+ metadata.gz: 6ed901071401ada54eaf3a2860b63e1067bb7bac39ceeb21c2eaf940e3516027f1e7a1f5b7cde9e8ce42710c935d2f63676ba2aff9a3f26b8ddf46554fcbef70
7
+ data.tar.gz: 0c97778bd38110213930fa4c99433595570142f5ca7073686b5a1c232e0b81c345cb62ee66f819ce015e38d7dfccd52742a7eaf1d025134df5b0133ba33f9fb0
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0 (2026/11/20)
4
+
5
+ - [#20](https://github.com/aredotna/arena-rb/pull/20): Fixed the test suite with minitest 6 and CI on current runners - [@dblock](https://github.com/dblock).
6
+ - [#21](https://github.com/aredotna/arena-rb/pull/21): Added `Arena::V3::Client` for the Are.na v3 API and a configurable `user_agent` - [@dblock](https://github.com/dblock).
7
+ - [#22](https://github.com/aredotna/arena-rb/pull/22): Read default credentials from `ARENA_CLIENT_ID`, `ARENA_CLIENT_SECRET`, `ARENA_ACCESS_TOKEN` and `ARENA_AUTH_TOKEN` instead of `APPLICATION_ID`, `APPLICATION_SECRET` and `AUTH_TOKEN`, and no longer send `APPLICATION_SECRET` as the access token - [@dblock](https://github.com/dblock).
8
+ - [#23](https://github.com/aredotna/arena-rb/pull/23): Removed the unused `Arena::Cache` adaptors, `Arena::Error::CacheError` and the `use_caching` and `expires_in` settings - [@dblock](https://github.com/dblock).
9
+ - [#24](https://github.com/aredotna/arena-rb/pull/24): Removed the global `String#constantize` monkey patch and only instantiate `Arena::Base` classes from API class names - [@dblock](https://github.com/dblock).
10
+ - [#25](https://github.com/aredotna/arena-rb/pull/25): Added the MIT license and project links to the gemspec, and package only `lib` and documentation - [@dblock](https://github.com/dblock).
11
+ - [#26](https://github.com/aredotna/arena-rb/pull/26): Added RubyGems, test and lint badges and reorganized the README around the v3 API - [@dblock](https://github.com/dblock).
data/README.md CHANGED
@@ -1,43 +1,77 @@
1
- [![test](https://github.com/aredotna/arena-rb/actions/workflows/test.yml/badge.svg)](https://github.com/aredotna/arena-rb/actions/workflows/test.yml)
2
-
3
1
  # Arena
4
2
 
5
- ## Installation
6
-
7
- Add this line to your application's Gemfile:
3
+ [![Gem Version](https://badge.fury.io/rb/arena.svg)](https://rubygems.org/gems/arena)
4
+ [![Test](https://github.com/aredotna/arena-rb/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/aredotna/arena-rb/actions/workflows/test.yml)
5
+ [![Lint](https://github.com/aredotna/arena-rb/actions/workflows/lint.yml/badge.svg?branch=master)](https://github.com/aredotna/arena-rb/actions/workflows/lint.yml)
8
6
 
9
- gem 'arena'
7
+ A Ruby client for the [Are.na API](https://www.are.na/developers).
10
8
 
11
- And then execute:
9
+ ## Installation
12
10
 
13
- $ bundle
11
+ Add to your Gemfile and run `bundle install`.
14
12
 
15
- Or install it yourself as:
13
+ ```ruby
14
+ gem 'arena'
15
+ ```
16
16
 
17
- $ gem install arena
17
+ Or install it with `gem install arena`.
18
18
 
19
19
  ## Usage
20
20
 
21
- Register an application at [https://dev.are.na](https://dev.are.na).
21
+ Use the v3 API via `Arena.v3`, see [Are.na API v3](https://www.are.na/developers/explore) and its [OpenAPI spec](https://api.are.na/v3/openapi.json).
22
22
 
23
- ### Configure for personal use (optional; be aware this grants access to everything your account has access to)
24
23
  ```ruby
25
- Arena.configure do |config|
26
- config.access_token = 'XXXXXXXXXXXXX'
24
+ require 'arena'
25
+
26
+ channel = Arena.v3.channel('arena-influences')
27
+ channel.title # => "Arena Influences"
28
+ channel.owner.slug # => "are-na-team"
29
+
30
+ contents = Arena.v3.channel_contents('arena-influences', sort: 'created_at_desc', per: 10)
31
+ contents.each do |connectable|
32
+ puts "#{connectable.type}: #{connectable.title} (connected at #{connectable.connection.connected_at})"
27
33
  end
34
+ contents.meta.next_page # => 2
35
+ contents.more? # => true
28
36
  ```
29
37
 
30
- ### Simple usage example
38
+ Responses are `Arena::V3::Resource` objects whose attributes are readable as methods or with `[]`. Lists are an enumerable `Arena::V3::Collection` with `data` and `meta`. Errors raise `Arena::V3::Error` subclasses, such as `Arena::V3::NotFoundError`, `Arena::V3::UnauthorizedError` and `Arena::V3::RateLimitError`, with `status`, `body` and `headers`.
39
+
40
+ ## Configuration
41
+
42
+ Unauthenticated requests are limited to 30 per minute. Authenticate with a personal access token from [are.na/settings](https://www.are.na/settings) or a user's OAuth token for higher limits and for private content, search (Premium only) and writes.
31
43
 
32
44
  ```ruby
33
- @channel = Arena.channel(params[:id])
34
- ```
45
+ Arena.configure do |config|
46
+ config.access_token = 'token'
47
+ config.user_agent = 'MyApp/1.0 (+https://example.com)'
48
+ end
35
49
 
36
- ```erb
37
- <% @channel.contents.each do |connectable| %>
38
- <%= connectable.title %>
39
- <% if connectable.has_image? %>
40
- <img src="<%= connectable.image.display.url %>" alt="<%= connectable.title %>" />
41
- <% end %>
42
- <% end %>
50
+ Arena.v3.me.slug
51
+ Arena.v3.create_block(value: 'https://example.com', channel_ids: [123]) # requires the write scope
43
52
  ```
53
+
54
+ Pass options to `Arena.v3` to override the global configuration, e.g. `Arena.v3(access_token: user_token).me`.
55
+
56
+ | Setting | Default | Description |
57
+ |----------------------|------------------------------------------------------------|---------------------------------------------------|
58
+ | `access_token` | `ENV['ARENA_ACCESS_TOKEN']` | Personal access or OAuth token, sent as `Bearer`. |
59
+ | `application_id` | `ENV['ARENA_CLIENT_ID']` | OAuth application client ID. |
60
+ | `application_secret` | `ENV['ARENA_CLIENT_SECRET']` | OAuth application client secret. |
61
+ | `auth_token` | `ENV['ARENA_AUTH_TOKEN']` | Legacy `X-AUTH-TOKEN`, used without an access token. |
62
+ | `user_agent` | `arena-rb/<version> (+https://github.com/aredotna/arena-rb)` | `User-Agent` header, identify your application. |
63
+ | `base_domain` | `api.are.na` | API host. |
64
+
65
+ Register an OAuth application at [are.na/oauth/applications](https://www.are.na/oauth/applications), then use `Arena.v3.oauth_token(grant_type: 'authorization_code', code: code, redirect_uri: redirect_uri)` to exchange an authorization code for a user token.
66
+
67
+ ## Legacy v2 API
68
+
69
+ Are.na is winding down the v2 API, and some of its endpoints, such as `Arena.channel_feed` and `Arena.user_feed`, already return `410 Gone`. The v2 client is still available for the remaining endpoints, e.g. `Arena.channel('arena-influences').contents` or `Arena.search('brutalism')`, but new code should use `Arena.v3`.
70
+
71
+ ## Contributing
72
+
73
+ See [CHANGELOG](CHANGELOG.md) for changes. Run `bundle install` and `bundle exec rake` to run RuboCop and the tests.
74
+
75
+ ## License
76
+
77
+ [MIT](LICENSE)
data/lib/arena/api.rb CHANGED
@@ -49,11 +49,17 @@ module Arena
49
49
  end
50
50
 
51
51
  # Returns a paginated feed for a given Channel
52
+ #
53
+ # @deprecated The v2 feed endpoints have been disabled by Are.na and return 410 Gone,
54
+ # use Arena.v3.channel_contents instead.
52
55
  def channel_feed(id, options = {})
53
56
  object_from_response(Arena::ChannelFeed, :get, "/channel/#{id}/feed", options)
54
57
  end
55
58
 
56
59
  # Returns a paginated feed for a given User
60
+ #
61
+ # @deprecated The v2 feed endpoints have been disabled by Are.na and return 410 Gone,
62
+ # use Arena.v3.user_contents instead.
57
63
  def user_feed(id, options = {})
58
64
  object_from_response(Arena::UserFeed, :get, "/user/#{id}/feed", options)
59
65
  end
data/lib/arena/base.rb CHANGED
@@ -1,11 +1,26 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'arena/error'
4
+
3
5
  module Arena
4
6
  class Base
5
7
  attr_reader :attrs
6
8
 
7
9
  alias to_hash attrs
8
10
 
11
+ # Returns the Arena::Base subclass for a class name returned by the API, e.g. "Text" for Arena::Text.
12
+ #
13
+ # @param name [String]
14
+ # @return [Class]
15
+ def self.class_for(name)
16
+ klass = Arena.const_get(name.to_s, false) if name.to_s.match?(/\A[A-Z]\w*\z/)
17
+ raise Arena::Error, "Unexpected class #{name.inspect}" unless klass.is_a?(Class) && klass <= Arena::Base
18
+
19
+ klass
20
+ rescue NameError
21
+ raise Arena::Error, "Unexpected class #{name.inspect}"
22
+ end
23
+
9
24
  # Define methods that retrieve the value from an initialized instance
10
25
  # variable Hash, using the attribute as a key
11
26
  #
data/lib/arena/channel.rb CHANGED
@@ -24,7 +24,7 @@ module Arena
24
24
  end
25
25
 
26
26
  def contents
27
- @contents ||= @attrs['contents'].collect { |object| "Arena::#{object['class']}".constantize.new(object) }
27
+ @contents ||= @attrs['contents'].collect { |object| Arena::Base.class_for(object['class']).new(object) }
28
28
  end
29
29
 
30
30
  def contents_updated_at
data/lib/arena/client.rb CHANGED
@@ -31,12 +31,13 @@ module Arena
31
31
  private
32
32
 
33
33
  def set_headers
34
+ headers = @user_agent ? { 'User-Agent' => @user_agent } : {}
34
35
  if !@access_token.nil?
35
- { 'Authorization' => "Bearer #{@access_token}" }
36
+ headers.merge('Authorization' => "Bearer #{@access_token}")
36
37
  elsif !@auth_token.nil?
37
- { 'X-AUTH-TOKEN' => @auth_token }
38
+ headers.merge('X-AUTH-TOKEN' => @auth_token)
38
39
  else
39
- {}
40
+ headers
40
41
  end
41
42
  end
42
43
 
@@ -44,10 +45,14 @@ module Arena
44
45
  response.code != 200
45
46
  end
46
47
 
47
- def error_message(response)
48
+ def error_message_from_json(response)
48
49
  "#{response['code']}: #{response['message']} - #{response['description']}"
49
50
  end
50
51
 
52
+ def error_message(response)
53
+ "#{response.code}: #{response.body && response.body.length.positive? ? response.body : 'Unexpected Error'}"
54
+ end
55
+
51
56
  def request(method, path, options)
52
57
  response = self.class.send(method, "https://#{@base_domain}/#{@api_version}#{path}", options)
53
58
 
@@ -55,13 +60,10 @@ module Arena
55
60
  begin
56
61
  JSON.parse(response.body)
57
62
  rescue JSON::ParserError, TypeError
58
- nil
59
63
  end
60
- else
61
- response.body
62
64
  end
63
65
 
64
- raise Arena::Error, error_message(parsed) if error?(response)
66
+ raise Arena::Error, parsed ? error_message_from_json(parsed) : error_message(response) if error?(response)
65
67
 
66
68
  parsed
67
69
  end
@@ -4,8 +4,7 @@ module Arena
4
4
  module Configurable
5
5
  attr_accessor :base_domain,
6
6
  :api_version,
7
- :use_caching,
8
- :expires_in
7
+ :user_agent
9
8
 
10
9
  attr_writer :application_id,
11
10
  :application_secret,
@@ -21,8 +20,7 @@ module Arena
21
20
  application_secret
22
21
  access_token
23
22
  auth_token
24
- use_caching
25
- expires_in
23
+ user_agent
26
24
  ]
27
25
  end
28
26
  end
data/lib/arena/default.rb CHANGED
@@ -4,8 +4,6 @@ module Arena
4
4
  module Default
5
5
  BASE_DOMAIN = 'api.are.na' unless defined? BASE_DOMAIN
6
6
  API_VERSION = 'v2' unless defined? API_VERSION
7
- USE_CACHING = false unless defined? USE_CACHING
8
- EXPIRES_IN = 600 unless defined? EXPIRES_IN # 10 minutes
9
7
 
10
8
  class << self
11
9
  def options
@@ -21,27 +19,23 @@ module Arena
21
19
  end
22
20
 
23
21
  def application_id
24
- ENV.fetch('APPLICATION_ID', nil)
22
+ ENV.fetch('ARENA_CLIENT_ID', nil)
25
23
  end
26
24
 
27
25
  def application_secret
28
- ENV.fetch('APPLICATION_SECRET', nil)
26
+ ENV.fetch('ARENA_CLIENT_SECRET', nil)
29
27
  end
30
28
 
31
29
  def access_token
32
- ENV.fetch('APPLICATION_SECRET', nil)
30
+ ENV.fetch('ARENA_ACCESS_TOKEN', nil)
33
31
  end
34
32
 
35
33
  def auth_token
36
- ENV.fetch('AUTH_TOKEN', nil)
34
+ ENV.fetch('ARENA_AUTH_TOKEN', nil)
37
35
  end
38
36
 
39
- def use_caching
40
- USE_CACHING
41
- end
42
-
43
- def expires_in
44
- EXPIRES_IN
37
+ def user_agent
38
+ "arena-rb/#{Arena::VERSION} (+https://github.com/aredotna/arena-rb)"
45
39
  end
46
40
  end
47
41
  end
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'arena/core_ext/string'
4
3
  require 'arena/base'
5
4
  require 'arena/channel'
6
5
  require 'arena/user'
@@ -20,7 +19,7 @@ module Arena
20
19
  unless instance_variable_get "@#{method}s"
21
20
  instance_variable_set("@#{method}s",
22
21
  @attrs["#{method}s"].collect do |element|
23
- "Arena::#{method.capitalize}".constantize.new(element)
22
+ Arena::Base.class_for(method.capitalize).new(element)
24
23
  end)
25
24
  end
26
25
  instance_variable_get "@#{method}s"
data/lib/arena/story.rb CHANGED
@@ -25,7 +25,7 @@ module Arena
25
25
 
26
26
  unless instance_variable_get "@#{method}"
27
27
  instance_variable_set("@#{method}",
28
- "Arena::#{@attrs[type]}".constantize.new(@attrs[method]))
28
+ Arena::Base.class_for(@attrs[type]).new(@attrs[method]))
29
29
  end
30
30
  instance_variable_get "@#{method}"
31
31
  end
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'arena/v3/resource'
4
+ require 'arena/v3/collection'
5
+
6
+ module Arena
7
+ module V3
8
+ # Methods for the Are.na v3 API, see https://www.are.na/developers/explore.
9
+ #
10
+ # List methods accept page and per (max 100), as well as endpoint-specific options such as sort or type,
11
+ # and return an Arena::V3::Collection. Other methods return an Arena::V3::Resource.
12
+ module API
13
+ # Checks that the API is reachable.
14
+ def ping
15
+ resource(:get, '/ping')
16
+ end
17
+
18
+ # The authenticated user.
19
+ def me
20
+ resource(:get, '/me')
21
+ end
22
+
23
+ # The authenticated user's feed, cursor-paginated with limit, next and prev.
24
+ def me_feed(options = {})
25
+ collection(:get, '/me/feed', options)
26
+ end
27
+
28
+ # The authenticated user's notifications.
29
+ def me_notifications(options = {})
30
+ collection(:get, '/me/notifications', options)
31
+ end
32
+
33
+ # A channel by id or slug.
34
+ def channel(id)
35
+ resource(:get, "/channels/#{escape(id)}")
36
+ end
37
+
38
+ # Blocks and channels connected to a channel, sorted with sort (e.g. created_at_desc, position_asc).
39
+ def channel_contents(id, options = {})
40
+ collection(:get, "/channels/#{escape(id)}/contents", options)
41
+ end
42
+
43
+ # Channels a channel is connected to.
44
+ def channel_connections(id, options = {})
45
+ collection(:get, "/channels/#{escape(id)}/connections", options)
46
+ end
47
+
48
+ # Users following a channel.
49
+ def channel_followers(id, options = {})
50
+ collection(:get, "/channels/#{escape(id)}/followers", options)
51
+ end
52
+
53
+ # Creates a channel, e.g. create_channel(title: 'Ideas', visibility: 'private').
54
+ def create_channel(options = {})
55
+ resource(:post, '/channels', options)
56
+ end
57
+
58
+ # Updates a channel.
59
+ def update_channel(id, options = {})
60
+ resource(:put, "/channels/#{escape(id)}", options)
61
+ end
62
+
63
+ # Deletes a channel.
64
+ def delete_channel(id)
65
+ request(:delete, "/channels/#{escape(id)}")
66
+ nil
67
+ end
68
+
69
+ # A block by id.
70
+ def block(id)
71
+ resource(:get, "/blocks/#{escape(id)}")
72
+ end
73
+
74
+ # Channels a block is connected to.
75
+ def block_connections(id, options = {})
76
+ collection(:get, "/blocks/#{escape(id)}/connections", options)
77
+ end
78
+
79
+ # Comments on a block.
80
+ def block_comments(id, options = {})
81
+ collection(:get, "/blocks/#{escape(id)}/comments", options)
82
+ end
83
+
84
+ # Creates a block from text or a URL and connects it, e.g. create_block(value: 'Hello', channel_ids: [123]).
85
+ def create_block(options = {})
86
+ resource(:post, '/blocks', options)
87
+ end
88
+
89
+ # Updates a block.
90
+ def update_block(id, options = {})
91
+ resource(:put, "/blocks/#{escape(id)}", options)
92
+ end
93
+
94
+ # Comments on a block, e.g. create_comment(123, body: 'Nice!').
95
+ def create_comment(block_id, options = {})
96
+ resource(:post, "/blocks/#{escape(block_id)}/comments", options)
97
+ end
98
+
99
+ # Deletes a comment.
100
+ def delete_comment(id)
101
+ request(:delete, "/comments/#{escape(id)}")
102
+ nil
103
+ end
104
+
105
+ # A connection by id.
106
+ def connection(id)
107
+ resource(:get, "/connections/#{escape(id)}")
108
+ end
109
+
110
+ # Connects a block or a channel to channels,
111
+ # e.g. create_connection(connectable_id: 1, connectable_type: 'Block', channel_ids: [123]).
112
+ def create_connection(options = {})
113
+ resource(:post, '/connections', options)
114
+ end
115
+
116
+ # Removes a connection.
117
+ def delete_connection(id)
118
+ request(:delete, "/connections/#{escape(id)}")
119
+ nil
120
+ end
121
+
122
+ # A user by id or slug.
123
+ def user(id)
124
+ resource(:get, "/users/#{escape(id)}")
125
+ end
126
+
127
+ # Blocks and channels created by a user, newest first by default, filter with type (e.g. Channel, Image).
128
+ def user_contents(id, options = {})
129
+ collection(:get, "/users/#{escape(id)}/contents", options)
130
+ end
131
+
132
+ # Users following a user.
133
+ def user_followers(id, options = {})
134
+ collection(:get, "/users/#{escape(id)}/followers", options)
135
+ end
136
+
137
+ # Channels, users and groups a user follows.
138
+ def user_following(id, options = {})
139
+ collection(:get, "/users/#{escape(id)}/following", options)
140
+ end
141
+
142
+ # Groups a user belongs to.
143
+ def user_groups(id, options = {})
144
+ collection(:get, "/users/#{escape(id)}/groups", options)
145
+ end
146
+
147
+ # A group by id or slug.
148
+ def group(id)
149
+ resource(:get, "/groups/#{escape(id)}")
150
+ end
151
+
152
+ # Blocks and channels in a group.
153
+ def group_contents(id, options = {})
154
+ collection(:get, "/groups/#{escape(id)}/contents", options)
155
+ end
156
+
157
+ # Users following a group.
158
+ def group_followers(id, options = {})
159
+ collection(:get, "/groups/#{escape(id)}/followers", options)
160
+ end
161
+
162
+ # Members of a group.
163
+ def group_members(id, options = {})
164
+ collection(:get, "/groups/#{escape(id)}/members", options)
165
+ end
166
+
167
+ # Searches blocks, channels, users and groups, e.g. search('brutalism', type: 'Channel').
168
+ # Requires authentication with a Premium account.
169
+ def search(query, options = {})
170
+ collection(:get, '/search', options.merge(query: query))
171
+ end
172
+
173
+ # Obtains an OAuth access token,
174
+ # e.g. oauth_token(grant_type: 'authorization_code', code: '...', redirect_uri: '...').
175
+ # The client id and secret default to the configured application_id and application_secret.
176
+ def oauth_token(options = {})
177
+ resource(:post_form, '/oauth/token', {
178
+ client_id: @application_id,
179
+ client_secret: @application_secret
180
+ }.merge(options))
181
+ end
182
+
183
+ # Obtains an access token for the application itself with the client_credentials grant.
184
+ def client_credentials_token(options = {})
185
+ oauth_token({ grant_type: 'client_credentials' }.merge(options))
186
+ end
187
+
188
+ private
189
+
190
+ def resource(method, path, options = {})
191
+ Resource.new(request(method, path, options))
192
+ end
193
+
194
+ def collection(method, path, options = {})
195
+ Collection.new(request(method, path, options))
196
+ end
197
+
198
+ def escape(id)
199
+ URI.encode_www_form_component(id.to_s)
200
+ end
201
+ end
202
+ end
203
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'httparty'
4
+ require 'json'
5
+ require 'uri'
6
+ require 'arena/configurable'
7
+ require 'arena/v3/error'
8
+ require 'arena/v3/api'
9
+
10
+ module Arena
11
+ module V3
12
+ # A client for the Are.na v3 API, configured like Arena::Client.
13
+ #
14
+ # client = Arena::V3::Client.new(access_token: 'token')
15
+ # client.channel_contents('arena-influences', sort: 'created_at_desc', per: 10).each do |connectable|
16
+ # puts connectable.title
17
+ # end
18
+ class Client
19
+ include HTTParty
20
+ include Arena::Configurable
21
+ include Arena::V3::API
22
+
23
+ API_VERSION = 'v3'
24
+
25
+ def initialize(options = {})
26
+ Arena::Configurable.keys.each do |key| # rubocop:disable Style/HashEachMethods -- keys is an Array
27
+ instance_variable_set(:"@#{key}", options.key?(key) ? options[key] : Arena.instance_variable_get(:"@#{key}"))
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def request(method, path, options = {})
34
+ response = self.class.send(http_method(method), url(path), request_options(method, options))
35
+ parsed = parse(response)
36
+ raise_error(response, parsed) unless response.success?
37
+
38
+ parsed
39
+ end
40
+
41
+ def http_method(method)
42
+ method == :post_form ? :post : method
43
+ end
44
+
45
+ def url(path)
46
+ "https://#{@base_domain}/#{API_VERSION}#{path}"
47
+ end
48
+
49
+ def request_options(method, options)
50
+ options = options.compact
51
+ headers = request_headers
52
+
53
+ case method
54
+ when :get, :delete
55
+ { headers: headers, query: options.empty? ? nil : options }.compact
56
+ when :post_form
57
+ { headers: headers, body: options }
58
+ else
59
+ { headers: headers.merge('Content-Type' => 'application/json'), body: JSON.generate(options) }
60
+ end
61
+ end
62
+
63
+ def request_headers
64
+ headers = { 'Accept' => 'application/json' }
65
+ headers['User-Agent'] = @user_agent if @user_agent
66
+ if @access_token
67
+ headers['Authorization'] = "Bearer #{@access_token}"
68
+ elsif @auth_token
69
+ headers['X-AUTH-TOKEN'] = @auth_token
70
+ end
71
+ headers
72
+ end
73
+
74
+ def parse(response)
75
+ return unless response.body && !response.body.empty?
76
+ return unless response.content_type.to_s.include?('json')
77
+
78
+ JSON.parse(response.body)
79
+ rescue JSON::ParserError
80
+ nil
81
+ end
82
+
83
+ def raise_error(response, parsed)
84
+ raise Arena::V3::Error.for(response.code).new(
85
+ error_message(response, parsed),
86
+ status: response.code,
87
+ body: parsed || response.body,
88
+ headers: response.headers.to_h.transform_values { |value| value.is_a?(Array) ? value.first : value }
89
+ )
90
+ end
91
+
92
+ def error_message(response, parsed)
93
+ if parsed.is_a?(Hash) && (parsed['error'] || parsed['message'])
94
+ details = parsed['details'].is_a?(Hash) ? parsed['details']['message'] : nil
95
+ details ||= parsed['description']
96
+ [[response.code, parsed['error'] || parsed['message']].join(': '), details].compact.join(' - ')
97
+ else
98
+ "#{response.code}: #{response.body.to_s.empty? ? 'Unexpected Error' : response.body}"
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'arena/v3/resource'
4
+
5
+ module Arena
6
+ module V3
7
+ # A list returned by the v3 API, with its items in data and pagination in meta.
8
+ #
9
+ # Page-based lists have meta.current_page, meta.next_page and
10
+ # meta.has_more_pages, cursor-based lists (/v3/me/feed) have
11
+ # meta.next_cursor and meta.has_more.
12
+ class Collection < Resource
13
+ include Enumerable
14
+
15
+ def data
16
+ @data ||= Array(@attrs['data']).map { |element| Resource.new(element) }
17
+ end
18
+
19
+ def meta
20
+ @meta ||= Resource.new(@attrs['meta'])
21
+ end
22
+
23
+ def each(&block)
24
+ data.each(&block)
25
+ end
26
+
27
+ def size
28
+ data.size
29
+ end
30
+
31
+ alias length size
32
+
33
+ def empty?
34
+ data.empty?
35
+ end
36
+
37
+ def more?
38
+ meta.key?('has_more_pages') ? meta.has_more_pages == true : meta['has_more'] == true
39
+ end
40
+ end
41
+ end
42
+ end