fixer_api_client 0.1.2 → 0.2.1

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: d350ccddd2567a680186cda13897b956e2a16774292fdb1597cd667b2c0bad7e
4
- data.tar.gz: b09262a09256ecad5a2a7f62d65b0f4776cec33c010a3ccab3e106c20bd4effb
3
+ metadata.gz: 399de28435ebc2f315f72ddd946dc3d6d6938ddbdb9898e15ca83fc1739f6a7c
4
+ data.tar.gz: 18546a83ee75382806c6f8cac704e67bff63553d8f903f029f638a390ac802f8
5
5
  SHA512:
6
- metadata.gz: 2260ea6f50a3711bd52f90b41a15b2e5dcc202605c0c165a659b8dd6e35b458dbead9f2b9cfff41cd685f1667df580975f09852aad2de47d40d4fc0fd536838d
7
- data.tar.gz: 3407db45ba0d5ae59094f9402dce44166a161a54d9f4669a83e1d11c4e570ab90ea865c1ccf1fcf90bf347e3a2e205a6f10da1570a22ff15a6c5efd6221b2924
6
+ metadata.gz: 64cf0f7dcadc96a5791cd6303b7839f84a495017eeba8b646e535fab2b1d163e42e1ba29ec32c2d7ecaedc83676e1141598f5855f61e12cd8bc57f8bf8aa56eb
7
+ data.tar.gz: 00a535973be4f0e611ba3b664feebbe4a80abfecaf2fcb4f5bf7b3fc4590051912708b85b56c01cd96d50b176dcfb7f0ba0dafea26b32e251bc9b4d0e4387d3a
data/.gitignore CHANGED
@@ -1,14 +1,2 @@
1
- /.bundle/
2
- /.yardoc
3
- /_yardoc/
4
- /coverage/
5
- /doc/
6
1
  /pkg/
7
- /spec/reports/
8
- /tmp/
9
-
10
- # rspec failure tracking
11
- .rspec_status
12
- tags
13
- Gemfile.lock
14
- .byebug_history
2
+ *.gem
data/CHANGELOG.md CHANGED
@@ -1,14 +1,70 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1 (2026-11-26)
4
+
5
+ ### Fixed
6
+
7
+ - Corrected GitHub repository URLs in the gem metadata and documentation.
8
+
9
+ ## 0.2.0 (2026-11-26)
10
+
11
+ ### Added
12
+
13
+ - Reintroduced arithmetic operations (`+`, `-`, `*`, `/`).
14
+ - Added automatic currency conversion when performing arithmetic between different currencies, preserving the leftmost currency.
15
+ - Added currency comparisons through Ruby's `Comparable` module.
16
+ - Added support for numeric methods through `method_missing` and `respond_to_missing?`.
17
+ - Reintroduced rounding while preserving the currency context.
18
+ - Added a generic `convert_to` method.
19
+ - Added `BigDecimal` support for monetary values and exchange rates.
20
+ - Added thread-safe in-memory caching using `Mutex`.
21
+ - Added stale exchange-rate fallback when the API is unavailable.
22
+ - Added retry delay after failed API requests.
23
+ - Added custom exceptions for API and data retrieval failures.
24
+ - Added API response and timestamp validation.
25
+ - Added RSpec coverage for exchange-rate caching.
26
+
27
+ ### Changed
28
+
29
+ - Replaced filesystem-based exchange-rate caching with in-memory caching.
30
+ - Exchange rates are now fetched lazily and refreshed every 24 hours.
31
+ - Currency symbols are loaded from bundled, read-only JSON resources.
32
+ - Replaced global `Numeric` monkey-patching with Ruby refinements.
33
+ - Improved decimal precision by parsing raw JSON responses directly into `BigDecimal`.
34
+ - Currency conversions now use a consistent exchange-rate snapshot per operation.
35
+ - Cached data is recursively frozen to prevent accidental modifications.
36
+ - Changed the default API endpoint to HTTPS.
37
+ - Improved network error handling and API key validation.
38
+ - Improved documentation and usage examples.
39
+
40
+ ### Removed
41
+
42
+ - Runtime filesystem writes.
43
+ - Per-instance exchange-rate memoization.
44
+ - Unnecessary JSON serialization and parsing.
45
+ - Unnecessary Faraday middleware usage.
46
+ - Dependency on writable gem installation directories.
47
+
48
+ ### Breaking changes
49
+
50
+ - Currency extensions must be explicitly enabled using `using FixerApiClient::NumericExtensions`.
51
+ - Currency values are now represented by `BigDecimal` instead of standard integer or floating-point values.
52
+ - Multiplication between two currencies raises a `TypeError`.
53
+ - Division between two currencies returns a dimensionless `BigDecimal` ratio.
54
+ - Exchange-rate caches are no longer persisted across application restarts.
55
+ - Cached currency data is immutable.
56
+
1
57
  ## 0.1.2 (2021-03-26)
2
58
 
3
- - Remove arithmethic operations.
4
- - Removing rounding (just to currency.value.round(2)...)
5
- - Remove byebug dependency
59
+ - Removed arithmetic operations.
60
+ - Removed built-in rounding in favor of `currency.value.round(2)`.
61
+ - Removed the `byebug` dependency.
6
62
 
7
63
  ## 0.1.1 (2021-01-11)
8
64
 
9
- - Fix with test data
10
- - Fix to allow rates older than 1 day to be updated automatically
65
+ - Fixed issues with test data.
66
+ - Fixed automatic updates for exchange rates older than one day.
11
67
 
12
68
  ## 0.1.0 (2020-03-18)
13
69
 
