activesupport 6.0.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activesupport might be problematic. Click here for more details.

Files changed (250) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +572 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +40 -0
  5. data/lib/active_support.rb +96 -0
  6. data/lib/active_support/actionable_error.rb +48 -0
  7. data/lib/active_support/all.rb +5 -0
  8. data/lib/active_support/array_inquirer.rb +48 -0
  9. data/lib/active_support/backtrace_cleaner.rb +132 -0
  10. data/lib/active_support/benchmarkable.rb +51 -0
  11. data/lib/active_support/builder.rb +8 -0
  12. data/lib/active_support/cache.rb +830 -0
  13. data/lib/active_support/cache/file_store.rb +196 -0
  14. data/lib/active_support/cache/mem_cache_store.rb +212 -0
  15. data/lib/active_support/cache/memory_store.rb +174 -0
  16. data/lib/active_support/cache/null_store.rb +48 -0
  17. data/lib/active_support/cache/redis_cache_store.rb +488 -0
  18. data/lib/active_support/cache/strategy/local_cache.rb +194 -0
  19. data/lib/active_support/cache/strategy/local_cache_middleware.rb +45 -0
  20. data/lib/active_support/callbacks.rb +856 -0
  21. data/lib/active_support/concern.rb +171 -0
  22. data/lib/active_support/concurrency/load_interlock_aware_monitor.rb +17 -0
  23. data/lib/active_support/concurrency/share_lock.rb +227 -0
  24. data/lib/active_support/configurable.rb +146 -0
  25. data/lib/active_support/core_ext.rb +5 -0
  26. data/lib/active_support/core_ext/array.rb +9 -0
  27. data/lib/active_support/core_ext/array/access.rb +104 -0
  28. data/lib/active_support/core_ext/array/conversions.rb +213 -0
  29. data/lib/active_support/core_ext/array/extract.rb +21 -0
  30. data/lib/active_support/core_ext/array/extract_options.rb +31 -0
  31. data/lib/active_support/core_ext/array/grouping.rb +109 -0
  32. data/lib/active_support/core_ext/array/inquiry.rb +19 -0
  33. data/lib/active_support/core_ext/array/prepend_and_append.rb +5 -0
  34. data/lib/active_support/core_ext/array/wrap.rb +48 -0
  35. data/lib/active_support/core_ext/benchmark.rb +16 -0
  36. data/lib/active_support/core_ext/big_decimal.rb +3 -0
  37. data/lib/active_support/core_ext/big_decimal/conversions.rb +14 -0
  38. data/lib/active_support/core_ext/class.rb +4 -0
  39. data/lib/active_support/core_ext/class/attribute.rb +141 -0
  40. data/lib/active_support/core_ext/class/attribute_accessors.rb +6 -0
  41. data/lib/active_support/core_ext/class/subclasses.rb +54 -0
  42. data/lib/active_support/core_ext/date.rb +7 -0
  43. data/lib/active_support/core_ext/date/acts_like.rb +10 -0
  44. data/lib/active_support/core_ext/date/blank.rb +14 -0
  45. data/lib/active_support/core_ext/date/calculations.rb +146 -0
  46. data/lib/active_support/core_ext/date/conversions.rb +96 -0
  47. data/lib/active_support/core_ext/date/zones.rb +8 -0
  48. data/lib/active_support/core_ext/date_and_time/calculations.rb +351 -0
  49. data/lib/active_support/core_ext/date_and_time/compatibility.rb +16 -0
  50. data/lib/active_support/core_ext/date_and_time/zones.rb +41 -0
  51. data/lib/active_support/core_ext/date_time.rb +7 -0
  52. data/lib/active_support/core_ext/date_time/acts_like.rb +16 -0
  53. data/lib/active_support/core_ext/date_time/blank.rb +14 -0
  54. data/lib/active_support/core_ext/date_time/calculations.rb +211 -0
  55. data/lib/active_support/core_ext/date_time/compatibility.rb +18 -0
  56. data/lib/active_support/core_ext/date_time/conversions.rb +107 -0
  57. data/lib/active_support/core_ext/digest.rb +3 -0
  58. data/lib/active_support/core_ext/digest/uuid.rb +53 -0
  59. data/lib/active_support/core_ext/enumerable.rb +188 -0
  60. data/lib/active_support/core_ext/file.rb +3 -0
  61. data/lib/active_support/core_ext/file/atomic.rb +70 -0
  62. data/lib/active_support/core_ext/hash.rb +10 -0
  63. data/lib/active_support/core_ext/hash/compact.rb +5 -0
  64. data/lib/active_support/core_ext/hash/conversions.rb +263 -0
  65. data/lib/active_support/core_ext/hash/deep_merge.rb +34 -0
  66. data/lib/active_support/core_ext/hash/deep_transform_values.rb +46 -0
  67. data/lib/active_support/core_ext/hash/except.rb +24 -0
  68. data/lib/active_support/core_ext/hash/indifferent_access.rb +24 -0
  69. data/lib/active_support/core_ext/hash/keys.rb +143 -0
  70. data/lib/active_support/core_ext/hash/reverse_merge.rb +25 -0
  71. data/lib/active_support/core_ext/hash/slice.rb +26 -0
  72. data/lib/active_support/core_ext/hash/transform_values.rb +5 -0
  73. data/lib/active_support/core_ext/integer.rb +5 -0
  74. data/lib/active_support/core_ext/integer/inflections.rb +31 -0
  75. data/lib/active_support/core_ext/integer/multiple.rb +12 -0
  76. data/lib/active_support/core_ext/integer/time.rb +22 -0
  77. data/lib/active_support/core_ext/kernel.rb +5 -0
  78. data/lib/active_support/core_ext/kernel/concern.rb +14 -0
  79. data/lib/active_support/core_ext/kernel/reporting.rb +45 -0
  80. data/lib/active_support/core_ext/kernel/singleton_class.rb +8 -0
  81. data/lib/active_support/core_ext/load_error.rb +9 -0
  82. data/lib/active_support/core_ext/marshal.rb +24 -0
  83. data/lib/active_support/core_ext/module.rb +13 -0
  84. data/lib/active_support/core_ext/module/aliasing.rb +31 -0
  85. data/lib/active_support/core_ext/module/anonymous.rb +30 -0
  86. data/lib/active_support/core_ext/module/attr_internal.rb +38 -0
  87. data/lib/active_support/core_ext/module/attribute_accessors.rb +212 -0
  88. data/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb +144 -0
  89. data/lib/active_support/core_ext/module/concerning.rb +134 -0
  90. data/lib/active_support/core_ext/module/delegation.rb +313 -0
  91. data/lib/active_support/core_ext/module/deprecation.rb +25 -0
  92. data/lib/active_support/core_ext/module/introspection.rb +86 -0
  93. data/lib/active_support/core_ext/module/reachable.rb +6 -0
  94. data/lib/active_support/core_ext/module/redefine_method.rb +40 -0
  95. data/lib/active_support/core_ext/module/remove_method.rb +17 -0
  96. data/lib/active_support/core_ext/name_error.rb +38 -0
  97. data/lib/active_support/core_ext/numeric.rb +5 -0
  98. data/lib/active_support/core_ext/numeric/bytes.rb +66 -0
  99. data/lib/active_support/core_ext/numeric/conversions.rb +136 -0
  100. data/lib/active_support/core_ext/numeric/inquiry.rb +5 -0
  101. data/lib/active_support/core_ext/numeric/time.rb +66 -0
  102. data/lib/active_support/core_ext/object.rb +16 -0
  103. data/lib/active_support/core_ext/object/acts_like.rb +21 -0
  104. data/lib/active_support/core_ext/object/blank.rb +155 -0
  105. data/lib/active_support/core_ext/object/conversions.rb +6 -0
  106. data/lib/active_support/core_ext/object/deep_dup.rb +55 -0
  107. data/lib/active_support/core_ext/object/duplicable.rb +49 -0
  108. data/lib/active_support/core_ext/object/inclusion.rb +29 -0
  109. data/lib/active_support/core_ext/object/instance_variables.rb +30 -0
  110. data/lib/active_support/core_ext/object/json.rb +228 -0
  111. data/lib/active_support/core_ext/object/to_param.rb +3 -0
  112. data/lib/active_support/core_ext/object/to_query.rb +89 -0
  113. data/lib/active_support/core_ext/object/try.rb +156 -0
  114. data/lib/active_support/core_ext/object/with_options.rb +82 -0
  115. data/lib/active_support/core_ext/range.rb +7 -0
  116. data/lib/active_support/core_ext/range/compare_range.rb +70 -0
  117. data/lib/active_support/core_ext/range/conversions.rb +41 -0
  118. data/lib/active_support/core_ext/range/each.rb +25 -0
  119. data/lib/active_support/core_ext/range/include_range.rb +9 -0
  120. data/lib/active_support/core_ext/range/include_time_with_zone.rb +23 -0
  121. data/lib/active_support/core_ext/range/overlaps.rb +10 -0
  122. data/lib/active_support/core_ext/regexp.rb +7 -0
  123. data/lib/active_support/core_ext/securerandom.rb +45 -0
  124. data/lib/active_support/core_ext/string.rb +15 -0
  125. data/lib/active_support/core_ext/string/access.rb +114 -0
  126. data/lib/active_support/core_ext/string/behavior.rb +8 -0
  127. data/lib/active_support/core_ext/string/conversions.rb +59 -0
  128. data/lib/active_support/core_ext/string/exclude.rb +13 -0
  129. data/lib/active_support/core_ext/string/filters.rb +145 -0
  130. data/lib/active_support/core_ext/string/indent.rb +45 -0
  131. data/lib/active_support/core_ext/string/inflections.rb +259 -0
  132. data/lib/active_support/core_ext/string/inquiry.rb +15 -0
  133. data/lib/active_support/core_ext/string/multibyte.rb +58 -0
  134. data/lib/active_support/core_ext/string/output_safety.rb +314 -0
  135. data/lib/active_support/core_ext/string/starts_ends_with.rb +6 -0
  136. data/lib/active_support/core_ext/string/strip.rb +27 -0
  137. data/lib/active_support/core_ext/string/zones.rb +16 -0
  138. data/lib/active_support/core_ext/time.rb +7 -0
  139. data/lib/active_support/core_ext/time/acts_like.rb +10 -0
  140. data/lib/active_support/core_ext/time/calculations.rb +344 -0
  141. data/lib/active_support/core_ext/time/compatibility.rb +16 -0
  142. data/lib/active_support/core_ext/time/conversions.rb +72 -0
  143. data/lib/active_support/core_ext/time/zones.rb +113 -0
  144. data/lib/active_support/core_ext/uri.rb +25 -0
  145. data/lib/active_support/current_attributes.rb +203 -0
  146. data/lib/active_support/dependencies.rb +806 -0
  147. data/lib/active_support/dependencies/autoload.rb +79 -0
  148. data/lib/active_support/dependencies/interlock.rb +57 -0
  149. data/lib/active_support/dependencies/zeitwerk_integration.rb +110 -0
  150. data/lib/active_support/deprecation.rb +46 -0
  151. data/lib/active_support/deprecation/behaviors.rb +109 -0
  152. data/lib/active_support/deprecation/constant_accessor.rb +52 -0
  153. data/lib/active_support/deprecation/instance_delegator.rb +39 -0
  154. data/lib/active_support/deprecation/method_wrappers.rb +78 -0
  155. data/lib/active_support/deprecation/proxy_wrappers.rb +173 -0
  156. data/lib/active_support/deprecation/reporting.rb +114 -0
  157. data/lib/active_support/descendants_tracker.rb +109 -0
  158. data/lib/active_support/digest.rb +20 -0
  159. data/lib/active_support/duration.rb +433 -0
  160. data/lib/active_support/duration/iso8601_parser.rb +124 -0
  161. data/lib/active_support/duration/iso8601_serializer.rb +54 -0
  162. data/lib/active_support/encrypted_configuration.rb +45 -0
  163. data/lib/active_support/encrypted_file.rb +100 -0
  164. data/lib/active_support/evented_file_update_checker.rb +235 -0
  165. data/lib/active_support/execution_wrapper.rb +129 -0
  166. data/lib/active_support/executor.rb +8 -0
  167. data/lib/active_support/file_update_checker.rb +163 -0
  168. data/lib/active_support/gem_version.rb +17 -0
  169. data/lib/active_support/gzip.rb +38 -0
  170. data/lib/active_support/hash_with_indifferent_access.rb +399 -0
  171. data/lib/active_support/i18n.rb +16 -0
  172. data/lib/active_support/i18n_railtie.rb +126 -0
  173. data/lib/active_support/inflections.rb +72 -0
  174. data/lib/active_support/inflector.rb +9 -0
  175. data/lib/active_support/inflector/inflections.rb +257 -0
  176. data/lib/active_support/inflector/methods.rb +398 -0
  177. data/lib/active_support/inflector/transliterate.rb +147 -0
  178. data/lib/active_support/json.rb +4 -0
  179. data/lib/active_support/json/decoding.rb +76 -0
  180. data/lib/active_support/json/encoding.rb +134 -0
  181. data/lib/active_support/key_generator.rb +41 -0
  182. data/lib/active_support/lazy_load_hooks.rb +82 -0
  183. data/lib/active_support/locale/en.rb +31 -0
  184. data/lib/active_support/locale/en.yml +135 -0
  185. data/lib/active_support/log_subscriber.rb +135 -0
  186. data/lib/active_support/log_subscriber/test_helper.rb +106 -0
  187. data/lib/active_support/logger.rb +93 -0
  188. data/lib/active_support/logger_silence.rb +45 -0
  189. data/lib/active_support/logger_thread_safe_level.rb +56 -0
  190. data/lib/active_support/message_encryptor.rb +227 -0
  191. data/lib/active_support/message_verifier.rb +205 -0
  192. data/lib/active_support/messages/metadata.rb +71 -0
  193. data/lib/active_support/messages/rotation_configuration.rb +22 -0
  194. data/lib/active_support/messages/rotator.rb +56 -0
  195. data/lib/active_support/multibyte.rb +23 -0
  196. data/lib/active_support/multibyte/chars.rb +216 -0
  197. data/lib/active_support/multibyte/unicode.rb +157 -0
  198. data/lib/active_support/notifications.rb +253 -0
  199. data/lib/active_support/notifications/fanout.rb +244 -0
  200. data/lib/active_support/notifications/instrumenter.rb +164 -0
  201. data/lib/active_support/number_helper.rb +378 -0
  202. data/lib/active_support/number_helper/number_converter.rb +184 -0
  203. data/lib/active_support/number_helper/number_to_currency_converter.rb +46 -0
  204. data/lib/active_support/number_helper/number_to_delimited_converter.rb +31 -0
  205. data/lib/active_support/number_helper/number_to_human_converter.rb +70 -0
  206. data/lib/active_support/number_helper/number_to_human_size_converter.rb +61 -0
  207. data/lib/active_support/number_helper/number_to_percentage_converter.rb +16 -0
  208. data/lib/active_support/number_helper/number_to_phone_converter.rb +60 -0
  209. data/lib/active_support/number_helper/number_to_rounded_converter.rb +56 -0
  210. data/lib/active_support/number_helper/rounding_helper.rb +66 -0
  211. data/lib/active_support/option_merger.rb +27 -0
  212. data/lib/active_support/ordered_hash.rb +50 -0
  213. data/lib/active_support/ordered_options.rb +85 -0
  214. data/lib/active_support/parameter_filter.rb +129 -0
  215. data/lib/active_support/per_thread_registry.rb +60 -0
  216. data/lib/active_support/proxy_object.rb +15 -0
  217. data/lib/active_support/rails.rb +29 -0
  218. data/lib/active_support/railtie.rb +80 -0
  219. data/lib/active_support/reloader.rb +130 -0
  220. data/lib/active_support/rescuable.rb +174 -0
  221. data/lib/active_support/security_utils.rb +31 -0
  222. data/lib/active_support/string_inquirer.rb +34 -0
  223. data/lib/active_support/subscriber.rb +169 -0
  224. data/lib/active_support/tagged_logging.rb +88 -0
  225. data/lib/active_support/test_case.rb +163 -0
  226. data/lib/active_support/testing/assertions.rb +228 -0
  227. data/lib/active_support/testing/autorun.rb +7 -0
  228. data/lib/active_support/testing/constant_lookup.rb +51 -0
  229. data/lib/active_support/testing/declarative.rb +28 -0
  230. data/lib/active_support/testing/deprecation.rb +38 -0
  231. data/lib/active_support/testing/file_fixtures.rb +38 -0
  232. data/lib/active_support/testing/isolation.rb +110 -0
  233. data/lib/active_support/testing/method_call_assertions.rb +70 -0
  234. data/lib/active_support/testing/parallelization.rb +128 -0
  235. data/lib/active_support/testing/setup_and_teardown.rb +55 -0
  236. data/lib/active_support/testing/stream.rb +44 -0
  237. data/lib/active_support/testing/tagged_logging.rb +27 -0
  238. data/lib/active_support/testing/time_helpers.rb +200 -0
  239. data/lib/active_support/time.rb +20 -0
  240. data/lib/active_support/time_with_zone.rb +561 -0
  241. data/lib/active_support/values/time_zone.rb +570 -0
  242. data/lib/active_support/version.rb +10 -0
  243. data/lib/active_support/xml_mini.rb +202 -0
  244. data/lib/active_support/xml_mini/jdom.rb +183 -0
  245. data/lib/active_support/xml_mini/libxml.rb +80 -0
  246. data/lib/active_support/xml_mini/libxmlsax.rb +83 -0
  247. data/lib/active_support/xml_mini/nokogiri.rb +83 -0
  248. data/lib/active_support/xml_mini/nokogirisax.rb +86 -0
  249. data/lib/active_support/xml_mini/rexml.rb +130 -0
  250. metadata +385 -0
