padrino-helpers 0.18.6 → 0.18.7

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: e6ed027bb5dfe6ab9d40aff832528d42f74b8b8af6edd743088de049671e484d
4
- data.tar.gz: e41ac27da5e82874d96604ff149e61f411106af71d2b38b5270b683ec68eeda9
3
+ metadata.gz: 8d48b3eb0375fcb6efd0cd47969a692cf4be678eea8016a34eca8559dda015d2
4
+ data.tar.gz: 3b2edb1fc3870dc11a51da6523084487e8328446307aa400b9e4d2f01dc46e9f
5
5
  SHA512:
6
- metadata.gz: 810548985ca4feacab73f229e6de1b0fca30cb863e19756449ccdc27e4646837da5238ee35038da3edd45bfc3f43fdabd1b956ca015640692dc1861f1919bc1b
7
- data.tar.gz: a8f269847b149528001c8e12674552eefa0737aa67df19767a193eea2586c8232c793c7fa1864e4c6b64e2f130143b92d0dcabb736556f68bf1d9754af223b75
6
+ metadata.gz: '0594ec553348926d37a9458709c52993711858faab537f65fb61087d025ef3aabc043b85b3fdb01994d80c064b0a884cd467281684ff0fbb5c90ce437b4a3b6c'
7
+ data.tar.gz: 11cf30d2143bf4862a5db29e14085e4959a7f101b27e0b827fdf89d2a8fcf59a36154f11e2e88a7ce5a7c2ba499f4774d9826b3badeba97414e306dd5971562e
@@ -48,6 +48,14 @@ module Padrino
48
48
  #
49
49
  DEFAULT_RENDERING_OPTIONS = { strict_format: false, raise_exceptions: true } unless defined?(DEFAULT_RENDERING_OPTIONS)
50
50
 
51
+ ##
52
+ # Guards every app's layout and template path caches: requests render from several threads
53
+ # at once, and on JRuby a Hash used from two threads at once can lose entries or raise.
54
+ # Finding a path that isn't cached runs outside it.
55
+ # ceiling: one lock for every app; give each class its own if it shows up as contention.
56
+ #
57
+ CACHE_LOCK = Mutex.new unless defined?(CACHE_LOCK) # @private
58
+
51
59
  class << self
52
60
  ##
53
61
  # Default engine configurations for Padrino::Rendering.
@@ -122,22 +130,22 @@ module Padrino
122
130
  end
123
131
 
124
132
  def cache_layout_path(name)
125
- @_cached_layout ||= {}
126
- if !reload_templates? && (path = @_cached_layout[name])
133
+ if !reload_templates? && (path = CACHE_LOCK.synchronize { (@_cached_layout ||= {})[name] })
127
134
  path
128
135
  else
129
- @_cached_layout[name] = yield(name)
136
+ path = yield(name)
137
+ CACHE_LOCK.synchronize { (@_cached_layout ||= {})[name] = path }
130
138
  end
131
139
  end
132
140
 
133
141
  def cache_template_path(options)
134
142
  began_at = Time.now
135
- @_cached_templates ||= {}
136
143
  logging = defined?(settings) && settings.logging? && defined?(logger) && logger.respond_to?(:bench) && logger.debug?
137
- if !reload_templates? && (path = @_cached_templates[options])
144
+ if !reload_templates? && (path = CACHE_LOCK.synchronize { (@_cached_templates ||= {})[options] })
138
145
  logger.bench :cached, began_at, path[0] if logging
139
146
  else
140
- path = @_cached_templates[options] = yield
147
+ path = yield
148
+ CACHE_LOCK.synchronize { (@_cached_templates ||= {})[options] = path }
141
149
  logger.bench :template, began_at, path[0] if path && logging
142
150
  end
143
151
  path
@@ -189,7 +189,7 @@ module Padrino
189
189
  # Returns the object's models name.
190
190
  #
191
191
  def object_model_name(explicit_object = object)
192
- explicit_object.is_a?(Symbol) ? explicit_object : explicit_object.class.to_s.underscore.gsub('/', '_')
192
+ explicit_object.is_a?(Symbol) ? explicit_object : Inflections.underscore(explicit_object.class).gsub('/', '_')
193
193
  end