14
- - Initial version
70
+ - Initial release.
data/Gemfile.lock ADDED
@@ -0,0 +1,127 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ fixer_api_client (0.2.1)
5
+ bigdecimal
6
+ faraday
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ bigdecimal (4.1.3)
12
+ byebug (13.0.0)
13
+ reline (>= 0.6.0)
14
+ diff-lcs (1.6.2)
15
+ erb (6.0.7)
16
+ faraday (1.10.6)
17
+ faraday-em_http (~> 1.0)
18
+ faraday-em_synchrony (~> 1.0)
19
+ faraday-excon (~> 1.1)
20
+ faraday-httpclient (~> 1.0)
21
+ faraday-multipart (~> 1.0)
22
+ faraday-net_http (~> 1.0)
23
+ faraday-net_http_persistent (~> 1.0)
24
+ faraday-patron (~> 1.0)
25
+ faraday-rack (~> 1.0)
26
+ faraday-retry (~> 1.0)
27
+ ruby2_keywords (>= 0.0.4)
28
+ faraday-em_http (1.0.0)
29
+ faraday-em_synchrony (1.0.1)
30
+ faraday-excon (1.1.0)
31
+ faraday-httpclient (1.0.1)
32
+ faraday-multipart (1.2.0)
33
+ multipart-post (~> 2.0)
34
+ faraday-net_http (1.0.2)
35
+ faraday-net_http_persistent (1.2.0)
36
+ faraday-patron (1.0.0)
37
+ faraday-rack (1.0.0)
38
+ faraday-retry (1.0.4)
39
+ io-console (0.9.5)
40
+ irb (1.19.0)
41
+ pp (>= 0.6.0)
42
+ prism (>= 1.3.0)
43
+ rdoc (>= 4.0.0)
44
+ reline (>= 0.4.2)
45
+ logger (1.7.0)
46
+ multipart-post (2.4.1)
47
+ pp (0.6.4)
48
+ prettyprint
49
+ prettyprint (0.2.1)
50
+ prism (1.9.0)
51
+ rake (12.3.3)
52
+ rbs (4.2.0)
53
+ logger
54
+ prism (>= 1.6.0)
55
+ tsort
56
+ rdoc (8.1.0)
57
+ erb
58
+ prism (>= 1.6.0)
59
+ rbs (>= 4.0.0)
60
+ tsort
61
+ reline (0.7.0)
62
+ io-console (~> 0.5)
63
+ rspec (3.13.2)
64
+ rspec-core (~> 3.13.0)
65
+ rspec-expectations (~> 3.13.0)
66
+ rspec-mocks (~> 3.13.0)
67
+ rspec-core (3.13.7)
68
+ rspec-support (~> 3.13.0)
69
+ rspec-expectations (3.13.6)
70
+ diff-lcs (>= 1.2.0, < 2.0)
71
+ rspec-support (~> 3.13.0)
72
+ rspec-mocks (3.13.9)
73
+ diff-lcs (>= 1.2.0, < 2.0)
74
+ rspec-support (~> 3.13.0)
75
+ rspec-support (3.13.8)
76
+ ruby2_keywords (0.0.5)
77
+ tsort (0.2.0)
78
+
79
+ PLATFORMS
80
+ arm64-darwin-25
81
+ ruby
82
+
83
+ DEPENDENCIES
84
+ byebug
85
+ fixer_api_client!
86
+ irb
87
+ rake (~> 12)
88
+ rspec (~> 3)
89
+
90
+ CHECKSUMS
91
+ bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66
92
+ byebug (13.0.0) sha256=d2263efe751941ca520fa29744b71972d39cbc41839496706f5d9b22e92ae05d
93
+ diff-lcs (1.6.2) sha256=9ae0d2cba7d4df3075fe8cd8602a8604993efc0dfa934cff568969efb1909962
94
+ erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92
95
+ faraday (1.10.6) sha256=7ff4802a6b312876a2241b3e641ce0d5045e168dd871b422c35b505e5261ad4d
96
+ faraday-em_http (1.0.0) sha256=7a3d4c7079789121054f57e08cd4ef7e40ad1549b63101f38c7093a9d6c59689
97
+ faraday-em_synchrony (1.0.1) sha256=bf3ce45dcf543088d319ab051f80985ea6d294930635b7a0b966563179f81750
98
+ faraday-excon (1.1.0) sha256=b055c842376734d7f74350fe8611542ae2000c5387348d9ba9708109d6e40940
99
+ faraday-httpclient (1.0.1) sha256=4c8ff1f0973ff835be8d043ef16aaf54f47f25b7578f6d916deee8399a04d33b
100
+ faraday-multipart (1.2.0) sha256=7d89a949693714176f612323ca13746a2ded204031a6ba528adee788694ef757
101
+ faraday-net_http (1.0.2) sha256=63992efea42c925a20818cf3c0830947948541fdcf345842755510d266e4c682
102
+ faraday-net_http_persistent (1.2.0) sha256=0b0cbc8f03dab943c3e1cc58d8b7beb142d9df068b39c718cd83e39260348335
103
+ faraday-patron (1.0.0) sha256=dc2cd7b340bb3cc8e36bcb9e6e7eff43d134b6d526d5f3429c7a7680ddd38fa7
104
+ faraday-rack (1.0.0) sha256=ef60ec969a2bb95b8dbf24400155aee64a00fc8ba6c6a4d3968562bcc92328c0
105
+ faraday-retry (1.0.4) sha256=dc659233777fabf96c69c2ffe56c0a5d2c102af90321a42cc6c90157bcd716aa
106
+ fixer_api_client (0.2.1)
107
+ io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5
108
+ irb (1.19.0) sha256=55ee56acbdd6c9fe06a2e6909f46a24e5c41f45f16906bab04e8049cf46f1d27
109
+ logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
110
+ multipart-post (2.4.1) sha256=9872d03a8e552020ca096adadbf5e3cb1cd1cdd6acd3c161136b8a5737cdb4a8
111
+ pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570
112
+ prettyprint (0.2.1) sha256=d555d57ea6d7cf001d4774b693546a6bd88bec1e778ddffb5c60b68ceec4b7d4
113
+ prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
114
+ rake (12.3.3) sha256=f7694adb4fe638da35452300cee6c545e9c377a0e3190018ac04d590b3c26ab3
115
+ rbs (4.2.0) sha256=51f7b886dcc05bc09e10b901daa6a81829f6adc03101d6ca9ea4aac6103e0674
116
+ rdoc (8.1.0) sha256=befc37880a5cfd36dcb176c748b5fd5ee39dd3536a75e81824e4972ce230f60a
117
+ reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d
118
+ rspec (3.13.2) sha256=206284a08ad798e61f86d7ca3e376718d52c0bc944626b2349266f239f820587
119
+ rspec-core (3.13.7) sha256=c64ff16d9788119805cbc6a3f4b6d87cc22417c2d25976a3330de136896b5469
120
+ rspec-expectations (3.13.6) sha256=bf538ca6d367ff5b0d85a87fdb5c0c6038f2cd1308a0eeba07476caa02d22f35
121
+ rspec-mocks (3.13.9) sha256=ea5c7ff3054a6098ca6039aacef80aec69d5a8a3ef80be8fc88337359b672a30
122
+ rspec-support (3.13.8) sha256=e4160030309b7e3e9d9863dfe720a35dfcc577162f5402cd68fc8c5258a0ffd6
123
+ ruby2_keywords (0.0.5) sha256=ffd13740c573b7301cf7a2e61fc857b2a8e3d3aff32545d6f8300d8bae10e3ef
124
+ tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f
125
+
126
+ BUNDLED WITH
127
+ 4.0.9
data/README.md CHANGED
@@ -1,73 +1,261 @@
1
1
  # FixerApiClient
2
2
 