@@ -0,0 +1,398 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/inflections"
4
+
5
+ module ActiveSupport
6
+ # The Inflector transforms words from singular to plural, class names to table
7
+ # names, modularized class names to ones without, and class names to foreign
8
+ # keys. The default inflections for pluralization, singularization, and
9
+ # uncountable words are kept in inflections.rb.
10
+ #
11
+ # The Rails core team has stated patches for the inflections library will not
12
+ # be accepted in order to avoid breaking legacy applications which may be
13
+ # relying on errant inflections. If you discover an incorrect inflection and
14
+ # require it for your application or wish to define rules for languages other
15
+ # than English, please correct or add them yourself (explained below).
16
+ module Inflector
17
+ extend self
18
+
19
+ # Returns the plural form of the word in the string.
20
+ #
21
+ # If passed an optional +locale+ parameter, the word will be
22
+ # pluralized using rules defined for that language. By default,
23
+ # this parameter is set to <tt>:en</tt>.
24
+ #
25
+ # pluralize('post') # => "posts"
26
+ # pluralize('octopus') # => "octopi"
27
+ # pluralize('sheep') # => "sheep"
28
+ # pluralize('words') # => "words"
29
+ # pluralize('CamelOctopus') # => "CamelOctopi"
30
+ # pluralize('ley', :es) # => "leyes"
31
+ def pluralize(word, locale = :en)
32
+ apply_inflections(word, inflections(locale).plurals, locale)
33
+ end
34
+
35
+ # The reverse of #pluralize, returns the singular form of a word in a
36
+ # string.
37
+ #
38
+ # If passed an optional +locale+ parameter, the word will be
39
+ # singularized using rules defined for that language. By default,
40
+ # this parameter is set to <tt>:en</tt>.
41
+ #
42
+ # singularize('posts') # => "post"
43
+ # singularize('octopi') # => "octopus"
44
+ # singularize('sheep') # => "sheep"
45
+ # singularize('word') # => "word"
46
+ # singularize('CamelOctopi') # => "CamelOctopus"
47
+ # singularize('leyes', :es) # => "ley"
48
+ def singularize(word, locale = :en)
49
+ apply_inflections(word, inflections(locale).singulars, locale)
50
+ end
51
+
52
+ # Converts strings to UpperCamelCase.
53
+ # If the +uppercase_first_letter+ parameter is set to false, then produces
54
+ # lowerCamelCase.
55
+ #
56
+ # Also converts '/' to '::' which is useful for converting
57
+ # paths to namespaces.
58
+ #
59
+ # camelize('active_model') # => "ActiveModel"
60
+ # camelize('active_model', false) # => "activeModel"
61
+ # camelize('active_model/errors') # => "ActiveModel::Errors"
62
+ # camelize('active_model/errors', false) # => "activeModel::Errors"
63
+ #
64
+ # As a rule of thumb you can think of +camelize+ as the inverse of
65
+ # #underscore, though there are cases where that does not hold:
66
+ #
67
+ # camelize(underscore('SSLError')) # => "SslError"
68
+ def camelize(term, uppercase_first_letter = true)
69
+ string = term.to_s
70
+ if uppercase_first_letter
71
+ string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize }
72
+ else
73
+ string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase }
74
+ end
75
+ string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
76
+ string.gsub!("/", "::")
77
+ string
78
+ end
79
+
80
+ # Makes an underscored, lowercase form from the expression in the string.
81
+ #
82
+ # Changes '::' to '/' to convert namespaces to paths.
83
+ #
84
+ # underscore('ActiveModel') # => "active_model"
85
+ # underscore('ActiveModel::Errors') # => "active_model/errors"
86
+ #
87
+ # As a rule of thumb you can think of +underscore+ as the inverse of
88
+ # #camelize, though there are cases where that does not hold:
89
+ #
90
+ # camelize(underscore('SSLError')) # => "SslError"
91
+ def underscore(camel_cased_word)
92
+ return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word)
93
+ word = camel_cased_word.to_s.gsub("::", "/")
94
+ word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" }
95
+ word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
96
+ word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
97
+ word.tr!("-", "_")
98
+ word.downcase!
99
+ word
100
+ end
101
+
102
+ # Tweaks an attribute name for display to end users.
103
+ #
104
+ # Specifically, performs these transformations:
105
+ #
106
+ # * Applies human inflection rules to the argument.
107
+ # * Deletes leading underscores, if any.
108
+ # * Removes a "_id" suffix if present.
109
+ # * Replaces underscores with spaces, if any.
110
+ # * Downcases all words except acronyms.
111
+ # * Capitalizes the first word.
112
+ # The capitalization of the first word can be turned off by setting the
113
+ # +:capitalize+ option to false (default is true).
114
+ #
115
+ # The trailing '_id' can be kept and capitalized by setting the
116
+ # optional parameter +keep_id_suffix+ to true (default is false).
117
+ #
118
+ # humanize('employee_salary') # => "Employee salary"
119
+ # humanize('author_id') # => "Author"
120
+ # humanize('author_id', capitalize: false) # => "author"
121
+ # humanize('_id') # => "Id"
122
+ # humanize('author_id', keep_id_suffix: true) # => "Author Id"
123
+ #
124
+ # If "SSL" was defined to be an acronym:
125
+ #
126
+ # humanize('ssl_error') # => "SSL error"
127
+ #
128
+ def humanize(lower_case_and_underscored_word, capitalize: true, keep_id_suffix: false)
129
+ result = lower_case_and_underscored_word.to_s.dup
130
+
131
+ inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
132
+
133
+ result.sub!(/\A_+/, "")
134
+ unless keep_id_suffix
135
+ result.sub!(/_id\z/, "")
136
+ end
137
+ result.tr!("_", " ")
138
+
139
+ result.gsub!(/([a-z\d]*)/i) do |match|
140
+ "#{inflections.acronyms[match.downcase] || match.downcase}"
141
+ end
142
+
143
+ if capitalize
144
+ result.sub!(/\A\w/) { |match| match.upcase }
145
+ end
146
+
147
+ result
148
+ end
149
+
150
+ # Converts just the first character to uppercase.
151
+ #
152
+ # upcase_first('what a Lovely Day') # => "What a Lovely Day"
153
+ # upcase_first('w') # => "W"
154
+ # upcase_first('') # => ""
155
+ def upcase_first(string)
156
+ string.length > 0 ? string[0].upcase.concat(string[1..-1]) : ""
157
+ end
158
+
159
+ # Capitalizes all the words and replaces some characters in the string to
160
+ # create a nicer looking title. +titleize+ is meant for creating pretty
161
+ # output. It is not used in the Rails internals.
162
+ #
163
+ # The trailing '_id','Id'.. can be kept and capitalized by setting the
164
+ # optional parameter +keep_id_suffix+ to true.
165
+ # By default, this parameter is false.
166
+ #
167
+ # +titleize+ is also aliased as +titlecase+.
168
+ #
169
+ # titleize('man from the boondocks') # => "Man From The Boondocks"
170
+ # titleize('x-men: the last stand') # => "X Men: The Last Stand"
171
+ # titleize('TheManWithoutAPast') # => "The Man Without A Past"
172
+ # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark"
173
+ # titleize('string_ending_with_id', keep_id_suffix: true) # => "String Ending With Id"
174
+ def titleize(word, keep_id_suffix: false)
175
+ humanize(underscore(word), keep_id_suffix: keep_id_suffix).gsub(/\b(?<!\w['’`])[a-z]/) do |match|
176
+ match.capitalize
177
+ end
178
+ end
179
+
180
+ # Creates the name of a table like Rails does for models to table names.
181
+ # This method uses the #pluralize method on the last word in the string.
182
+ #
183
+ # tableize('RawScaledScorer') # => "raw_scaled_scorers"
184
+ # tableize('ham_and_egg') # => "ham_and_eggs"
185
+ # tableize('fancyCategory') # => "fancy_categories"
186
+ def tableize(class_name)
187
+ pluralize(underscore(class_name))
188
+ end
189
+
190
+ # Creates a class name from a plural table name like Rails does for table
191
+ # names to models. Note that this returns a string and not a Class (To
192
+ # convert to an actual class follow +classify+ with #constantize).
193
+ #
194
+ # classify('ham_and_eggs') # => "HamAndEgg"
195
+ # classify('posts') # => "Post"
196
+ #
197
+ # Singular names are not handled correctly:
198
+ #
199
+ # classify('calculus') # => "Calculus"
200
+ def classify(table_name)
201
+ # strip out any leading schema name
202
+ camelize(singularize(table_name.to_s.sub(/.*\./, "")))
203
+ end
204
+
205
+ # Replaces underscores with dashes in the string.
206
+ #
207
+ # dasherize('puni_puni') # => "puni-puni"
208
+ def dasherize(underscored_word)
209
+ underscored_word.tr("_", "-")
210
+ end
211
+
212
+ # Removes the module part from the expression in the string.
213
+ #
214
+ # demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections"
215
+ # demodulize('Inflections') # => "Inflections"
216
+ # demodulize('::Inflections') # => "Inflections"
217
+ # demodulize('') # => ""
218
+ #
219
+ # See also #deconstantize.
220
+ def demodulize(path)
221
+ path = path.to_s
222
+ if i = path.rindex("::")
223
+ path[(i + 2)..-1]
224
+ else
225
+ path
226
+ end
227
+ end
228
+
229
+ # Removes the rightmost segment from the constant expression in the string.
230
+ #
231
+ # deconstantize('Net::HTTP') # => "Net"
232
+ # deconstantize('::Net::HTTP') # => "::Net"
233
+ # deconstantize('String') # => ""
234
+ # deconstantize('::String') # => ""
235
+ # deconstantize('') # => ""
236
+ #
237
+ # See also #demodulize.
238
+ def deconstantize(path)
239
+ path.to_s[0, path.rindex("::") || 0] # implementation based on the one in facets' Module#spacename
240
+ end
241
+
242
+ # Creates a foreign key name from a class name.
243
+ # +separate_class_name_and_id_with_underscore+ sets whether
244
+ # the method should put '_' between the name and 'id'.
245
+ #
246
+ # foreign_key('Message') # => "message_id"
247
+ # foreign_key('Message', false) # => "messageid"
248
+ # foreign_key('Admin::Post') # => "post_id"
249
+ def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
250
+ underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
251
+ end
252
+
253
+ # Tries to find a constant with the name specified in the argument string.
254
+ #
255
+ # constantize('Module') # => Module
256
+ # constantize('Foo::Bar') # => Foo::Bar
257
+ #
258
+ # The name is assumed to be the one of a top-level constant, no matter
259
+ # whether it starts with "::" or not. No lexical context is taken into
260
+ # account:
261
+ #
262
+ # C = 'outside'
263
+ # module M
264
+ # C = 'inside'
265
+ # C # => 'inside'
266
+ # constantize('C') # => 'outside', same as ::C
267
+ # end
268
+ #
269
+ # NameError is raised when the name is not in CamelCase or the constant is
270
+ # unknown.
271
+ def constantize(camel_cased_word)
272
+ names = camel_cased_word.split("::")
273
+
274
+ # Trigger a built-in NameError exception including the ill-formed constant in the message.
275
+ Object.const_get(camel_cased_word) if names.empty?
276
+
277
+ # Remove the first blank element in case of '::ClassName' notation.
278
+ names.shift if names.size > 1 && names.first.empty?
279
+
280
+ names.inject(Object) do |constant, name|
281
+ if constant == Object
282
+ constant.const_get(name)
283
+ else
284
+ candidate = constant.const_get(name)
285
+ next candidate if constant.const_defined?(name, false)
286
+ next candidate unless Object.const_defined?(name)
287
+
288
+ # Go down the ancestors to check if it is owned directly. The check
289
+ # stops when we reach Object or the end of ancestors tree.
290
+ constant = constant.ancestors.inject(constant) do |const, ancestor|
291
+ break const if ancestor == Object
292
+ break ancestor if ancestor.const_defined?(name, false)
293
+ const
294
+ end
295
+
296
+ # owner is in Object, so raise
297
+ constant.const_get(name, false)
298
+ end
299
+ end
300
+ end
301
+
302
+ # Tries to find a constant with the name specified in the argument string.
303
+ #
304
+ # safe_constantize('Module') # => Module
305
+ # safe_constantize('Foo::Bar') # => Foo::Bar
306
+ #
307
+ # The name is assumed to be the one of a top-level constant, no matter
308
+ # whether it starts with "::" or not. No lexical context is taken into
309
+ # account:
310
+ #
311
+ # C = 'outside'
312
+ # module M
313
+ # C = 'inside'
314
+ # C # => 'inside'
315
+ # safe_constantize('C') # => 'outside', same as ::C
316
+ # end
317
+ #
318
+ # +nil+ is returned when the name is not in CamelCase or the constant (or
319
+ # part of it) is unknown.
320
+ #
321
+ # safe_constantize('blargle') # => nil
322
+ # safe_constantize('UnknownModule') # => nil
323
+ # safe_constantize('UnknownModule::Foo::Bar') # => nil
324
+ def safe_constantize(camel_cased_word)
325
+ constantize(camel_cased_word)
326
+ rescue NameError => e
327
+ raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) ||
328
+ e.name.to_s == camel_cased_word.to_s)
329
+ rescue ArgumentError => e
330
+ raise unless /not missing constant #{const_regexp(camel_cased_word)}!$/.match?(e.message)
331
+ rescue LoadError => e
332
+ raise unless /Unable to autoload constant #{const_regexp(camel_cased_word)}/.match?(e.message)
333
+ end
334
+
335
+ # Returns the suffix that should be added to a number to denote the position
336
+ # in an ordered sequence such as 1st, 2nd, 3rd, 4th.
337
+ #
338
+ # ordinal(1) # => "st"
339
+ # ordinal(2) # => "nd"
340
+ # ordinal(1002) # => "nd"
341
+ # ordinal(1003) # => "rd"
342
+ # ordinal(-11) # => "th"
343
+ # ordinal(-1021) # => "st"
344
+ def ordinal(number)
345
+ I18n.translate("number.nth.ordinals", number: number)
346
+ end
347
+
348
+ # Turns a number into an ordinal string used to denote the position in an
349
+ # ordered sequence such as 1st, 2nd, 3rd, 4th.
350
+ #
351
+ # ordinalize(1) # => "1st"
352
+ # ordinalize(2) # => "2nd"
353
+ # ordinalize(1002) # => "1002nd"
354
+ # ordinalize(1003) # => "1003rd"
355
+ # ordinalize(-11) # => "-11th"
356
+ # ordinalize(-1021) # => "-1021st"
357
+ def ordinalize(number)
358
+ I18n.translate("number.nth.ordinalized", number: number)
359
+ end
360
+
361
+ private
362
+
363
+ # Mounts a regular expression, returned as a string to ease interpolation,
364
+ # that will match part by part the given constant.
365
+ #
366
+ # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?"
367
+ # const_regexp("::") # => "::"
368
+ def const_regexp(camel_cased_word)
369
+ parts = camel_cased_word.split("::")
370
+
371
+ return Regexp.escape(camel_cased_word) if parts.blank?
372
+
373
+ last = parts.pop
374
+
375
+ parts.reverse.inject(last) do |acc, part|
376
+ part.empty? ? acc : "#{part}(::#{acc})?"
377
+ end
378
+ end
379
+
380
+ # Applies inflection rules for +singularize+ and +pluralize+.
381
+ #
382
+ # If passed an optional +locale+ parameter, the uncountables will be
383
+ # found for that locale.
384
+ #
385
+ # apply_inflections('post', inflections.plurals, :en) # => "posts"
386
+ # apply_inflections('posts', inflections.singulars, :en) # => "post"
387
+ def apply_inflections(word, rules, locale = :en)
388
+ result = word.to_s.dup
389
+
390
+ if word.empty? || inflections(locale).uncountables.uncountable?(result)
391
+ result
392
+ else
393
+ rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
394
+ result
395
+ end
396
+ end
397
+ end
398
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/string/multibyte"
4
+ require "active_support/i18n"
5
+
6
+ module ActiveSupport
7
+ module Inflector
8
+ # Replaces non-ASCII characters with an ASCII approximation, or if none
9
+ # exists, a replacement character which defaults to "?".
10
+ #
11
+ # transliterate('Ærøskøbing')
12
+ # # => "AEroskobing"
13
+ #
14
+ # Default approximations are provided for Western/Latin characters,
15
+ # e.g, "ø", "ñ", "é", "ß", etc.
16
+ #
17
+ # This method is I18n aware, so you can set up custom approximations for a
18
+ # locale. This can be useful, for example, to transliterate German's "ü"
19
+ # and "ö" to "ue" and "oe", or to add support for transliterating Russian
20
+ # to ASCII.
21
+ #
22
+ # In order to make your custom transliterations available, you must set
23
+ # them as the <tt>i18n.transliterate.rule</tt> i18n key:
24
+ #
25
+ # # Store the transliterations in locales/de.yml
26
+ # i18n:
27
+ # transliterate:
28
+ # rule:
29
+ # ü: "ue"
30
+ # ö: "oe"
31
+ #
32
+ # # Or set them using Ruby
33
+ # I18n.backend.store_translations(:de, i18n: {
34
+ # transliterate: {
35
+ # rule: {
36
+ # 'ü' => 'ue',
37
+ # 'ö' => 'oe'
38
+ # }
39
+ # }
40
+ # })
41
+ #
42
+ # The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that
43
+ # maps characters to ASCII approximations as shown above, or, for more
44
+ # complex requirements, a Proc:
45
+ #
46
+ # I18n.backend.store_translations(:de, i18n: {
47
+ # transliterate: {
48
+ # rule: ->(string) { MyTransliterator.transliterate(string) }
49
+ # }
50
+ # })
51
+ #
52
+ # Now you can have different transliterations for each locale:
53
+ #
54
+ # transliterate('Jürgen', locale: :en)
55
+ # # => "Jurgen"
56
+ #
57
+ # transliterate('Jürgen', locale: :de)
58
+ # # => "Juergen"
59
+ #
60
+ # Transliteration is restricted to UTF-8, US-ASCII and GB18030 strings
61
+ # Other encodings will raise an ArgumentError.
62
+ def transliterate(string, replacement = "?", locale: nil)
63
+ string = string.dup if string.frozen?
64
+ raise ArgumentError, "Can only transliterate strings. Received #{string.class.name}" unless string.is_a?(String)
65
+
66
+ allowed_encodings = [Encoding::UTF_8, Encoding::US_ASCII, Encoding::GB18030]
67
+ raise ArgumentError, "Can not transliterate strings with #{string.encoding} encoding" unless allowed_encodings.include?(string.encoding)
68
+
69
+ input_encoding = string.encoding
70
+
71
+ # US-ASCII is a subset of UTF-8 so we'll force encoding as UTF-8 if
72
+ # US-ASCII is given. This way we can let tidy_bytes handle the string
73
+ # in the same way as we do for UTF-8
74
+ string.force_encoding(Encoding::UTF_8) if string.encoding == Encoding::US_ASCII
75
+
76
+ # GB18030 is Unicode compatible but is not a direct mapping so needs to be
77
+ # transcoded. Using invalid/undef :replace will result in loss of data in
78
+ # the event of invalid characters, but since tidy_bytes will replace
79
+ # invalid/undef with a "?" we're safe to do the same beforehand
80
+ string.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace) if string.encoding == Encoding::GB18030
81
+
82
+ transliterated = I18n.transliterate(
83
+ ActiveSupport::Multibyte::Unicode.tidy_bytes(string).unicode_normalize(:nfc),
84
+ replacement: replacement,
85
+ locale: locale
86
+ )
87
+
88
+ # Restore the string encoding of the input if it was not UTF-8.
89
+ # Apply invalid/undef :replace as tidy_bytes does
90
+ transliterated.encode!(input_encoding, invalid: :replace, undef: :replace) if input_encoding != transliterated.encoding
91
+
92
+ transliterated
93
+ end
94
+
95
+ # Replaces special characters in a string so that it may be used as part of
96
+ # a 'pretty' URL.
97
+ #
98
+ # parameterize("Donald E. Knuth") # => "donald-e-knuth"
99
+ # parameterize("^très|Jolie-- ") # => "tres-jolie"
100
+ #
101
+ # To use a custom separator, override the +separator+ argument.
102
+ #
103
+ # parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth"
104
+ # parameterize("^très|Jolie__ ", separator: '_') # => "tres_jolie"
105
+ #
106
+ # To preserve the case of the characters in a string, use the +preserve_case+ argument.
107
+ #
108
+ # parameterize("Donald E. Knuth", preserve_case: true) # => "Donald-E-Knuth"
109
+ # parameterize("^très|Jolie-- ", preserve_case: true) # => "tres-Jolie"
110
+ #
111
+ # It preserves dashes and underscores unless they are used as separators:
112
+ #
113
+ # parameterize("^très|Jolie__ ") # => "tres-jolie__"
114
+ # parameterize("^très|Jolie-- ", separator: "_") # => "tres_jolie--"
115
+ # parameterize("^très_Jolie-- ", separator: ".") # => "tres_jolie--"
116
+ #
117
+ # If the optional parameter +locale+ is specified,
118
+ # the word will be parameterized as a word of that language.
119
+ # By default, this parameter is set to <tt>nil</tt> and it will use
120
+ # the configured <tt>I18n.locale<tt>.
121
+ def parameterize(string, separator: "-", preserve_case: false, locale: nil)
122
+ # Replace accented chars with their ASCII equivalents.
123
+ parameterized_string = transliterate(string, locale: locale)
124
+
125
+ # Turn unwanted chars into the separator.
126
+ parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator)
127
+
128
+ unless separator.nil? || separator.empty?
129
+ if separator == "-"
130
+ re_duplicate_separator = /-{2,}/
131
+ re_leading_trailing_separator = /^-|-$/i
132
+ else
133
+ re_sep = Regexp.escape(separator)
134
+ re_duplicate_separator = /#{re_sep}{2,}/
135
+ re_leading_trailing_separator = /^#{re_sep}|#{re_sep}$/i
136
+ end
137
+ # No more than one of the separator in a row.
138
+ parameterized_string.gsub!(re_duplicate_separator, separator)
139
+ # Remove leading/trailing separator.
140
+ parameterized_string.gsub!(re_leading_trailing_separator, "")
141
+ end
142
+
143
+ parameterized_string.downcase! unless preserve_case
144
+ parameterized_string
145
+ end
146
+ end
147
+ end