194
194
 
195
195
  ##
@@ -128,7 +128,7 @@ module Padrino
128
128
  options = { length: 30, omission: '...' }.update(options)
129
129
  return unless text
130
130
 
131
- len = options[:length] - options[:omission].length
131
+ len = [options[:length] - options[:omission].length, 0].max
132
132
  chars = text
133
133
  (chars.length > options[:length] ? chars[0...len] + options[:omission] : text).to_s
134
134
  end
@@ -156,7 +156,7 @@ module Padrino
156
156
  return unless text
157
157
 
158
158
  words = text.split
159
- words[0..(options[:length] - 1)].join(' ') + (words.length > options[:length] ? options[:omission] : '')
159
+ words.first([options[:length], 0].max).join(' ') + (words.length > options[:length] ? options[:omission] : '')
160
160
  end
161
161
 
162
162
  ##
@@ -12,7 +12,7 @@ module Padrino
12
12
  # Formats a +number+ into a currency string (e.g., $13.65). You can customize the format
13
13
  # in the +options+ hash.
14
14
  #
15
- # @param [Float] number
15
+ # @param [Float, BigDecimal] number
16
16
  # Currency value to format.
17
17
  # @param [Hash] options
18
18
  # Options for currency conversion.
@@ -66,7 +66,7 @@ module Padrino
66
66
  # Formats a +number+ as a percentage string (e.g., 65%). You can customize the
67
67
  # format in the +options+ hash.
68
68
  #
69
- # @param [Integer, Float] number
69
+ # @param [Integer, Float, BigDecimal] number
70
70
  # Percentage value to format.
71
71
  # @param [Hash] options
72
72
  # Options for percentage conversion.
@@ -159,7 +159,7 @@ module Padrino
159
159
  # You can customize the format in the +options+ hash.
160
160
  #
161
161
  # @overload number_with_precision(number, options = {})
162
- # @param [Integer, Float] number
162
+ # @param [Integer, Float, BigDecimal] number
163
163
  # Number value to format.
164
164
  # @param [Hash] options
165
165
  # Options for formatter.
@@ -198,17 +198,48 @@ module Padrino
198
198
  end
199
199
 
200
200
  begin
201
- rounded_number = (Float(number) * (10**precision)).round.to_f / 10**precision
202
- number_with_delimiter(
203
- format("%01.#{precision}f", rounded_number),
204
- separator: separator,
205
- delimiter: delimiter
206
- )
201
+ # ceiling: a BigDecimal with an exponent above 309 takes the Float path, which returns
202
+ # it unformatted as before, so a huge exponent can't make a huge string; write those
203
+ # out too, with a length limit, if anyone needs them.
204
+ formatted_number =
205
+ if defined?(::BigDecimal) && number.is_a?(::BigDecimal) && number.exponent <= Float::MAX_10_EXP + 1
206
+ NumberHelpers.decimal_with_precision(number, precision)
207
+ else
208
+ rounded_number = (Float(number) * (10**precision)).round.to_f / 10**precision
209
+ format("%01.#{precision}f", rounded_number)
210
+ end
211
+ number_with_delimiter(formatted_number, separator: separator, delimiter: delimiter)
207
212
  rescue StandardError
208
213
  number
209
214
  end
210
215
  end
211
216
 