3
- - Just a gem to interact with *Fixer IO API*
3
+ A lightweight Ruby client for the [Fixer.io API](https://fixer.io), with a natural syntax for currency conversion, decimal arithmetic and comparisons.
4
+
5
+ ```ruby
6
+ require 'fixer_api_client'
7
+ using FixerApiClient::NumericExtensions
8
+
9
+ (100.usd + 50.eur + 2000.cop).to_cop.round(2)
10
+ ```
11
+
12
+ ## Features
13
+
14
+ - Currency-specific methods such as `100.usd`, `100.eur` and `100.cop`, enabled through Ruby refinements rather than global monkey patches.
15
+ - Dynamic conversion methods such as `to_usd`, `to_eur` and `to_cop`.
16
+ - Monetary arithmetic using `BigDecimal`.
17
+ - Automatic conversion of currency operands to the left-hand currency when adding or subtracting.
18
+ - Numeric operations such as rounding and comparisons.
19
+ - Lazy, thread-safe, in-memory exchange-rate caching with stale-data fallback.
20
+ - No runtime filesystem writes, Rails dependency or external cache service.
4
21
 
5
22
  ## Installation
6
23
 
7
- Add this line to your application's Gemfile:
24
+ Requires Ruby 3.0 or newer.
25
+
26
+ Add the gem to your application's `Gemfile`:
8
27
 
9
28
  ```ruby
10
29
  gem 'fixer_api_client'
11
30
  ```
12
31
 
13
- And then execute:
32
+ Then run:
33
+
34
+ ```bash
35
+ bundle install
36
+ ```
37
+
38
+ Alternatively:
39
+
40
+ ```bash
41
+ gem install fixer_api_client
42
+ ```
43
+
44
+ To try the current development checkout in another project before publishing a release, use a local Bundler dependency:
45
+
46
+ ```ruby
47
+ gem 'fixer_api_client', path: '../fixer_api_client'
48
+ ```
49
+
50
+ ## Configuration
51
+
52
+ Obtain an API key from [Fixer.io](https://fixer.io) and set it in your environment:
53
+
54
+ ```bash
55
+ export FIXER_IO_API_KEY='your-api-key'
56
+ ```
14
57
 
15
- $ bundle install
58
+ | Environment variable | Description |
59
+ | --- | --- |
60
+ | `FIXER_IO_API_KEY` | Required when fetching live exchange rates. |
61
+ | `FIXER_IO_API_URL` | Optional API base URL. Defaults to `https://data.fixer.io/api`. |
62
+ | `fixer_api_client_tests` | Set to `true` to use bundled offline test data instead of live rates. Intended for development and testing only. |
16
63
 
17
- Or install it yourself as:
64
+ Keep API keys out of source control. Use your deployment platform's secret management or environment configuration in production.
18
65
 
19
- $ gem install fixer_api_client
66
+ The client expects EUR-based rates from Fixer's `/latest` endpoint. Cross-currency conversions are calculated using EUR as the intermediate currency; no custom base currency is required.
20
67
 
21
68
  ## Usage
22
69
 
23
- - This gem will make currency conversions using [Fixer IO API](https://fixer.io).
70
+ ### Creating currencies
71
+
72
+ ```ruby
73
+ require 'fixer_api_client'
74
+ using FixerApiClient::NumericExtensions
75
+
76
+ amount = 100.usd
77
+
78
+ amount.value # => BigDecimal representing 100
79
+ amount.symbol # => 'usd'
80
+ amount.friendly_name # => 'United States Dollar'
81
+ amount.to_s # => '100.0 United States Dollar'
82
+ ```
83
+
84
+ The refinement is lexical: enable it in the file or scope where you want to use currency-specific numeric methods. Requiring the gem does not globally modify `Numeric`.
85
+
86
+ You can also instantiate a currency without enabling the refinement:
87
+
88
+ ```ruby
89
+ FixerApiClient::Currency.new(BigDecimal('100.25'), 'usd', 'United States Dollar')
90
+ ```
91
+
92
+ ### Converting currencies
93
+
94
+ ```ruby
95
+ 100.usd.to_cop
96
+ 100.cop.to_eur
97
+ 100.eur.to_usd
98
+ 100.usd.convert_to('COP')
99
+ 100.usd.to_cop.round(2)
100
+ ```
101
+
102
+ Conversion results depend on the cached exchange-rate snapshot. Converting to the same currency returns the original object without fetching rates.
103
+
104
+ ### Arithmetic
105
+
106
+ Arithmetic returns a new currency object when the result represents money; it does not change the original amount.
107
+
108
+ ```ruby
109
+ 100.usd + 50 # => 150.0 United States Dollar
110
+ 100.usd - 20 # => 80.0 United States Dollar
111
+ 100.usd * 2 # => 200.0 United States Dollar
112
+ 100.usd / 4 # => 25.0 United States Dollar
113
+ 100.usd / 50.usd # => BigDecimal representing 2
114
+ ```
24
115
 
25
- - You need to add `FIXER_IO_API_KEY` and `FIXER_IO_API_URL` env vars. You can get api key [here](https://fixer.io/product). The api key is necesssary to update rates on a daily basis
26
- - NOTE: I made this based this with a free account, so no https available for me, that's why you can pass the api url as an env var.
116
+ When adding or subtracting two currencies, the right-hand operand is converted to the currency of the left-hand operand. The same rule applies to chained additions and subtractions:
27
117
 
28
- - The gem will inject methods to numeric values, example
29
118
  ```ruby
30
- >> 1.usd
31
- => 1 United States Dollar
119
+ (1.usd + 1.cop + 1.ars).symbol # => 'usd'
120
+ (1.cop + 1.usd + 1.ars).symbol # => 'cop'
121
+ 100.eur - 50.usd # => Currency in EUR
32
122
  ```
33
123
 
34
- - You can also make conversions on the fly:
124
+ | Operation | Result |
125
+ | --- | --- |
126
+ | Currency + or - numeric | Currency in the receiver's denomination |
127
+ | Currency + or - currency | Currency in the receiver's denomination |
128
+ | Currency * numeric | Currency |
129
+ | Currency / numeric | Currency |
130
+ | Currency / currency | Dimensionless `BigDecimal` ratio |
131
+ | Currency * currency | `TypeError` |
132
+ | Division by zero | `ZeroDivisionError` |
133
+
134
+ Reverse arithmetic (for example, `50 + 100.usd`) is not supported by the current implementation; put the currency on the left.
135
+
136
+ ### Numeric methods and comparisons
137
+
138
+ Numeric methods are delegated to the underlying `BigDecimal` through `method_missing`. Methods such as `abs`, `round`, `ceil`, `floor`, `truncate` and unary plus/minus preserve the currency when they return a number. Other delegated methods return their underlying results.
139
+
35
140
  ```ruby
36
- >> 2.usd.to_cop
37
- => 8253.28 Colombian Peso
141
+ 10.567.usd.round(2) # => 10.57 United States Dollar
142
+ (-10).usd.abs # => 10.0 United States Dollar
143
+ 100.usd.positive? # => true
144
+ 0.usd.zero? # => true
145
+ 100.usd.to_i # => 100
146
+ 100.usd.to_f # => 100.0
147
+
148
+ 100.usd > 50.usd # => true
149
+ 100.usd == 100.usd # => true
150
+ 100.usd.between?(50.usd, 150.usd) # => true
151
+ 100.usd > 50.eur # compares after conversion
38
152
  ```
39
153
 
40
- - If you want to look at available conversion methods
154
+ `Currency` includes Ruby's `Comparable` module. Cross-currency comparisons use the same conversion policy as arithmetic. Unsupported or unavailable rates can raise errors; a symbol in the bundled catalog does not guarantee that Fixer supplies its rate.
155
+
156
+ ### Decimal precision
157
+
158
+ Amounts are stored as `BigDecimal`, and raw API JSON is parsed using `decimal_class: BigDecimal`, avoiding an intermediate floating-point conversion for decimal rates.
159
+
41
160
  ```ruby
42
- FixerApiClient::available_conversions
161
+ (0.1.usd + 0.2.usd).value == BigDecimal('0.3') # => true
162
+ BigDecimal('10.567').usd.round(2)
43
163
  ```
44
164
 
45
- - Or the available currencies
165
+ Prefer decimal strings when exact input precision matters. Converting an already imprecise `Float` to `BigDecimal` cannot recover lost precision. Division and exchange-rate calculations may still require rounding; the gem does not automatically round conversions to a currency's minor units. Round explicitly when appropriate for your application.
166
+
167
+ ### Discovering currencies and rates
168
+
169
+ ```ruby
170
+ FixerApiClient.available_currencies # array of code/name strings
171
+ FixerApiClient.available_conversions # array of conversion method names
172
+ FixerApiClient.rates_creation_date # UTC timestamp as a string
173
+
174
+ FixerApiClient::CurrencyData.symbols # frozen hash of currency codes and names
175
+ FixerApiClient::CurrencyData.rates # frozen hash of EUR-based rates
176
+ ```
177
+
178
+ The rate lookup and creation-date methods may fetch rates if the cache is missing or expired. Decimal rates are `BigDecimal`; whole-number rates may be `Integer`.
179
+
180
+ ## Exchange-rate caching
181
+
182
+ Currency symbols are shipped as a read-only JSON resource and loaded into memory. Requiring the gem and constructing an amount do not contact Fixer. Rates are fetched only when needed for conversion or explicit rate access.
183
+
184
+ | Setting | Default |
185
+ | --- | --- |
186
+ | Cache lifetime | 24 hours from the API timestamp |
187
+ | Maximum stale age | 7 days from the API timestamp |
188
+ | Retry delay after failed refresh with usable stale data | 60 seconds |
189
+ | Cache scope | One Ruby process |
190
+
191
+ These settings are constants in the current implementation, not public configuration options.
192
+
193
+ The client validates HTTP status, API success, EUR base, timestamp freshness and positive finite rates before replacing the cached snapshot. A `Mutex` serializes cache access and refreshes within a process. Cached data is recursively frozen to protect against accidental mutation. Each individual conversion uses one rate snapshot, but a chain of conversions can span a cache refresh.
194
+
195
+ If a refresh fails, previously cached rates may be used while they remain within the maximum stale age. If no usable snapshot exists, the client raises `FixerApiClient::CurrencyData::FetchError`. The retry delay applies only when usable stale data exists.
196
+
46
197
  ```ruby
47
- FixerApiClient::available_currencies
198
+ begin
199
+ 100.usd.to_cop
200
+ rescue FixerApiClient::CurrencyData::FetchError => e
201
+ warn e.message
202
+ end
203
+ ```
204
+
205
+ An unknown currency or unavailable rate can also raise `KeyError`. Stale rates may be unsuitable for transactions that require current pricing; inspect the rate timestamp and apply your own freshness policy.
206
+
207
+ ### Deploying to cloud environments
208
+
209
+ No writable gem directory, installation-time Fixer request, Redis instance or persistent volume is required. The design works with ordinary Ruby processes and deployments on platforms such as Heroku, AWS and Google Cloud, provided outbound HTTPS is available when live rates are needed.
210
+
211
+ The cache is not shared across processes, workers or containers. Each process starts with an empty live-rate cache and can make its own API requests, including after a restart. This matters when scaling applications or working with a limited API quota. A distributed cache is not currently implemented.
212
+
213
+ ## Development and testing
214
+
215
+ Clone the repository and install dependencies:
216
+
217
+ ```bash
218
+ git clone https://github.com/jhonhquintero/fixer_api_client.git
219
+ cd fixer_api_client
220
+ bin/setup
221
+ bundle exec rspec
222
+ ```
223
+
224
+ You can also run `bundle exec rake spec`. The existing RSpec suite stubs HTTP responses and time to exercise cache reuse, refresh, decimal parsing, response validation and failure handling without contacting the live API.
225
+
226
+ For an interactive session using bundled historical data rather than the API:
227
+
228
+ ```bash
229
+ fixer_api_client_tests=true bin/console
48
230
  ```
49
231
 
50
- - And if you want to check when the rates data was updated...
51
232
  ```ruby
52
- FixerApiClient::rates_creation_date
233
+ using FixerApiClient::NumericExtensions
234
+ 100.usd.to_cop.round(2)
53
235
  ```
54
236
 
55
- ## TODO
237
+ For live rates, launch `bin/console` with your API key and without test mode. The development console includes `reload!` to reload Ruby source files; restarting is safer after changes to constants, refinements or cached state.
238
+
239
+ Build or install the gem locally from a Git checkout:
56
240
 
57
- - Update rates on demand
58
- - More tests...
241
+ ```bash
242
+ bundle exec rake build
243
+ bundle exec rake install
244
+ ```
59
245
 
60
- ## Development
246
+ To publish a new release, update `lib/fixer_api_client/version.rb` and the changelog, run the test suite, and then use `bundle exec rake release` when ready to tag and publish to RubyGems.
61
247
 
62
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
248
+ ## Roadmap
63
249
 
64
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
250
+ - Replace test-specific production branches with VCR/WebMock and isolated test setup.
251
+ - Add explicit cache invalidation and configurable cache policies.
252
+ - Explore optional shared cache adapters for multi-process deployments.
253
+ - Expand arithmetic, conversion and concurrency test coverage.
65
254
 
66
255
  ## Contributing
67
256
 
68
- Bug reports and pull requests are welcome on GitHub at https://github.com/mr-sudaca/fixer_api_client.
69
-
257
+ Bug reports and pull requests are welcome at [GitHub](https://github.com/jhonhquintero/fixer_api_client).
70
258
 
71
259
  ## License
72
260
 
73
- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
261
+ Available under the [MIT License](https://opensource.org/licenses/MIT). See `LICENSE.txt` for details.
data/bin/console CHANGED
@@ -1,14 +1,23 @@
1
1
  #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
2
3
 
3
- require "bundler/setup"
4
- require "fixer_api_client"
4
+ require 'bundler/setup'
5
+ require 'fixer_api_client'
6
+ require 'irb'
5
7
 
6
8
  # You can add fixtures and/or initialization code here to make experimenting
7
9
  # with your gem easier. You can also use a different console, if you like.
8
10
 
9
11
  # (If you use this, don't forget to add pry to your Gemfile!)
10
- # require "pry"
12
+ # require 'pry'
11
13
  # Pry.start
12
14
 
13
- require "irb"
15
+ def reload!
16
+ Dir.glob(File.expand_path('../lib/**/*.rb', __dir__)).sort.each do |file|
17
+ load file
18
+ end
19
+
20
+ true
21
+ end
22
+
14
23
  IRB.start(__FILE__)
@@ -1,36 +1,47 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require_relative 'lib/fixer_api_client/version'
2
4
 
3
5
  Gem::Specification.new do |spec|
4
- spec.name = "fixer_api_client"
6
+ spec.name = 'fixer_api_client'
5
7
  spec.version = FixerApiClient::VERSION
6
- spec.authors = ["Jhon Quintero"]
7
- spec.email = ["jhon@notgmail.co"]
8
+ spec.authors = ['Jhon Quintero']
9
+ spec.email = ['jhon@notgmail.co']
10
+
11
+ spec.summary = 'Another api client'
12
+ spec.homepage = 'https://github.com/jhonhquintero/fixer_api_client'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = Gem::Requirement.new('>= 3.0.0')
8
15
 
9
- spec.summary = %q{Another api client}
10
- spec.description = %q{Another api client for Fixer API}
11
- spec.homepage = "https://github.com/mr-sudaca/fixer_api_client"
12
- spec.license = "MIT"
13
- spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
16
+ spec.description = <<~DESCRIPTION
17
+ A Ruby client for the Fixer API providing currency conversion,
18
+ mixed-currency arithmetic, BigDecimal precision, and thread-safe
19
+ in-memory exchange-rate caching.
20
+ DESCRIPTION
14
21
 
15
- # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
22
+ # spec.metadata['allowed_push_host'] = 'TODO: Set to 'http://mygemserver.com''
16
23
 
17
- spec.metadata["homepage_uri"] = spec.homepage
18
- spec.metadata["source_code_uri"] = "https://github.com/mr-sudaca/fixer_api_client"
19
- spec.metadata["changelog_uri"] = "https://github.com/mr-sudaca/fixer_api_client"
24
+ spec.metadata['homepage_uri'] = spec.homepage
25
+ spec.metadata['source_code_uri'] = 'https://github.com/jhonhquintero/fixer_api_client'
26
+ spec.metadata['changelog_uri'] = 'https://github.com/jhonhquintero/fixer_api_client'
20
27
 
21
28
  # Specify which files should be added to the gem when it is released.
22
29
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
- spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
24
- `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ spec.files = Dir.chdir(__dir__) do
31
+ `git ls-files -z`.split("\x0").reject do |f|
32
+ f.match?(%r{^(test|spec|features)/})
33
+ end
25
34
  end
26
- spec.bindir = "exe"
35
+
36
+ spec.bindir = 'exe'
27
37
  spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
- spec.require_paths = ["lib"]
38
+ spec.require_paths = ['lib']
29
39
 
40
+ spec.add_dependency 'bigdecimal'
30
41
  spec.add_dependency 'faraday'
31
- spec.add_dependency 'faraday_middleware'
32
42
 
33
- spec.add_development_dependency 'rspec', '~> 3'
34
- spec.add_development_dependency 'rake', '~> 12'
35
43
  spec.add_development_dependency 'byebug'
44
+ spec.add_development_dependency 'irb'
45
+ spec.add_development_dependency 'rake', '~> 12'
46
+ spec.add_development_dependency 'rspec', '~> 3'
36
47
  end
@@ -1 +1 @@
1
- {"success":true,"timestamp":1610377566,"base":"EUR","date":"2021-01-11","rates":{"AED":4.460023,"AFN":93.68113,"ALL":123.009405,"AMD":635.990421,"ANG":2.180663,"AOA":798.38364,"ARS":103.669793,"AUD":1.581502,"AWG":2.185699,"AZN":2.066497,"BAM":1.952899,"BBD":2.452839,"BDT":103.011685,"BGN":1.952,"BHD":0.457822,"BIF":2375.12674,"BMD":1.214277,"BND":1.615202,"BOB":8.364015,"BRL":6.672937,"BSD":1.214787,"BTC":3.6426242e-05,"BTN":89.112617,"BWP":13.468096,"BYN":3.133697,"BYR":23799.838501,"BZD":2.448745,"CAD":1.556521,"CDF":2392.126124,"CHF":1.082134,"CLF":0.031716,"CLP":875.118743,"CNY":7.870947,"COP":4267.238187,"CRC":746.136259,"CUC":1.214277,"CUP":32.178353,"CVE":109.909091,"CZK":26.27091,"DJF":216.267183,"DKK":7.437086,"DOP":70.761976,"DZD":160.535954,"EGP":19.002647,"ERN":18.214629,"ETB":47.720067,"EUR":1,"FJD":2.48322,"FKP":0.90187,"GBP":0.90168,"GEL":4.019357,"GGP":0.90187,"GHS":7.115585,"GIP":0.90187,"GMD":62.770282,"GNF":12385.629958,"GTQ":9.475656,"GYD":254.16062,"HKD":9.417754,"HNL":29.445722,"HRK":7.580618,"HTG":87.863848,"HUF":361.370151,"IDR":17287.42555,"ILS":3.860723,"IMP":0.90187,"INR":89.32559,"IQD":1775.880807,"IRR":51127.15242,"ISK":156.678724,"JEP":0.90187,"JMD":173.518992,"JOD":0.860938,"JPY":126.684368,"KES":133.024046,"KGS":101.01052,"KHR":4923.895259,"KMF":488.638127,"KPW":1092.917525,"KRW":1334.41791,"KWD":0.368715,"KYD":1.012389,"KZT":509.956201,"LAK":11298.851468,"LBP":1844.48776,"LKR":229.603167,"LRD":202.845444,"LSL":18.590355,"LTL":3.585446,"LVL":0.734504,"LYD":5.39079,"MAD":10.734071,"MDL":20.925093,"MGA":4605.754122,"MKD":61.563665,"MMK":1624.230023,"MNT":3470.228051,"MOP":9.703296,"MRO":433.49685,"MUR":47.659931,"MVR":18.724173,"MWK":947.136556,"MXN":24.507524,"MYR":4.896575,"MZN":90.985643,"NAD":18.590769,"NGN":462.88675,"NIO":42.530038,"NOK":10.413282,"NPR":142.580348,"NZD":1.696607,"OMR":0.467501,"PAB":1.214887,"PEN":4.39809,"PGK":4.268168,"PHP":58.4359,"PKR":194.587763,"PLN":4.528568,"PYG":8355.197188,"QAR":4.421192,"RON":4.870344,"RSD":117.58459,"RUB":90.846147,"RWF":1183.920538,"SAR":4.556128,"SBD":9.763597,"SCR":25.748643,"SDG":67.089018,"SEK":10.100542,"SGD":1.616943,"SHP":0.90187,"SLL":12391.701445,"SOS":707.924092,"SRD":17.186845,"STD":25299.30525,"SVC":10.630133,"SYP":622.723311,"SZL":18.590892,"THB":36.622639,"TJS":13.842709,"TMT":4.249971,"TND":3.269446,"TOP":2.753249,"TRY":9.105897,"TTD":8.258772,"TWD":34.030153,"TZS":2832.83767,"UAH":34.203064,"UGX":4492.394301,"USD":1.214277,"UYU":51.624367,"UZS":12701.342479,"VEF":12.1276,"VND":28014.414205,"VUV":131.456783,"WST":3.031951,"XAF":654.995485,"XAG":0.048415,"XAU":0.000658,"XCD":3.281646,"XDR":0.840645,"XOF":649.638173,"XPF":119.060156,"YER":304.056508,"ZAR":18.892091,"ZMK":10929.955061,"ZMW":25.778521,"ZWL":390.997572}}
1
+ {"success":true,"timestamp":1795698966,"base":"EUR","date":"2026-11-26","rates":{"AED":4.03062,"AFN":71.338172,"ALL":89.781404,"AMD":395.038179,"ANG":1.964992,"AOA":1007.517893,"ARS":1760.192675,"AUD":1.654327,"AWG":1.978269,"AZN":1.864708,"BAM":1.956484,"BBD":2.210173,"BDT":137.608133,"BGN":1.946408,"BHD":0.413845,"BIF":3297.153296,"BMD":1.097514,"BND":1.416395,"BOB":13.00855,"BRL":6.323979,"BSD":1.097384,"BTC":1.8053309e-05,"BTN":101.390465,"BWP":15.687487,"BYN":3.296153,"BYR":21511.272327,"BZD":2.206972,"CAD":1.562009,"CDF":2502.331977,"CHF":0.915453,"CLF":0.028937,"CLP":1138.890911,"CNY":7.314378,"CNH":7.310755,"COP":3895.834095,"CRC":487.172625,"CUC":1.097514,"CUP":26.336212,"CVE":110.303583,"CZK":24.452554,"DJF":195.408351,"DKK":7.473686,"DOP":65.662968,"DZD":150.542649,"EGP":60.174825,"ERN":16.462708,"ETB":179.380545,"EUR":1,"FJD":2.521318,"FKP":0.837644,"GBP":0.837661,"GEL":2.84226,"GGP":0.837644,"GHS":12.943527,"GIP":0.837644,"GMD":81.215621,"GNF":9732.404252,"GTQ":8.389935,"GYD":229.54029,"HKD":8.601424,"HNL":29.499318,"HRK":7.498177,"HTG":143.970359,"HUF":372.212507,"IDR":20187.725446,"ILS":3.654683,"IMP":0.837644,"INR":101.553016,"IQD":1663.581897,"IRR":2142740.031353,"ISK":137.002826,"JEP":0.837644,"JMD":173.670747,"JOD":0.77812,"JPY":174.774146,"KES":142.797102,"KGS":95.977015,"KHR":4463.663,"KMF":492.783696,"KPW":987.762889,"KRW":1475.091501,"KWD":0.34317,"KYD":0.91452,"KZT":502.555787,"LAK":24747.656367,"LBP":98267.372483,"LKR":365.417818,"LRD":179.962948,"LSL":19.316257,"LTL":3.240674,"LVL":0.663875,"LYD":7.103485,"MAD":10.97894,"MDL":20.191063,"MGA":4965.736942,"MKD":61.554938,"MMK":2304.679775,"MNT":3961.894572,"MOP":8.859099,"MRU":44.706638,"MUR":51.462842,"MVR":16.898744,"MWK":1902.765559,"MXN":21.584477,"MYR":4.518248,"MZN":69.587843,"NAD":19.316257,"NGN":1499.632025,"NIO":40.384126,"NOK":10.719907,"NPR":162.224744,"NZD":2.003616,"OMR":0.42198,"PAB":1.097384,"PEN":3.803931,"PGK":4.94573,"PHP":69.972017,"PKR":303.361411,"PLN":4.482653,"PYG":7024.457052,"QAR":4.000199,"RON":5.343467,"RSD":117.666637,"RUB":90.243909,"RWF":1621.76727,"SAR":4.118314,"SBD":8.974548,"SCR":15.133398,"SDG":660.156721,"SEK":11.203389,"SGD":1.416281,"SHP":0.838341,"SLE":25.243043,"SLL":23014.321627,"SOS":627.119357,"SRD":40.952573,"STD":22716.321739,"STN":24.508573,"SVC":9.601358,"SYP":14269.876023,"SZL":19.310755,"THB":37.373667,"TJS":10.15045,"TMT":3.841299,"TND":3.328164,"TOP":2.64255,"TRY":55.618388,"TTD":7.446605,"TWD":36.197328,"TZS":2952.304722,"UAH":49.477206,"UGX":4723.652264,"USD":1.097514,"UYU":44.465553,"UZS":13165.605135,"VES":1011.227905,"VND":28351.527673,"VUV":133.961753,"WST":3.093333,"XAF":655.957,"XAG":0.026525,"XAU":0.000307885671,"XCD":2.966086,"XCG":1.977692,"XDR":0.775999,"XOF":655.957,"XPF":119.331742,"YER":259.669931,"ZAR":19.262873,"ZMK":9878.941396,"ZMW":22.851993,"ZWL":353.399026,"SSP":6338.633442,"MXV":2.415536}}
@@ -1,21 +1,18 @@
1
- require 'json'
1
+ # frozen_string_literal: true
2
+
2
3
  require 'faraday'
3
- require 'faraday_middleware'
4
4
 
5
5
  module FixerApiClient
6
+ # Handles the connection to the Fixer.io API.
6
7
  class Connection
7
-
8
8
  def self.connection
9
9
  ::Faraday.new(url: url) do |conn|
10
- conn.request :json
11
10
  conn.adapter :net_http
12
- conn.response :json, content_type: /\bjson$/
13
11
  end
14
12
  end
15
13
 
16
14
  def self.url
17
- ENV['FIXER_IO_API_URL'] || 'http://data.fixer.io/api'
15
+ ENV['FIXER_IO_API_URL'] || 'https://data.fixer.io/api'
18
16
  end
19
-
20
17
  end
21
18
  end
@@ -1,45 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bigdecimal'
4
+
1
5
  module FixerApiClient
6
+ # Represents a currency with conversion, arithmetic,
7
+ # comparison, and numeric delegation capabilities.
2
8
  class Currency
9
+ include Comparable
10
+
3
11
  BASE_CURRENCY = 'EUR'
4
- BASE_CURRENCY_AMOUNT = 1
12
+
13
+ CURRENCY_PRESERVING_METHODS = %i[
14
+ abs
15
+ round
16
+ ceil
17
+ floor
18
+ truncate
19
+ +@
20
+ -@
21
+ ].freeze
5
22
 
6
23
  attr_reader :value, :symbol, :friendly_name
7
24
 
8
25
  def initialize(value, symbol, friendly_name)
9
- @value = value
10
- @symbol = symbol
26
+ @value = to_decimal(value)
27
+ @symbol = symbol.downcase
11
28
  @friendly_name = friendly_name
12
-
13
29
  end
14
30
 
15
31
  def inspect
16
- "#{value} #{friendly_name}"
32
+ "#{value.to_s('F')} #{friendly_name}"
33
+ end
34
+
35
+ alias to_s inspect
36
+
37
+ # Arithmetic operators
38
+
39
+ def +(other)
40
+ with_value(value + normalize_argument(other))
41
+ end
42
+
43
+ def -(other)
44
+ with_value(value - normalize_argument(other))
45
+ end
46
+
47
+ def *(other)
48
+ raise TypeError, 'Cannot multiply two currencies' if other.is_a?(Currency)
49
+
50
+ with_value(value * normalize_argument(other))
51
+ end
52
+
53
+ def /(other)
54
+ divisor = normalize_argument(other)
55
+
56
+ raise ZeroDivisionError, 'Divided by zero' if divisor.zero?
57
+
58
+ result = value / divisor
59
+
60
+ return result if other.is_a?(Currency)
61
+
62
+ with_value(result)
63
+ end
64
+
65
+ # Comparison
66
+
67
+ def <=>(other)
68
+ return nil unless other.is_a?(Currency) || other.is_a?(Numeric)
69
+
70
+ value <=> normalize_argument(other)
17
71
  end
18
72
 
19
- FixerApiClient::CurrencyData.symbols.each do |symbol, friendly_name|
20
- define_method "to_#{symbol.downcase}" do
21
- new_value =
22
- (to_base * currency_rates[symbol.upcase])
73
+ # Currency conversion
74
+
75
+ def convert_to(target_symbol)
76
+ target_symbol = target_symbol.upcase
23
77
 
24
- self.class.new(new_value, symbol.downcase, friendly_name)
78
+ return self if symbol.upcase == target_symbol
79
+
80
+ friendly_name = CurrencyData.symbols.fetch(target_symbol)
81
+ rates = CurrencyData.rates
82
+ new_value = to_base(rates) * rate_for(target_symbol, rates)
83
+
84
+ self.class.new(new_value, target_symbol, friendly_name)
85
+ end
86
+
87
+ CurrencyData.symbols.each_key do |symbol|
88
+ define_method("to_#{symbol.downcase}") do
89
+ convert_to(symbol)
25
90
  end
26
91
  end
27
92
 
28
93
  private
29
94
 
30
- # this will convert the value we have to the base currency (EUR) because
31
- # API free tier only allows to set EUR as base, so, let's say we have
32
- # 1 USD, this, will convert it to 0.80 EUR
33
- def to_base
34
- value / current_rate
95
+ def to_decimal(number)
96
+ case number
97
+ when BigDecimal
98
+ number
99
+ when Rational
100
+ BigDecimal(number, 32)
101
+ else
102
+ BigDecimal(number.to_s)
103
+ end
104
+ end
105
+
106
+ def with_value(new_value)
107
+ self.class.new(new_value, symbol, friendly_name)
108
+ end
109
+
110
+ def normalize_argument(other)
111
+ case other
112
+ when Currency
113
+ other.convert_to(symbol).value
114
+ when Numeric
115
+ to_decimal(other)
116
+ else
117
+ raise TypeError, "Unsupported operand: #{other.class}"
118
+ end
119
+ end
120
+
121
+ def to_base(rates)
122
+ return value if symbol.upcase == BASE_CURRENCY
123
+
124
+ value / rate_for(symbol, rates)
35
125
  end
36
126
 
37
- def current_rate
38
- currency_rates[symbol.upcase]
127
+ def rate_for(currency_symbol, rates)
128
+ to_decimal(rates.fetch(currency_symbol.upcase))
39
129
  end
40
-
41
- def currency_rates
42
- @currency_rates ||= FixerApiClient::CurrencyData.rates
130
+
131
+ def method_missing(method_name, *args, **kwargs, &block)
132
+ return super unless value.respond_to?(method_name)
133
+
134
+ result = value.public_send(
135
+ method_name, *args, **kwargs, &block
136
+ )
137
+
138
+ if CURRENCY_PRESERVING_METHODS.include?(method_name) &&
139
+ result.is_a?(Numeric)
140
+ with_value(result)
141
+ else
142
+ result
143
+ end
144
+ end
145
+
146
+ def respond_to_missing?(method_name, include_private = false)
147
+ value.respond_to?(method_name) || super
43
148
  end
44
149
  end
45
150
  end
@@ -1,98 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bigdecimal'
1
4
  require 'json'
2
- require 'time'
5
+ require 'thread'
3
6
 
4
7
  module FixerApiClient
8
+ # Loads bundled symbols and caches exchange rates in memory per process.
5
9
  class CurrencyData
10
+ CACHE_TTL = 86_400
11
+ MAX_STALE_AGE = 7 * CACHE_TTL
12
+ RETRY_DELAY = 60
13
+ CACHE_LOCK = Mutex.new
14
+ DATA_DIRECTORY = File.expand_path('../data', __dir__)
6
15
 
7
- def self.rates
8
- new.rates
9
- end
10
-
11
- def self.symbols
12
- new.symbols
13
- end
16
+ class FetchError < FixerApiClient::Error; end
14
17
 
15
- def self.rates_creation_date
16
- new.rates_creation_date
17
- end
18
+ class << self
19
+ def rates
20
+ rates_data.fetch('rates')
21
+ end
18
22
 
19
- def rates_creation_date
20
- timestamp = parse(rates_filename, 'rates')['timestamp']
21
- timestamp && Time.strptime(timestamp.to_s,'%s').utc.to_s
22
- end
23
+ def symbols
24
+ CACHE_LOCK.synchronize do
25
+ @symbols ||= {}
26
+ @symbols[environment] ||= read_fixture('currency_symbols.json').fetch('symbols')
27
+ end
28
+ end
23
29
 
24
- def rates
25
- @rates ||= parse(rates_filename, 'rates')['rates']
26
- end
30
+ def rates_creation_date
31
+ Time.at(rates_data.fetch('timestamp')).utc.to_s
32
+ end
27
33
 
28
- def symbols
29
- @symbols ||= parse(currencies_filename, 'symbols')['symbols']
30
- end
34
+ private
31
35
 
32
- private
33
-
34
- def parse(filename, data_path)
35
- data =
36
- if update?(filename)
37
- results = connection.get("#{url_for(data_path)}?access_key=#{api_key}")
38
- if results.status == 200
39
- file = File.open(filename, 'w')
40
- file.puts(results.body.to_json)
41
- file.close
42
- results.body.to_json
36
+ def rates_data
37
+ CACHE_LOCK.synchronize do
38
+ if tests?
39
+ @test_rates ||= read_fixture('rates_data.json')
43
40
  else
44
- File.read(filename)
41
+ refresh_rates
45
42
  end
46
- else
47
- File.read(filename)
48
43
  end
44
+ end
49
45
 
50
- JSON.parse(data)
51
- end
46
+ def refresh_rates
47
+ now = Time.now.to_i
48
+ return @rates_data if @rates_data && now - @rates_data.fetch('timestamp') < CACHE_TTL
49
+
50
+ if @retry_after && monotonic_time < @retry_after && usable_stale_rates?(now)
51
+ return @rates_data
52
+ end
53
+
54
+ @rates_data = fetch_rates
55
+ @retry_after = nil
56
+ @rates_data
57
+ rescue FetchError
58
+ raise unless usable_stale_rates?(Time.now.to_i)
52
59
 
53
- def url_for(path)
54
- case path
55
- when 'rates' then '/latest'
56
- when 'symbols' then '/symbols'
60
+ @retry_after = monotonic_time + RETRY_DELAY
61
+ @rates_data
57
62
  end
58
- end
59
63
 
60
- def update?(filename)
61
- return false if tests?
62
- return false unless File.exists?(filename) && !File.zero?(filename)
63
- return false if filename =~ /currency_symbols/ # currency symbols file doesn't have timestamp...
64
+ def usable_stale_rates?(now)
65
+ @rates_data && now - @rates_data.fetch('timestamp') <= MAX_STALE_AGE
66
+ end
64
67
 
65
- data = File.read(filename)
66
- json = JSON.parse(data)
67
- ((Time.now.utc - Time.at(json['timestamp']).utc) / 60 / 60) > 24
68
- end
68
+ def monotonic_time
69
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
70
+ end
69
71
 
70
- def tests?
71
- ENV['fixer_api_client_tests'].to_s == 'true'
72
- end
72
+ def fetch_rates
73
+ response = Connection.connection.get('/latest', access_key: api_key)
74
+ raise FetchError, "Fixer returned HTTP #{response.status}" unless response.status == 200
73
75
 
74
- def rates_filename
75
- @rates_filename ||=
76
- File.join(File.dirname(__dir__), 'data', env,'rates_data.json')
77
- end
78
-
79
- def env
80
- tests? ? 'test' : 'production'
81
- end
76
+ data = JSON.parse(response.body, decimal_class: BigDecimal)
77
+ raise FetchError, 'Invalid exchange-rate response' unless valid_rates?(data)
78
+
79
+ deep_freeze(data)
80
+ rescue Faraday::ConnectionFailed, Faraday::TimeoutError, Faraday::SSLError => e
81
+ # Avoid including a request URL that may contain the API key.
82
+ raise FetchError, "Fixer request failed (#{e.class})", cause: nil
83
+ rescue JSON::ParserError
84
+ raise FetchError, 'Fixer returned invalid JSON', cause: nil
85
+ end
86
+
87
+ def valid_rates?(data)
88
+ return false unless data.is_a?(Hash) && data['success'] == true && data['base'] == 'EUR'
89
+
90
+ timestamp = data['timestamp']
91
+ rates = data['rates']
92
+
93
+ timestamp.is_a?(Integer) && timestamp.positive? && timestamp <= Time.now.to_i &&
94
+ Time.now.to_i - timestamp < CACHE_TTL &&
95
+ rates.is_a?(Hash) && !rates.empty? && rates['EUR'] == 1 &&
96
+ rates.values.all? { |rate| rate.is_a?(Numeric) && rate.finite? && rate.positive? }
97
+ end
98
+
99
+ def read_fixture(filename)
100
+ path = File.join(DATA_DIRECTORY, environment, filename)
101
+ deep_freeze(JSON.parse(File.read(path), decimal_class: BigDecimal))
102
+ end
103
+
104
+ def deep_freeze(value)
105
+ case value
106
+ when Hash
107
+ value.each { |key, item| key.freeze; deep_freeze(item) }
108
+ when Array
109
+ value.each { |item| deep_freeze(item) }
110
+ end
111
+ value.freeze
112
+ end
113
+
114
+ def tests?
115
+ ENV['fixer_api_client_tests'] == 'true'
116
+ end
117
+
118
+ def environment
119
+ tests? ? 'test' : 'production'
120
+ end
82
121
 
83
- def currencies_filename
84
- @currencies_filename ||=
85
- File.join(File.dirname(__dir__), 'data', env, 'currency_symbols.json')
122
+ def api_key
123
+ key = ENV['FIXER_IO_API_KEY']
124
+ raise FetchError, 'You need an API key' if key.nil? || key.strip.empty?
125
+
126
+ key
127
+ end
86
128
  end
87
129
 
88
- def connection
89
- @connection ||= FixerApiClient::Connection.connection
130
+ # Preserve the previous instance-level API, using the shared process cache.
131
+ def rates
132
+ self.class.rates
90
133
  end
91
134
 
92
- def api_key
93
- raise 'You need an api key' unless ENV['FIXER_IO_API_KEY']
135
+ def symbols
136
+ self.class.symbols
137
+ end
94
138
 
95
- ENV['FIXER_IO_API_KEY']
139
+ def rates_creation_date
140
+ self.class.rates_creation_date
96
141
  end
97
142
  end
98
143
  end
@@ -1,9 +1,14 @@
1
- require 'json'
1
+ # frozen_string_literal: true
2
2
 
3
- class Numeric
4
- FixerApiClient::CurrencyData.symbols.each do |symbol, friendly_name|
5
- define_method symbol.downcase do
6
- FixerApiClient::Currency.new(self, symbol.downcase, friendly_name)
3
+ module FixerApiClient
4
+ # Extends numeric values with currency-specific methods.
5
+ module NumericExtensions
6
+ refine Numeric do
7
+ FixerApiClient::CurrencyData.symbols.each do |symbol, friendly_name|
8
+ define_method(symbol.downcase) do
9
+ FixerApiClient::Currency.new(self, symbol.downcase, friendly_name)
10
+ end
11
+ end
7
12
  end
8
13
  end
9
14
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module FixerApiClient
2
- VERSION = "0.1.2"
4
+ VERSION = '0.2.1'
3
5
  end
metadata CHANGED
@@ -1,17 +1,16 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fixer_api_client
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.2.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jhon Quintero
8
- autorequire:
9
8
  bindir: exe
10
9
  cert_chain: []
11
- date: 2021-03-26 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
- name: faraday
13
+ name: bigdecimal
15
14
  requirement: !ruby/object:Gem::Requirement
16
15
  requirements:
17
16
  - - ">="
@@ -25,7 +24,7 @@ dependencies:
25
24
  - !ruby/object:Gem::Version
26
25
  version: '0'
27
26
  - !ruby/object:Gem::Dependency
28
- name: faraday_middleware
27
+ name: faraday
29
28
  requirement: !ruby/object:Gem::Requirement
30
29
  requirements:
31
30
  - - ">="
@@ -39,19 +38,33 @@ dependencies:
39
38
  - !ruby/object:Gem::Version
40
39
  version: '0'
41
40
  - !ruby/object:Gem::Dependency
42
- name: rspec
41
+ name: byebug
43
42
  requirement: !ruby/object:Gem::Requirement
44
43
  requirements:
45
- - - "~>"
44
+ - - ">="
46
45
  - !ruby/object:Gem::Version
47
- version: '3'
46
+ version: '0'
48
47
  type: :development
49
48
  prerelease: false
50
49
  version_requirements: !ruby/object:Gem::Requirement
51
50
  requirements:
52
- - - "~>"
51
+ - - ">="
53
52
  - !ruby/object:Gem::Version
54
- version: '3'
53
+ version: '0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: irb
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
55
68
  - !ruby/object:Gem::Dependency
56
69
  name: rake
57
70
  requirement: !ruby/object:Gem::Requirement
@@ -67,20 +80,23 @@ dependencies:
67
80
  - !ruby/object:Gem::Version
68
81
  version: '12'
69
82
  - !ruby/object:Gem::Dependency
70
- name: byebug
83
+ name: rspec
71
84
  requirement: !ruby/object:Gem::Requirement
72
85
  requirements:
73
- - - ">="
86
+ - - "~>"
74
87
  - !ruby/object:Gem::Version
75
- version: '0'
88
+ version: '3'
76
89
  type: :development
77
90
  prerelease: false
78
91
  version_requirements: !ruby/object:Gem::Requirement
79
92
  requirements:
80
- - - ">="
93
+ - - "~>"
81
94
  - !ruby/object:Gem::Version
82
- version: '0'
83
- description: Another api client for Fixer API
95
+ version: '3'
96
+ description: |
97
+ A Ruby client for the Fixer API providing currency conversion,
98
+ mixed-currency arithmetic, BigDecimal precision, and thread-safe
99
+ in-memory exchange-rate caching.
84
100
  email:
85
101
  - jhon@notgmail.co
86
102
  executables: []
@@ -88,10 +104,9 @@ extensions: []
88
104
  extra_rdoc_files: []
89
105
  files:
90
106
  - ".gitignore"
91
- - ".rspec"
92
- - ".travis.yml"
93
107
  - CHANGELOG.md
94
108
  - Gemfile
109
+ - Gemfile.lock
95
110
  - LICENSE.txt
96
111
  - README.md
97
112
  - Rakefile
@@ -108,14 +123,13 @@ files:
108
123
  - lib/fixer_api_client/currency_data.rb
109
124
  - lib/fixer_api_client/numeric_overloader.rb
110
125
  - lib/fixer_api_client/version.rb
111
- homepage: https://github.com/mr-sudaca/fixer_api_client
126
+ homepage: https://github.com/jhonhquintero/fixer_api_client
112
127
  licenses:
113
128
  - MIT
114
129
  metadata:
115
- homepage_uri: https://github.com/mr-sudaca/fixer_api_client
116
- source_code_uri: https://github.com/mr-sudaca/fixer_api_client
117
- changelog_uri: https://github.com/mr-sudaca/fixer_api_client
118
- post_install_message:
130
+ homepage_uri: https://github.com/jhonhquintero/fixer_api_client
131
+ source_code_uri: https://github.com/jhonhquintero/fixer_api_client
132
+ changelog_uri: https://github.com/jhonhquintero/fixer_api_client
119
133
  rdoc_options: []
120
134
  require_paths:
121
135
  - lib
@@ -123,15 +137,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
123
137
  requirements:
124
138
  - - ">="
125
139
  - !ruby/object:Gem::Version
126
- version: 2.3.0
140
+ version: 3.0.0
127
141
  required_rubygems_version: !ruby/object:Gem::Requirement
128
142
  requirements:
129
143
  - - ">="
130
144
  - !ruby/object:Gem::Version
131
145
  version: '0'
132
146
  requirements: []
133
- rubygems_version: 3.2.3
134
- signing_key:
147
+ rubygems_version: 4.0.9
135
148
  specification_version: 4
136
149
  summary: Another api client
137
150
  test_files: []
data/.rspec DELETED
@@ -1,3 +0,0 @@
1
- --format documentation
2
- --color
3
- --require spec_helper
data/.travis.yml DELETED
@@ -1,6 +0,0 @@
1
- ---
2
- language: ruby
3
- cache: bundler
4
- rvm:
5
- - 2.3.1
6
- before_install: gem install bundler -v 2.1.2