217
+ ##
218
+ # Writes a BigDecimal rounded to +precision+ fraction digits exactly, halves away
219
+ # from zero as Float#round does, with every fraction digit written. Through a Float,
220
+ # BigDecimal('1.005') would round to 1.00 and digits past the 16th would be lost.
221
+ #
222
+ # @example
223
+ # NumberHelpers.decimal_with_precision(BigDecimal('1.005'), 2) # => "1.01"
224
+ # NumberHelpers.decimal_with_precision(BigDecimal('-2.5'), 0) # => "-3"
225
+ #
226
+ # @api private
227
+ def self.decimal_with_precision(number, precision)
228
+ # format raises the same for these on the Float path.
229
+ raise ArgumentError, "invalid precision: #{precision.inspect}" unless precision.is_a?(Integer) && precision >= 0
230
+ raise FloatDomainError, number.to_s unless number.finite?
231
+
232
+ # BigDecimal#round(n, mode) is exact whatever BigDecimal.limit and BigDecimal.mode say.
233
+ # A value below 10**-(precision + 1) rounds to zero; skipping it keeps a tiny exponent
234
+ # from costing time (JRuby's round divides by 10 to the exponent).
235
+ rounded = number.exponent < -precision ? BigDecimal(0) : number.round(precision, ::BigDecimal::ROUND_HALF_UP)
236
+ # to_s is US-ASCII or binary, depending on the bigdecimal version; a Float gets UTF-8.
237
+ # The sign comes off the string: bigdecimal 2.0's abs rounds to BigDecimal.limit.
238
+ integer, fraction = rounded.to_s('F').encode(::Encoding::UTF_8).delete_prefix('-').split('.')
239
+ digits = precision.zero? ? integer : "#{integer}.#{fraction.ljust(precision, '0')}"
240
+ rounded.negative? ? "-#{digits}" : digits
241
+ end
242
+
212
243
  # The units available for storage formatting.
213
244
  STORAGE_UNITS = %i[byte kb mb gb tb].freeze
214
245
 
@@ -1,6 +1,7 @@
1
1
  require 'padrino-support'
2
2
  require 'padrino-support/inflections'
3
3
  require 'i18n'
4
+ require 'padrino-support/locale'
4
5
 
5
6
  # remove at 0.14
6
7
  require 'padrino/rendering'
@@ -32,6 +32,22 @@ describe 'FormBuilder' do
32
32
  Padrino::Helpers::FormBuilder::StandardFormBuilder.new(self, object)
33
33
  end
34
34
 
35
+ describe 'for #object_model_name method' do
36
+ it 'should work without String#underscore from ActiveSupport or padrino-gen' do
37
+ hidden = String.method_defined?(:underscore)
38
+ if hidden
39
+ String.send(:alias_method, :__hidden_underscore, :underscore)
40
+ String.send(:remove_method, :underscore)
41
+ end
42
+ assert_equal 'user', standard_builder.send(:object_model_name)
43
+ ensure
44
+ if hidden
45
+ String.send(:alias_method, :underscore, :__hidden_underscore)
46
+ String.send(:remove_method, :__hidden_underscore)
47
+ end
48
+ end
49
+ end
50
+
35
51
  describe 'for #form_for method' do
36
52
  it 'should display correct form html' do
37
53
  actual_html = form_for(@user, '/register', id: 'register', "accept-charset": 'UTF-8', method: 'post') { 'Demo' }
@@ -175,6 +175,10 @@ describe 'FormatHelpers' do
175
175
  actual_text = truncate('And they found that many people were sleeping better.', length: 25, omission: '(clipped)')
176
176
  assert_equal 'And they found t(clipped)', actual_text
177
177
  end
178
+ it 'should not return more text when the length is shorter than the omission' do
179
+ assert_equal '...', truncate('hello world', length: 2)
180
+ assert_equal '(cut)', truncate('hello world', length: 3, omission: '(cut)')
181
+ end
178
182
  end
179
183
 
180
184
  describe 'for #truncate_words method' do
@@ -193,6 +197,9 @@ describe 'FormatHelpers' do
193
197
  actual_text = truncate_words('And they found that many people were sleeping better.', length: 4, omission: '(clipped)')
194
198
  assert_equal 'And they found that(clipped)', actual_text
195
199
  end
200
+ it 'should keep no words for a length of zero' do
201
+ assert_equal '...', truncate_words('one two three', length: 0)
202
+ end
196
203
  end
197
204
 
198
205
  describe 'for #h and #h! method' do
@@ -97,6 +97,74 @@ describe 'NumberHelpers' do
97
97
  assert_nil number_with_precision(nil)
98
98
  end
99
99
 
100
+ it 'should round a BigDecimal exactly in number_with_precision' do
101
+ assert_equal '1.01', number_with_precision(BigDecimal('1.005'), precision: 2)
102
+ assert_equal '-1.01', number_with_precision(BigDecimal('-1.005'), precision: 2)
103
+ assert_equal '12345678901234567.89', number_with_precision(BigDecimal('12345678901234567.89'), precision: 2)
104
+ assert_equal '0.30000000000000000000', number_with_precision(BigDecimal('0.3'), precision: 20)
105
+ assert_equal '13.00000', number_with_precision(BigDecimal('13'), precision: 5)
106
+ assert_equal '3', number_with_precision(BigDecimal('2.5'), precision: 0)
107
+ assert_equal '-3', number_with_precision(BigDecimal('-2.5'), precision: 0)
108
+ assert_equal '0.00', number_with_precision(BigDecimal('-0.001'), precision: 2)
109
+ assert_equal '0.00', number_with_precision(BigDecimal('-0'), precision: 2)
110
+ assert_equal '12.345.678.901.234.567,89',
111
+ number_with_precision(BigDecimal('12345678901234567.885'), precision: 2, separator: ',', delimiter: '.')
112
+ end
113
+
114
+ it 'should round a BigDecimal exactly in number_to_currency and number_to_percentage' do
115
+ assert_equal '$1.01', number_to_currency(BigDecimal('1.005'))
116
+ assert_equal '$12,345,678,901,234,567.89', number_to_currency(BigDecimal('12345678901234567.89'))
117
+ assert_equal '4.001%', number_to_percentage(BigDecimal('4.0005'))
118
+ end
119
+
120
+ it 'should keep returning a BigDecimal it can not format unchanged' do
121
+ [BigDecimal('NaN'), BigDecimal('Infinity'), BigDecimal('-Infinity'), BigDecimal('1e400')].each do |number|
122
+ assert_same number, number_with_precision(number, precision: 2)
123
+ assert_same number, number_to_currency(number)
124
+ end
125
+ [-1, 1.5].each do |precision|
126
+ number = BigDecimal('12.345')
127
+ assert_same number, number_with_precision(number, precision: precision)
128
+ end
129
+ end
130
+
131
+ it 'should round a BigDecimal half away from zero whatever the BigDecimal rounding mode' do
132
+ mode = BigDecimal.mode(BigDecimal::ROUND_MODE)
133
+ BigDecimal.mode(BigDecimal::ROUND_MODE, BigDecimal::ROUND_HALF_EVEN)
134
+ assert_equal '1.01', number_with_precision(BigDecimal('1.005'), precision: 2)
135
+ assert_equal '3', number_with_precision(BigDecimal('2.5'), precision: 0)
136
+ ensure
137
+ BigDecimal.mode(BigDecimal::ROUND_MODE, mode)
138
+ end
139
+
140
+ it 'should round a BigDecimal exactly whatever the BigDecimal limit' do
141
+ limit = BigDecimal.limit(3)
142
+ assert_equal '12345.67', number_with_precision(BigDecimal('12345.67'), precision: 2)
143
+ assert_equal '$12,345.67', number_to_currency(BigDecimal('12345.67'))
144
+ assert_equal '-12345.68', number_with_precision(BigDecimal('-12345.678'), precision: 2)
145
+ assert_equal 3, BigDecimal.limit
146
+ ensure
147
+ BigDecimal.limit(limit)
148
+ end
149
+
150
+ it 'should round a BigDecimal with a large negative exponent to zero' do
151
+ assert_equal '0.00', number_with_precision(BigDecimal('1e-10000000'), precision: 2)
152
+ assert_equal '$0.00', number_to_currency(BigDecimal('1e-10000000'))
153
+ assert_equal '0.01', number_with_precision(BigDecimal('5e-3'), precision: 2)
154
+ assert_equal '0.00', number_with_precision(BigDecimal('4.9e-3'), precision: 2)
155
+ assert_equal '-0.01', number_with_precision(BigDecimal('-5e-3'), precision: 2)
156
+ end
157
+
158
+ it 'should format a BigDecimal with an exponent up to 309 and return a larger one as given' do
159
+ assert_equal "1#{'0' * 308}.00", number_with_precision(BigDecimal('1e308'), precision: 2)
160
+ large = BigDecimal('1e309')
161
+ assert_same large, number_with_precision(large, precision: 2)
162
+ end
163
+
164
+ it 'should write a rounded BigDecimal in the encoding a Float gets' do
165
+ assert_equal number_with_precision(1.5, precision: 2).encoding, number_with_precision(BigDecimal('1.5'), precision: 2).encoding
166
+ end
167
+
100
168
  it 'should display number_with_precision with custom delimiter and separator' do
101
169
  assert_equal '31,83', number_with_precision(31.826, precision: 2, separator: ',')
102
170
  assert_equal '1.231,83', number_with_precision(1231.826, precision: 2, separator: ',', delimiter: '.')
@@ -802,6 +802,54 @@ describe 'Rendering' do
802
802
  get '/test'
803
803
  assert_equal 'test', body
804
804
  end
805
+
806
+ it 'should read and write the cached paths one thread at a time' do
807
+ # Counts the times a thread reads or writes while another is still inside: on JRuby,
808
+ # where threads run at once, that can drop entries or raise.
809
+ overlap_counting_hash = Class.new(Hash) do
810
+ attr_reader :overlaps
811
+
812
+ def initialize
813
+ super
814
+ @inside = 0
815
+ @overlaps = 0
816
+ @count_lock = Mutex.new
817
+ end
818
+
819
+ def [](key)
820
+ visit { super }
821
+ end
822
+
823
+ def []=(key, value)
824
+ visit { super }
825
+ end
826
+
827
+ private
828
+
829
+ def visit
830
+ @count_lock.synchronize { @overlaps += 1 if (@inside += 1) > 1 }
831
+ sleep 0.005
832
+ yield
833
+ ensure
834
+ @count_lock.synchronize { @inside -= 1 }
835
+ end
836
+ end
837
+ create_layout :application, 'layout <%= yield %>'
838
+ create_view :index, 'page'
839
+ mock_app do
840
+ disable :reload_templates
841
+ get('/') { render :index }
842
+ end
843
+ # Build the app's prototype first, as a server does before taking requests.
844
+ @app.prototype
845
+ caches = %i[@_cached_templates @_cached_layout].map do |name|
846
+ @app.instance_variable_set(name, overlap_counting_hash.new)
847
+ end
848
+ threads = Array.new(4) { Thread.new { Rack::MockRequest.new(@app).get('/').body } }
849
+ assert_equal ['layout page'] * 4, threads.map(&:value)
850
+ assert_equal [0, 0], caches.map(&:overlaps)
851
+ assert(caches.all? { |cache| cache.size.positive? })
852
+ end
805
853
  end
806
854
 
807
855
  describe 'rendering bug in some' do
@@ -57,6 +57,11 @@ describe 'TranslationHelpers' do
57
57
  it 'should accept an options hash' do
58
58
  assert_equal '05.03', send(name, @date, { format: :short })
59
59
  end
60
+
61
+ it 'should use the date and time formats padrino-support provides' do
62
+ assert_equal 'March 05, 2024', send(name, @date, locale: :en, format: :long)
63
+ assert_equal 'Di, 05. Mär 2024 14:07:09 +0000', send(name, @time, locale: :de)
64
+ end
60
65
  end
61
66
  end
62
67
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: padrino-helpers
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.18.6
4
+ version: 0.18.7
5
5
  platform: ruby
6
6
  authors:
7
7
  - Padrino Team
@@ -19,14 +19,14 @@ dependencies:
19
19
  requirements:
20
20
  - - '='
21
21
  - !ruby/object:Gem::Version
22
- version: 0.18.6
22
+ version: 0.18.7
23
23
  type: :runtime
24
24
  prerelease: false
25
25
  version_requirements: !ruby/object:Gem::Requirement
26
26
  requirements:
27
27
  - - '='
28
28
  - !ruby/object:Gem::Version
29
- version: 0.18.6
29
+ version: 0.18.7
30
30
  - !ruby/object:Gem::Dependency
31
31
  name: tilt
32
32
  requirement: !ruby/object:Gem::Requirement