activesupport 5.0.7.1

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 (236) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +1013 -0
  3. data/MIT-LICENSE +20 -0
  4. data/README.rdoc +39 -0
  5. data/lib/active_support.rb +99 -0
  6. data/lib/active_support/all.rb +3 -0
  7. data/lib/active_support/array_inquirer.rb +44 -0
  8. data/lib/active_support/backtrace_cleaner.rb +103 -0
  9. data/lib/active_support/benchmarkable.rb +49 -0
  10. data/lib/active_support/builder.rb +6 -0
  11. data/lib/active_support/cache.rb +701 -0
  12. data/lib/active_support/cache/file_store.rb +204 -0
  13. data/lib/active_support/cache/mem_cache_store.rb +207 -0
  14. data/lib/active_support/cache/memory_store.rb +167 -0
  15. data/lib/active_support/cache/null_store.rb +41 -0
  16. data/lib/active_support/cache/strategy/local_cache.rb +172 -0
  17. data/lib/active_support/cache/strategy/local_cache_middleware.rb +44 -0
  18. data/lib/active_support/callbacks.rb +791 -0
  19. data/lib/active_support/concern.rb +142 -0
  20. data/lib/active_support/concurrency/latch.rb +26 -0
  21. data/lib/active_support/concurrency/share_lock.rb +226 -0
  22. data/lib/active_support/configurable.rb +148 -0
  23. data/lib/active_support/core_ext.rb +4 -0
  24. data/lib/active_support/core_ext/array.rb +7 -0
  25. data/lib/active_support/core_ext/array/access.rb +90 -0
  26. data/lib/active_support/core_ext/array/conversions.rb +211 -0
  27. data/lib/active_support/core_ext/array/extract_options.rb +29 -0
  28. data/lib/active_support/core_ext/array/grouping.rb +107 -0
  29. data/lib/active_support/core_ext/array/inquiry.rb +17 -0
  30. data/lib/active_support/core_ext/array/prepend_and_append.rb +7 -0
  31. data/lib/active_support/core_ext/array/wrap.rb +46 -0
  32. data/lib/active_support/core_ext/benchmark.rb +14 -0
  33. data/lib/active_support/core_ext/big_decimal.rb +1 -0
  34. data/lib/active_support/core_ext/big_decimal/conversions.rb +14 -0
  35. data/lib/active_support/core_ext/class.rb +2 -0
  36. data/lib/active_support/core_ext/class/attribute.rb +128 -0
  37. data/lib/active_support/core_ext/class/attribute_accessors.rb +4 -0
  38. data/lib/active_support/core_ext/class/subclasses.rb +41 -0
  39. data/lib/active_support/core_ext/date.rb +5 -0
  40. data/lib/active_support/core_ext/date/acts_like.rb +8 -0
  41. data/lib/active_support/core_ext/date/blank.rb +12 -0
  42. data/lib/active_support/core_ext/date/calculations.rb +143 -0
  43. data/lib/active_support/core_ext/date/conversions.rb +95 -0
  44. data/lib/active_support/core_ext/date/zones.rb +6 -0
  45. data/lib/active_support/core_ext/date_and_time/calculations.rb +335 -0
  46. data/lib/active_support/core_ext/date_and_time/compatibility.rb +14 -0
  47. data/lib/active_support/core_ext/date_and_time/zones.rb +40 -0
  48. data/lib/active_support/core_ext/date_time.rb +5 -0
  49. data/lib/active_support/core_ext/date_time/acts_like.rb +14 -0
  50. data/lib/active_support/core_ext/date_time/blank.rb +12 -0
  51. data/lib/active_support/core_ext/date_time/calculations.rb +199 -0
  52. data/lib/active_support/core_ext/date_time/compatibility.rb +16 -0
  53. data/lib/active_support/core_ext/date_time/conversions.rb +105 -0
  54. data/lib/active_support/core_ext/digest/uuid.rb +51 -0
  55. data/lib/active_support/core_ext/enumerable.rb +146 -0
  56. data/lib/active_support/core_ext/file.rb +1 -0
  57. data/lib/active_support/core_ext/file/atomic.rb +68 -0
  58. data/lib/active_support/core_ext/hash.rb +9 -0
  59. data/lib/active_support/core_ext/hash/compact.rb +24 -0
  60. data/lib/active_support/core_ext/hash/conversions.rb +262 -0
  61. data/lib/active_support/core_ext/hash/deep_merge.rb +38 -0
  62. data/lib/active_support/core_ext/hash/except.rb +22 -0
  63. data/lib/active_support/core_ext/hash/indifferent_access.rb +23 -0
  64. data/lib/active_support/core_ext/hash/keys.rb +170 -0
  65. data/lib/active_support/core_ext/hash/reverse_merge.rb +22 -0
  66. data/lib/active_support/core_ext/hash/slice.rb +48 -0
  67. data/lib/active_support/core_ext/hash/transform_values.rb +29 -0
  68. data/lib/active_support/core_ext/integer.rb +3 -0
  69. data/lib/active_support/core_ext/integer/inflections.rb +29 -0
  70. data/lib/active_support/core_ext/integer/multiple.rb +10 -0
  71. data/lib/active_support/core_ext/integer/time.rb +29 -0
  72. data/lib/active_support/core_ext/kernel.rb +4 -0
  73. data/lib/active_support/core_ext/kernel/agnostics.rb +11 -0
  74. data/lib/active_support/core_ext/kernel/concern.rb +12 -0
  75. data/lib/active_support/core_ext/kernel/debugger.rb +3 -0
  76. data/lib/active_support/core_ext/kernel/reporting.rb +43 -0
  77. data/lib/active_support/core_ext/kernel/singleton_class.rb +6 -0
  78. data/lib/active_support/core_ext/load_error.rb +31 -0
  79. data/lib/active_support/core_ext/marshal.rb +22 -0
  80. data/lib/active_support/core_ext/module.rb +12 -0
  81. data/lib/active_support/core_ext/module/aliasing.rb +74 -0
  82. data/lib/active_support/core_ext/module/anonymous.rb +28 -0
  83. data/lib/active_support/core_ext/module/attr_internal.rb +36 -0
  84. data/lib/active_support/core_ext/module/attribute_accessors.rb +212 -0
  85. data/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb +141 -0
  86. data/lib/active_support/core_ext/module/concerning.rb +135 -0
  87. data/lib/active_support/core_ext/module/delegation.rb +216 -0
  88. data/lib/active_support/core_ext/module/deprecation.rb +23 -0
  89. data/lib/active_support/core_ext/module/introspection.rb +68 -0
  90. data/lib/active_support/core_ext/module/method_transplanting.rb +3 -0
  91. data/lib/active_support/core_ext/module/qualified_const.rb +70 -0
  92. data/lib/active_support/core_ext/module/reachable.rb +8 -0
  93. data/lib/active_support/core_ext/module/remove_method.rb +35 -0
  94. data/lib/active_support/core_ext/name_error.rb +31 -0
  95. data/lib/active_support/core_ext/numeric.rb +4 -0
  96. data/lib/active_support/core_ext/numeric/bytes.rb +64 -0
  97. data/lib/active_support/core_ext/numeric/conversions.rb +144 -0
  98. data/lib/active_support/core_ext/numeric/inquiry.rb +26 -0
  99. data/lib/active_support/core_ext/numeric/time.rb +74 -0
  100. data/lib/active_support/core_ext/object.rb +14 -0
  101. data/lib/active_support/core_ext/object/acts_like.rb +10 -0
  102. data/lib/active_support/core_ext/object/blank.rb +143 -0
  103. data/lib/active_support/core_ext/object/conversions.rb +4 -0
  104. data/lib/active_support/core_ext/object/deep_dup.rb +53 -0
  105. data/lib/active_support/core_ext/object/duplicable.rb +124 -0
  106. data/lib/active_support/core_ext/object/inclusion.rb +27 -0
  107. data/lib/active_support/core_ext/object/instance_variables.rb +28 -0
  108. data/lib/active_support/core_ext/object/json.rb +205 -0
  109. data/lib/active_support/core_ext/object/to_param.rb +1 -0
  110. data/lib/active_support/core_ext/object/to_query.rb +84 -0
  111. data/lib/active_support/core_ext/object/try.rb +146 -0
  112. data/lib/active_support/core_ext/object/with_options.rb +69 -0
  113. data/lib/active_support/core_ext/range.rb +4 -0
  114. data/lib/active_support/core_ext/range/conversions.rb +31 -0
  115. data/lib/active_support/core_ext/range/each.rb +21 -0
  116. data/lib/active_support/core_ext/range/include_range.rb +23 -0
  117. data/lib/active_support/core_ext/range/overlaps.rb +8 -0
  118. data/lib/active_support/core_ext/regexp.rb +5 -0
  119. data/lib/active_support/core_ext/securerandom.rb +23 -0
  120. data/lib/active_support/core_ext/string.rb +13 -0
  121. data/lib/active_support/core_ext/string/access.rb +104 -0
  122. data/lib/active_support/core_ext/string/behavior.rb +6 -0
  123. data/lib/active_support/core_ext/string/conversions.rb +57 -0
  124. data/lib/active_support/core_ext/string/exclude.rb +11 -0
  125. data/lib/active_support/core_ext/string/filters.rb +102 -0
  126. data/lib/active_support/core_ext/string/indent.rb +43 -0
  127. data/lib/active_support/core_ext/string/inflections.rb +244 -0
  128. data/lib/active_support/core_ext/string/inquiry.rb +13 -0
  129. data/lib/active_support/core_ext/string/multibyte.rb +53 -0
  130. data/lib/active_support/core_ext/string/output_safety.rb +260 -0
  131. data/lib/active_support/core_ext/string/starts_ends_with.rb +4 -0
  132. data/lib/active_support/core_ext/string/strip.rb +23 -0
  133. data/lib/active_support/core_ext/string/zones.rb +14 -0
  134. data/lib/active_support/core_ext/struct.rb +3 -0
  135. data/lib/active_support/core_ext/time.rb +5 -0
  136. data/lib/active_support/core_ext/time/acts_like.rb +8 -0
  137. data/lib/active_support/core_ext/time/calculations.rb +290 -0
  138. data/lib/active_support/core_ext/time/compatibility.rb +14 -0
  139. data/lib/active_support/core_ext/time/conversions.rb +67 -0
  140. data/lib/active_support/core_ext/time/marshal.rb +3 -0
  141. data/lib/active_support/core_ext/time/zones.rb +111 -0
  142. data/lib/active_support/core_ext/uri.rb +24 -0
  143. data/lib/active_support/dependencies.rb +755 -0
  144. data/lib/active_support/dependencies/autoload.rb +77 -0
  145. data/lib/active_support/dependencies/interlock.rb +55 -0
  146. data/lib/active_support/deprecation.rb +43 -0
  147. data/lib/active_support/deprecation/behaviors.rb +90 -0
  148. data/lib/active_support/deprecation/instance_delegator.rb +37 -0
  149. data/lib/active_support/deprecation/method_wrappers.rb +70 -0
  150. data/lib/active_support/deprecation/proxy_wrappers.rb +149 -0
  151. data/lib/active_support/deprecation/reporting.rb +112 -0
  152. data/lib/active_support/descendants_tracker.rb +60 -0
  153. data/lib/active_support/duration.rb +235 -0
  154. data/lib/active_support/duration/iso8601_parser.rb +122 -0
  155. data/lib/active_support/duration/iso8601_serializer.rb +51 -0
  156. data/lib/active_support/evented_file_update_checker.rb +199 -0
  157. data/lib/active_support/execution_wrapper.rb +126 -0
  158. data/lib/active_support/executor.rb +6 -0
  159. data/lib/active_support/file_update_checker.rb +157 -0
  160. data/lib/active_support/gem_version.rb +15 -0
  161. data/lib/active_support/gzip.rb +36 -0
  162. data/lib/active_support/hash_with_indifferent_access.rb +329 -0
  163. data/lib/active_support/i18n.rb +13 -0
  164. data/lib/active_support/i18n_railtie.rb +115 -0
  165. data/lib/active_support/inflections.rb +70 -0
  166. data/lib/active_support/inflector.rb +7 -0
  167. data/lib/active_support/inflector/inflections.rb +242 -0
  168. data/lib/active_support/inflector/methods.rb +390 -0
  169. data/lib/active_support/inflector/transliterate.rb +112 -0
  170. data/lib/active_support/json.rb +2 -0
  171. data/lib/active_support/json/decoding.rb +74 -0
  172. data/lib/active_support/json/encoding.rb +127 -0
  173. data/lib/active_support/key_generator.rb +71 -0
  174. data/lib/active_support/lazy_load_hooks.rb +76 -0
  175. data/lib/active_support/locale/en.yml +135 -0
  176. data/lib/active_support/log_subscriber.rb +109 -0
  177. data/lib/active_support/log_subscriber/test_helper.rb +104 -0
  178. data/lib/active_support/logger.rb +106 -0
  179. data/lib/active_support/logger_silence.rb +28 -0
  180. data/lib/active_support/logger_thread_safe_level.rb +31 -0
  181. data/lib/active_support/message_encryptor.rb +114 -0
  182. data/lib/active_support/message_verifier.rb +134 -0
  183. data/lib/active_support/multibyte.rb +21 -0
  184. data/lib/active_support/multibyte/chars.rb +231 -0
  185. data/lib/active_support/multibyte/unicode.rb +413 -0
  186. data/lib/active_support/notifications.rb +212 -0
  187. data/lib/active_support/notifications/fanout.rb +157 -0
  188. data/lib/active_support/notifications/instrumenter.rb +91 -0
  189. data/lib/active_support/number_helper.rb +368 -0
  190. data/lib/active_support/number_helper/number_converter.rb +182 -0
  191. data/lib/active_support/number_helper/number_to_currency_converter.rb +44 -0
  192. data/lib/active_support/number_helper/number_to_delimited_converter.rb +28 -0
  193. data/lib/active_support/number_helper/number_to_human_converter.rb +68 -0
  194. data/lib/active_support/number_helper/number_to_human_size_converter.rb +62 -0
  195. data/lib/active_support/number_helper/number_to_percentage_converter.rb +12 -0
  196. data/lib/active_support/number_helper/number_to_phone_converter.rb +58 -0
  197. data/lib/active_support/number_helper/number_to_rounded_converter.rb +92 -0
  198. data/lib/active_support/option_merger.rb +25 -0
  199. data/lib/active_support/ordered_hash.rb +48 -0
  200. data/lib/active_support/ordered_options.rb +81 -0
  201. data/lib/active_support/per_thread_registry.rb +58 -0
  202. data/lib/active_support/proxy_object.rb +13 -0
  203. data/lib/active_support/rails.rb +27 -0
  204. data/lib/active_support/railtie.rb +51 -0
  205. data/lib/active_support/reloader.rb +129 -0
  206. data/lib/active_support/rescuable.rb +173 -0
  207. data/lib/active_support/security_utils.rb +27 -0
  208. data/lib/active_support/string_inquirer.rb +26 -0
  209. data/lib/active_support/subscriber.rb +120 -0
  210. data/lib/active_support/tagged_logging.rb +77 -0
  211. data/lib/active_support/test_case.rb +88 -0
  212. data/lib/active_support/testing/assertions.rb +99 -0
  213. data/lib/active_support/testing/autorun.rb +5 -0
  214. data/lib/active_support/testing/constant_lookup.rb +50 -0
  215. data/lib/active_support/testing/declarative.rb +26 -0
  216. data/lib/active_support/testing/deprecation.rb +36 -0
  217. data/lib/active_support/testing/file_fixtures.rb +34 -0
  218. data/lib/active_support/testing/isolation.rb +115 -0
  219. data/lib/active_support/testing/method_call_assertions.rb +41 -0
  220. data/lib/active_support/testing/setup_and_teardown.rb +50 -0
  221. data/lib/active_support/testing/stream.rb +42 -0
  222. data/lib/active_support/testing/tagged_logging.rb +25 -0
  223. data/lib/active_support/testing/time_helpers.rb +136 -0
  224. data/lib/active_support/time.rb +18 -0
  225. data/lib/active_support/time_with_zone.rb +511 -0
  226. data/lib/active_support/values/time_zone.rb +484 -0
  227. data/lib/active_support/values/unicode_tables.dat +0 -0
  228. data/lib/active_support/version.rb +8 -0
  229. data/lib/active_support/xml_mini.rb +209 -0
  230. data/lib/active_support/xml_mini/jdom.rb +181 -0
  231. data/lib/active_support/xml_mini/libxml.rb +77 -0
  232. data/lib/active_support/xml_mini/libxmlsax.rb +82 -0
  233. data/lib/active_support/xml_mini/nokogiri.rb +81 -0
  234. data/lib/active_support/xml_mini/nokogirisax.rb +85 -0
  235. data/lib/active_support/xml_mini/rexml.rb +128 -0
  236. metadata +350 -0
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2005-2016 David Heinemeier Hansson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,39 @@
1
+ = Active Support -- Utility classes and Ruby extensions from Rails
2
+
3
+ Active Support is a collection of utility classes and standard library
4
+ extensions that were found useful for the Rails framework. These additions
5
+ reside in this package so they can be loaded as needed in Ruby projects
6
+ outside of Rails.
7
+
8
+
9
+ == Download and installation
10
+
11
+ The latest version of Active Support can be installed with RubyGems:
12
+
13
+ $ gem install activesupport
14
+
15
+ Source code can be downloaded as part of the Rails project on GitHub:
16
+
17
+ * https://github.com/rails/rails/tree/5-0-stable/activesupport
18
+
19
+
20
+ == License
21
+
22
+ Active Support is released under the MIT license:
23
+
24
+ * http://www.opensource.org/licenses/MIT
25
+
26
+
27
+ == Support
28
+
29
+ API documentation is at:
30
+
31
+ * http://api.rubyonrails.org
32
+
33
+ Bug reports can be filed for the Ruby on Rails project here:
34
+
35
+ * https://github.com/rails/rails/issues
36
+
37
+ Feature requests should be discussed on the rails-core mailing list here:
38
+
39
+ * https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core
@@ -0,0 +1,99 @@
1
+ #--
2
+ # Copyright (c) 2005-2016 David Heinemeier Hansson
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #++
23
+
24
+ require 'securerandom'
25
+ require "active_support/dependencies/autoload"
26
+ require "active_support/version"
27
+ require "active_support/logger"
28
+ require "active_support/lazy_load_hooks"
29
+ require "active_support/core_ext/date_and_time/compatibility"
30
+
31
+ module ActiveSupport
32
+ extend ActiveSupport::Autoload
33
+
34
+ autoload :Concern
35
+ autoload :Dependencies
36
+ autoload :DescendantsTracker
37
+ autoload :ExecutionWrapper
38
+ autoload :Executor
39
+ autoload :FileUpdateChecker
40
+ autoload :EventedFileUpdateChecker
41
+ autoload :LogSubscriber
42
+ autoload :Notifications
43
+ autoload :Reloader
44
+
45
+ eager_autoload do
46
+ autoload :BacktraceCleaner
47
+ autoload :ProxyObject
48
+ autoload :Benchmarkable
49
+ autoload :Cache
50
+ autoload :Callbacks
51
+ autoload :Configurable
52
+ autoload :Deprecation
53
+ autoload :Gzip
54
+ autoload :Inflector
55
+ autoload :JSON
56
+ autoload :KeyGenerator
57
+ autoload :MessageEncryptor
58
+ autoload :MessageVerifier
59
+ autoload :Multibyte
60
+ autoload :NumberHelper
61
+ autoload :OptionMerger
62
+ autoload :OrderedHash
63
+ autoload :OrderedOptions
64
+ autoload :StringInquirer
65
+ autoload :TaggedLogging
66
+ autoload :XmlMini
67
+ autoload :ArrayInquirer
68
+ end
69
+
70
+ autoload :Rescuable
71
+ autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
72
+ autoload :TestCase
73
+
74
+ def self.eager_load!
75
+ super
76
+
77
+ NumberHelper.eager_load!
78
+ end
79
+
80
+ cattr_accessor :test_order # :nodoc:
81
+
82
+ def self.halt_callback_chains_on_return_false
83
+ Callbacks.halt_and_display_warning_on_return_false
84
+ end
85
+
86
+ def self.halt_callback_chains_on_return_false=(value)
87
+ Callbacks.halt_and_display_warning_on_return_false = value
88
+ end
89
+
90
+ def self.to_time_preserves_timezone
91
+ DateAndTime::Compatibility.preserve_timezone
92
+ end
93
+
94
+ def self.to_time_preserves_timezone=(value)
95
+ DateAndTime::Compatibility.preserve_timezone = value
96
+ end
97
+ end
98
+
99
+ autoload :I18n, "active_support/i18n"
@@ -0,0 +1,3 @@
1
+ require 'active_support'
2
+ require 'active_support/time'
3
+ require 'active_support/core_ext'
@@ -0,0 +1,44 @@
1
+ module ActiveSupport
2
+ # Wrapping an array in an +ArrayInquirer+ gives a friendlier way to check
3
+ # its string-like contents:
4
+ #
5
+ # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
6
+ #
7
+ # variants.phone? # => true
8
+ # variants.tablet? # => true
9
+ # variants.desktop? # => false
10
+ class ArrayInquirer < Array
11
+ # Passes each element of +candidates+ collection to ArrayInquirer collection.
12
+ # The method returns true if at least one element is the same. If +candidates+
13
+ # collection is not given, method returns true.
14
+ #
15
+ # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
16
+ #
17
+ # variants.any? # => true
18
+ # variants.any?(:phone, :tablet) # => true
19
+ # variants.any?('phone', 'desktop') # => true
20
+ # variants.any?(:desktop, :watch) # => false
21
+ def any?(*candidates, &block)
22
+ if candidates.none?
23
+ super
24
+ else
25
+ candidates.any? do |candidate|
26
+ include?(candidate.to_sym) || include?(candidate.to_s)
27
+ end
28
+ end
29
+ end
30
+
31
+ private
32
+ def respond_to_missing?(name, include_private = false)
33
+ name[-1] == '?'
34
+ end
35
+
36
+ def method_missing(name, *args)
37
+ if name[-1] == '?'
38
+ any?(name[0..-2])
39
+ else
40
+ super
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,103 @@
1
+ module ActiveSupport
2
+ # Backtraces often include many lines that are not relevant for the context
3
+ # under review. This makes it hard to find the signal amongst the backtrace
4
+ # noise, and adds debugging time. With a BacktraceCleaner, filters and
5
+ # silencers are used to remove the noisy lines, so that only the most relevant
6
+ # lines remain.
7
+ #
8
+ # Filters are used to modify lines of data, while silencers are used to remove
9
+ # lines entirely. The typical filter use case is to remove lengthy path
10
+ # information from the start of each line, and view file paths relevant to the
11
+ # app directory instead of the file system root. The typical silencer use case
12
+ # is to exclude the output of a noisy library from the backtrace, so that you
13
+ # can focus on the rest.
14
+ #
15
+ # bc = BacktraceCleaner.new
16
+ # bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix
17
+ # bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
18
+ # bc.clean(exception.backtrace) # perform the cleanup
19
+ #
20
+ # To reconfigure an existing BacktraceCleaner (like the default one in Rails)
21
+ # and show as much data as possible, you can always call
22
+ # <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
23
+ # backtrace to a pristine state. If you need to reconfigure an existing
24
+ # BacktraceCleaner so that it does not filter or modify the paths of any lines
25
+ # of the backtrace, you can call <tt>BacktraceCleaner#remove_filters!</tt>
26
+ # These two methods will give you a completely untouched backtrace.
27
+ #
28
+ # Inspired by the Quiet Backtrace gem by thoughtbot.
29
+ class BacktraceCleaner
30
+ def initialize
31
+ @filters, @silencers = [], []
32
+ end
33
+
34
+ # Returns the backtrace after all filters and silencers have been run
35
+ # against it. Filters run first, then silencers.
36
+ def clean(backtrace, kind = :silent)
37
+ filtered = filter_backtrace(backtrace)
38
+
39
+ case kind
40
+ when :silent
41
+ silence(filtered)
42
+ when :noise
43
+ noise(filtered)
44
+ else
45
+ filtered
46
+ end
47
+ end
48
+ alias :filter :clean
49
+
50
+ # Adds a filter from the block provided. Each line in the backtrace will be
51
+ # mapped against this filter.
52
+ #
53
+ # # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
54
+ # backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
55
+ def add_filter(&block)
56
+ @filters << block
57
+ end
58
+
59
+ # Adds a silencer from the block provided. If the silencer returns +true+
60
+ # for a given line, it will be excluded from the clean backtrace.
61
+ #
62
+ # # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
63
+ # backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
64
+ def add_silencer(&block)
65
+ @silencers << block
66
+ end
67
+
68
+ # Removes all silencers, but leaves in the filters. Useful if your
69
+ # context of debugging suddenly expands as you suspect a bug in one of
70
+ # the libraries you use.
71
+ def remove_silencers!
72
+ @silencers = []
73
+ end
74
+
75
+ # Removes all filters, but leaves in the silencers. Useful if you suddenly
76
+ # need to see entire filepaths in the backtrace that you had already
77
+ # filtered out.
78
+ def remove_filters!
79
+ @filters = []
80
+ end
81
+
82
+ private
83
+ def filter_backtrace(backtrace)
84
+ @filters.each do |f|
85
+ backtrace = backtrace.map { |line| f.call(line) }
86
+ end
87
+
88
+ backtrace
89
+ end
90
+
91
+ def silence(backtrace)
92
+ @silencers.each do |s|
93
+ backtrace = backtrace.reject { |line| s.call(line) }
94
+ end
95
+
96
+ backtrace
97
+ end
98
+
99
+ def noise(backtrace)
100
+ backtrace - silence(backtrace)
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,49 @@
1
+ require 'active_support/core_ext/benchmark'
2
+ require 'active_support/core_ext/hash/keys'
3
+
4
+ module ActiveSupport
5
+ module Benchmarkable
6
+ # Allows you to measure the execution time of a block in a template and
7
+ # records the result to the log. Wrap this block around expensive operations
8
+ # or possible bottlenecks to get a time reading for the operation. For
9
+ # example, let's say you thought your file processing method was taking too
10
+ # long; you could wrap it in a benchmark block.
11
+ #
12
+ # <% benchmark 'Process data files' do %>
13
+ # <%= expensive_files_operation %>
14
+ # <% end %>
15
+ #
16
+ # That would add something like "Process data files (345.2ms)" to the log,
17
+ # which you can then use to compare timings when optimizing your code.
18
+ #
19
+ # You may give an optional logger level (<tt>:debug</tt>, <tt>:info</tt>,
20
+ # <tt>:warn</tt>, <tt>:error</tt>) as the <tt>:level</tt> option. The
21
+ # default logger level value is <tt>:info</tt>.
22
+ #
23
+ # <% benchmark 'Low-level files', level: :debug do %>
24
+ # <%= lowlevel_files_operation %>
25
+ # <% end %>
26
+ #
27
+ # Finally, you can pass true as the third argument to silence all log
28
+ # activity (other than the timing information) from inside the block. This
29
+ # is great for boiling down a noisy block to just a single statement that
30
+ # produces one log line:
31
+ #
32
+ # <% benchmark 'Process data files', level: :info, silence: true do %>
33
+ # <%= expensive_and_chatty_files_operation %>
34
+ # <% end %>
35
+ def benchmark(message = "Benchmarking", options = {})
36
+ if logger
37
+ options.assert_valid_keys(:level, :silence)
38
+ options[:level] ||= :info
39
+
40
+ result = nil
41
+ ms = Benchmark.ms { result = options[:silence] ? logger.silence { yield } : yield }
42
+ logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
43
+ result
44
+ else
45
+ yield
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,6 @@
1
+ begin
2
+ require 'builder'
3
+ rescue LoadError => e
4
+ $stderr.puts "You don't have builder installed in your application. Please add it to your Gemfile and run bundle install"
5
+ raise e
6
+ end
@@ -0,0 +1,701 @@
1
+ require 'benchmark'
2
+ require 'zlib'
3
+ require 'active_support/core_ext/array/extract_options'
4
+ require 'active_support/core_ext/array/wrap'
5
+ require 'active_support/core_ext/benchmark'
6
+ require 'active_support/core_ext/module/attribute_accessors'
7
+ require 'active_support/core_ext/numeric/bytes'
8
+ require 'active_support/core_ext/numeric/time'
9
+ require 'active_support/core_ext/object/to_param'
10
+ require 'active_support/core_ext/string/inflections'
11
+ require 'active_support/core_ext/string/strip'
12
+
13
+ module ActiveSupport
14
+ # See ActiveSupport::Cache::Store for documentation.
15
+ module Cache
16
+ autoload :FileStore, 'active_support/cache/file_store'
17
+ autoload :MemoryStore, 'active_support/cache/memory_store'
18
+ autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
19
+ autoload :NullStore, 'active_support/cache/null_store'
20
+
21
+ # These options mean something to all cache implementations. Individual cache
22
+ # implementations may support additional options.
23
+ UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
24
+
25
+ module Strategy
26
+ autoload :LocalCache, 'active_support/cache/strategy/local_cache'
27
+ end
28
+
29
+ class << self
30
+ # Creates a new Store object according to the given options.
31
+ #
32
+ # If no arguments are passed to this method, then a new
33
+ # ActiveSupport::Cache::MemoryStore object will be returned.
34
+ #
35
+ # If you pass a Symbol as the first argument, then a corresponding cache
36
+ # store class under the ActiveSupport::Cache namespace will be created.
37
+ # For example:
38
+ #
39
+ # ActiveSupport::Cache.lookup_store(:memory_store)
40
+ # # => returns a new ActiveSupport::Cache::MemoryStore object
41
+ #
42
+ # ActiveSupport::Cache.lookup_store(:mem_cache_store)
43
+ # # => returns a new ActiveSupport::Cache::MemCacheStore object
44
+ #
45
+ # Any additional arguments will be passed to the corresponding cache store
46
+ # class's constructor:
47
+ #
48
+ # ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
49
+ # # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache')
50
+ #
51
+ # If the first argument is not a Symbol, then it will simply be returned:
52
+ #
53
+ # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
54
+ # # => returns MyOwnCacheStore.new
55
+ def lookup_store(*store_option)
56
+ store, *parameters = *Array.wrap(store_option).flatten
57
+
58
+ case store
59
+ when Symbol
60
+ retrieve_store_class(store).new(*parameters)
61
+ when nil
62
+ ActiveSupport::Cache::MemoryStore.new
63
+ else
64
+ store
65
+ end
66
+ end
67
+
68
+ # Expands out the +key+ argument into a key that can be used for the
69
+ # cache store. Optionally accepts a namespace, and all keys will be
70
+ # scoped within that namespace.
71
+ #
72
+ # If the +key+ argument provided is an array, or responds to +to_a+, then
73
+ # each of elements in the array will be turned into parameters/keys and
74
+ # concatenated into a single key. For example:
75
+ #
76
+ # expand_cache_key([:foo, :bar]) # => "foo/bar"
77
+ # expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
78
+ #
79
+ # The +key+ argument can also respond to +cache_key+ or +to_param+.
80
+ def expand_cache_key(key, namespace = nil)
81
+ expanded_cache_key = namespace ? "#{namespace}/" : ""
82
+
83
+ if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
84
+ expanded_cache_key << "#{prefix}/"
85
+ end
86
+
87
+ expanded_cache_key << retrieve_cache_key(key)
88
+ expanded_cache_key
89
+ end
90
+
91
+ private
92
+ def retrieve_cache_key(key)
93
+ case
94
+ when key.respond_to?(:cache_key) then key.cache_key
95
+ when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
96
+ when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
97
+ else key.to_param
98
+ end.to_s
99
+ end
100
+
101
+ # Obtains the specified cache store class, given the name of the +store+.
102
+ # Raises an error when the store class cannot be found.
103
+ def retrieve_store_class(store)
104
+ require "active_support/cache/#{store}"
105
+ rescue LoadError => e
106
+ raise "Could not find cache store adapter for #{store} (#{e})"
107
+ else
108
+ ActiveSupport::Cache.const_get(store.to_s.camelize)
109
+ end
110
+ end
111
+
112
+ # An abstract cache store class. There are multiple cache store
113
+ # implementations, each having its own additional features. See the classes
114
+ # under the ActiveSupport::Cache module, e.g.
115
+ # ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
116
+ # popular cache store for large production websites.
117
+ #
118
+ # Some implementations may not support all methods beyond the basic cache
119
+ # methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
120
+ #
121
+ # ActiveSupport::Cache::Store can store any serializable Ruby object.
122
+ #
123
+ # cache = ActiveSupport::Cache::MemoryStore.new
124
+ #
125
+ # cache.read('city') # => nil
126
+ # cache.write('city', "Duckburgh")
127
+ # cache.read('city') # => "Duckburgh"
128
+ #
129
+ # Keys are always translated into Strings and are case sensitive. When an
130
+ # object is specified as a key and has a +cache_key+ method defined, this
131
+ # method will be called to define the key. Otherwise, the +to_param+
132
+ # method will be called. Hashes and Arrays can also be used as keys. The
133
+ # elements will be delimited by slashes, and the elements within a Hash
134
+ # will be sorted by key so they are consistent.
135
+ #
136
+ # cache.read('city') == cache.read(:city) # => true
137
+ #
138
+ # Nil values can be cached.
139
+ #
140
+ # If your cache is on a shared infrastructure, you can define a namespace
141
+ # for your cache entries. If a namespace is defined, it will be prefixed on
142
+ # to every key. The namespace can be either a static value or a Proc. If it
143
+ # is a Proc, it will be invoked when each key is evaluated so that you can
144
+ # use application logic to invalidate keys.
145
+ #
146
+ # cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
147
+ # @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
148
+ #
149
+ # Caches can also store values in a compressed format to save space and
150
+ # reduce time spent sending data. Since there is overhead, values must be
151
+ # large enough to warrant compression. To turn on compression either pass
152
+ # <tt>compress: true</tt> in the initializer or as an option to +fetch+
153
+ # or +write+. To specify the threshold at which to compress values, set the
154
+ # <tt>:compress_threshold</tt> option. The default threshold is 16K.
155
+ class Store
156
+ cattr_accessor :logger, :instance_writer => true
157
+
158
+ attr_reader :silence, :options
159
+ alias :silence? :silence
160
+
161
+ # Creates a new cache. The options will be passed to any write method calls
162
+ # except for <tt>:namespace</tt> which can be used to set the global
163
+ # namespace for the cache.
164
+ def initialize(options = nil)
165
+ @options = options ? options.dup : {}
166
+ end
167
+
168
+ # Silences the logger.
169
+ def silence!
170
+ @silence = true
171
+ self
172
+ end
173
+
174
+ # Silences the logger within a block.
175
+ def mute
176
+ previous_silence, @silence = defined?(@silence) && @silence, true
177
+ yield
178
+ ensure
179
+ @silence = previous_silence
180
+ end
181
+
182
+ # Fetches data from the cache, using the given key. If there is data in
183
+ # the cache with the given key, then that data is returned.
184
+ #
185
+ # If there is no such data in the cache (a cache miss), then +nil+ will be
186
+ # returned. However, if a block has been passed, that block will be passed
187
+ # the key and executed in the event of a cache miss. The return value of the
188
+ # block will be written to the cache under the given cache key, and that
189
+ # return value will be returned.
190
+ #
191
+ # cache.write('today', 'Monday')
192
+ # cache.fetch('today') # => "Monday"
193
+ #
194
+ # cache.fetch('city') # => nil
195
+ # cache.fetch('city') do
196
+ # 'Duckburgh'
197
+ # end
198
+ # cache.fetch('city') # => "Duckburgh"
199
+ #
200
+ # You may also specify additional options via the +options+ argument.
201
+ # Setting <tt>force: true</tt> forces a cache "miss," meaning we treat
202
+ # the cache value as missing even if it's present. Passing a block is
203
+ # required when `force` is true so this always results in a cache write.
204
+ #
205
+ # cache.write('today', 'Monday')
206
+ # cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday'
207
+ # cache.fetch('today', force: true) # => ArgumentError
208
+ #
209
+ # The `:force` option is useful when you're calling some other method to
210
+ # ask whether you should force a cache write. Otherwise, it's clearer to
211
+ # just call `Cache#write`.
212
+ #
213
+ # Setting <tt>:compress</tt> will store a large cache entry set by the call
214
+ # in a compressed format.
215
+ #
216
+ # Setting <tt>:expires_in</tt> will set an expiration time on the cache.
217
+ # All caches support auto-expiring content after a specified number of
218
+ # seconds. This value can be specified as an option to the constructor
219
+ # (in which case all entries will be affected), or it can be supplied to
220
+ # the +fetch+ or +write+ method to effect just one entry.
221
+ #
222
+ # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
223
+ # cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
224
+ #
225
+ # Setting <tt>:race_condition_ttl</tt> is very useful in situations where
226
+ # a cache entry is used very frequently and is under heavy load. If a
227
+ # cache expires and due to heavy load several different processes will try
228
+ # to read data natively and then they all will try to write to cache. To
229
+ # avoid that case the first process to find an expired cache entry will
230
+ # bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
231
+ # Yes, this process is extending the time for a stale value by another few
232
+ # seconds. Because of extended life of the previous cache, other processes
233
+ # will continue to use slightly stale data for a just a bit longer. In the
234
+ # meantime that first process will go ahead and will write into cache the
235
+ # new value. After that all the processes will start getting the new value.
236
+ # The key is to keep <tt>:race_condition_ttl</tt> small.
237
+ #
238
+ # If the process regenerating the entry errors out, the entry will be
239
+ # regenerated after the specified number of seconds. Also note that the
240
+ # life of stale cache is extended only if it expired recently. Otherwise
241
+ # a new value is generated and <tt>:race_condition_ttl</tt> does not play
242
+ # any role.
243
+ #
244
+ # # Set all values to expire after one minute.
245
+ # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
246
+ #
247
+ # cache.write('foo', 'original value')
248
+ # val_1 = nil
249
+ # val_2 = nil
250
+ # sleep 60
251
+ #
252
+ # Thread.new do
253
+ # val_1 = cache.fetch('foo', race_condition_ttl: 10) do
254
+ # sleep 1
255
+ # 'new value 1'
256
+ # end
257
+ # end
258
+ #
259
+ # Thread.new do
260
+ # val_2 = cache.fetch('foo', race_condition_ttl: 10) do
261
+ # 'new value 2'
262
+ # end
263
+ # end
264
+ #
265
+ # cache.fetch('foo') # => "original value"
266
+ # sleep 10 # First thread extended the life of cache by another 10 seconds
267
+ # cache.fetch('foo') # => "new value 1"
268
+ # val_1 # => "new value 1"
269
+ # val_2 # => "original value"
270
+ #
271
+ # Other options will be handled by the specific cache store implementation.
272
+ # Internally, #fetch calls #read_entry, and calls #write_entry on a cache
273
+ # miss. +options+ will be passed to the #read and #write calls.
274
+ #
275
+ # For example, MemCacheStore's #write method supports the +:raw+
276
+ # option, which tells the memcached server to store all values as strings.
277
+ # We can use this option with #fetch too:
278
+ #
279
+ # cache = ActiveSupport::Cache::MemCacheStore.new
280
+ # cache.fetch("foo", force: true, raw: true) do
281
+ # :bar
282
+ # end
283
+ # cache.fetch('foo') # => "bar"
284
+ def fetch(name, options = nil)
285
+ if block_given?
286
+ options = merged_options(options)
287
+ key = normalize_key(name, options)
288
+
289
+ entry = nil
290
+ instrument(:read, name, options) do |payload|
291
+ cached_entry = read_entry(key, options) unless options[:force]
292
+ entry = handle_expired_entry(cached_entry, key, options)
293
+ payload[:super_operation] = :fetch if payload
294
+ payload[:hit] = !!entry if payload
295
+ end
296
+
297
+ if entry
298
+ get_entry_value(entry, name, options)
299
+ else
300
+ save_block_result_to_cache(name, options) { |_name| yield _name }
301
+ end
302
+ elsif options && options[:force]
303
+ raise ArgumentError, 'Missing block: Calling `Cache#fetch` with `force: true` requires a block.'
304
+ else
305
+ read(name, options)
306
+ end
307
+ end
308
+
309
+ # Fetches data from the cache, using the given key. If there is data in
310
+ # the cache with the given key, then that data is returned. Otherwise,
311
+ # +nil+ is returned.
312
+ #
313
+ # Options are passed to the underlying cache implementation.
314
+ def read(name, options = nil)
315
+ options = merged_options(options)
316
+ key = normalize_key(name, options)
317
+ instrument(:read, name, options) do |payload|
318
+ entry = read_entry(key, options)
319
+ if entry
320
+ if entry.expired?
321
+ delete_entry(key, options)
322
+ payload[:hit] = false if payload
323
+ nil
324
+ else
325
+ payload[:hit] = true if payload
326
+ entry.value
327
+ end
328
+ else
329
+ payload[:hit] = false if payload
330
+ nil
331
+ end
332
+ end
333
+ end
334
+
335
+ # Reads multiple values at once from the cache. Options can be passed
336
+ # in the last argument.
337
+ #
338
+ # Some cache implementation may optimize this method.
339
+ #
340
+ # Returns a hash mapping the names provided to the values found.
341
+ def read_multi(*names)
342
+ options = names.extract_options!
343
+ options = merged_options(options)
344
+
345
+ results = {}
346
+ names.each do |name|
347
+ key = normalize_key(name, options)
348
+ entry = read_entry(key, options)
349
+ if entry
350
+ if entry.expired?
351
+ delete_entry(key, options)
352
+ else
353
+ results[name] = entry.value
354
+ end
355
+ end
356
+ end
357
+ results
358
+ end
359
+
360
+ # Fetches data from the cache, using the given keys. If there is data in
361
+ # the cache with the given keys, then that data is returned. Otherwise,
362
+ # the supplied block is called for each key for which there was no data,
363
+ # and the result will be written to the cache and returned.
364
+ #
365
+ # Options are passed to the underlying cache implementation.
366
+ #
367
+ # Returns a hash with the data for each of the names. For example:
368
+ #
369
+ # cache.write("bim", "bam")
370
+ # cache.fetch_multi("bim", "unknown_key") do |key|
371
+ # "Fallback value for key: #{key}"
372
+ # end
373
+ # # => { "bim" => "bam",
374
+ # # "unknown_key" => "Fallback value for key: unknown_key" }
375
+ #
376
+ def fetch_multi(*names)
377
+ options = names.extract_options!
378
+ options = merged_options(options)
379
+ results = read_multi(*names, options)
380
+
381
+ names.each_with_object({}) do |name, memo|
382
+ memo[name] = results.fetch(name) do
383
+ value = yield name
384
+ write(name, value, options)
385
+ value
386
+ end
387
+ end
388
+ end
389
+
390
+ # Writes the value to the cache, with the key.
391
+ #
392
+ # Options are passed to the underlying cache implementation.
393
+ def write(name, value, options = nil)
394
+ options = merged_options(options)
395
+
396
+ instrument(:write, name, options) do
397
+ entry = Entry.new(value, options)
398
+ write_entry(normalize_key(name, options), entry, options)
399
+ end
400
+ end
401
+
402
+ # Deletes an entry in the cache. Returns +true+ if an entry is deleted.
403
+ #
404
+ # Options are passed to the underlying cache implementation.
405
+ def delete(name, options = nil)
406
+ options = merged_options(options)
407
+
408
+ instrument(:delete, name) do
409
+ delete_entry(normalize_key(name, options), options)
410
+ end
411
+ end
412
+
413
+ # Returns +true+ if the cache contains an entry for the given key.
414
+ #
415
+ # Options are passed to the underlying cache implementation.
416
+ def exist?(name, options = nil)
417
+ options = merged_options(options)
418
+
419
+ instrument(:exist?, name) do
420
+ entry = read_entry(normalize_key(name, options), options)
421
+ (entry && !entry.expired?) || false
422
+ end
423
+ end
424
+
425
+ # Deletes all entries with keys matching the pattern.
426
+ #
427
+ # Options are passed to the underlying cache implementation.
428
+ #
429
+ # All implementations may not support this method.
430
+ def delete_matched(matcher, options = nil)
431
+ raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
432
+ end
433
+
434
+ # Increments an integer value in the cache.
435
+ #
436
+ # Options are passed to the underlying cache implementation.
437
+ #
438
+ # All implementations may not support this method.
439
+ def increment(name, amount = 1, options = nil)
440
+ raise NotImplementedError.new("#{self.class.name} does not support increment")
441
+ end
442
+
443
+ # Decrements an integer value in the cache.
444
+ #
445
+ # Options are passed to the underlying cache implementation.
446
+ #
447
+ # All implementations may not support this method.
448
+ def decrement(name, amount = 1, options = nil)
449
+ raise NotImplementedError.new("#{self.class.name} does not support decrement")
450
+ end
451
+
452
+ # Cleanups the cache by removing expired entries.
453
+ #
454
+ # Options are passed to the underlying cache implementation.
455
+ #
456
+ # All implementations may not support this method.
457
+ def cleanup(options = nil)
458
+ raise NotImplementedError.new("#{self.class.name} does not support cleanup")
459
+ end
460
+
461
+ # Clears the entire cache. Be careful with this method since it could
462
+ # affect other processes if shared cache is being used.
463
+ #
464
+ # The options hash is passed to the underlying cache implementation.
465
+ #
466
+ # All implementations may not support this method.
467
+ def clear(options = nil)
468
+ raise NotImplementedError.new("#{self.class.name} does not support clear")
469
+ end
470
+
471
+ protected
472
+ # Adds the namespace defined in the options to a pattern designed to
473
+ # match keys. Implementations that support delete_matched should call
474
+ # this method to translate a pattern that matches names into one that
475
+ # matches namespaced keys.
476
+ def key_matcher(pattern, options)
477
+ prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
478
+ if prefix
479
+ source = pattern.source
480
+ if source.start_with?('^')
481
+ source = source[1, source.length]
482
+ else
483
+ source = ".*#{source[0, source.length]}"
484
+ end
485
+ Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
486
+ else
487
+ pattern
488
+ end
489
+ end
490
+
491
+ # Reads an entry from the cache implementation. Subclasses must implement
492
+ # this method.
493
+ def read_entry(key, options) # :nodoc:
494
+ raise NotImplementedError.new
495
+ end
496
+
497
+ # Writes an entry to the cache implementation. Subclasses must implement
498
+ # this method.
499
+ def write_entry(key, entry, options) # :nodoc:
500
+ raise NotImplementedError.new
501
+ end
502
+
503
+ # Deletes an entry from the cache implementation. Subclasses must
504
+ # implement this method.
505
+ def delete_entry(key, options) # :nodoc:
506
+ raise NotImplementedError.new
507
+ end
508
+
509
+ private
510
+ # Merges the default options with ones specific to a method call.
511
+ def merged_options(call_options) # :nodoc:
512
+ if call_options
513
+ options.merge(call_options)
514
+ else
515
+ options.dup
516
+ end
517
+ end
518
+
519
+ # Expands key to be a consistent string value. Invokes +cache_key+ if
520
+ # object responds to +cache_key+. Otherwise, +to_param+ method will be
521
+ # called. If the key is a Hash, then keys will be sorted alphabetically.
522
+ def expanded_key(key) # :nodoc:
523
+ return key.cache_key.to_s if key.respond_to?(:cache_key)
524
+
525
+ case key
526
+ when Array
527
+ if key.size > 1
528
+ key = key.collect{|element| expanded_key(element)}
529
+ else
530
+ key = key.first
531
+ end
532
+ when Hash
533
+ key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
534
+ end
535
+
536
+ key.to_param
537
+ end
538
+
539
+ # Prefixes a key with the namespace. Namespace and key will be delimited
540
+ # with a colon.
541
+ def normalize_key(key, options)
542
+ key = expanded_key(key)
543
+ namespace = options[:namespace] if options
544
+ prefix = namespace.is_a?(Proc) ? namespace.call : namespace
545
+ key = "#{prefix}:#{key}" if prefix
546
+ key
547
+ end
548
+
549
+ def namespaced_key(*args)
550
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
551
+ `namespaced_key` is deprecated and will be removed from Rails 5.1.
552
+ Please use `normalize_key` which will return a fully resolved key.
553
+ MESSAGE
554
+ normalize_key(*args)
555
+ end
556
+
557
+ def instrument(operation, key, options = nil)
558
+ log { "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" }
559
+
560
+ payload = { :key => key }
561
+ payload.merge!(options) if options.is_a?(Hash)
562
+ ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
563
+ end
564
+
565
+ def log
566
+ return unless logger && logger.debug? && !silence?
567
+ logger.debug(yield)
568
+ end
569
+
570
+ def handle_expired_entry(entry, key, options)
571
+ if entry && entry.expired?
572
+ race_ttl = options[:race_condition_ttl].to_i
573
+ if (race_ttl > 0) && (Time.now.to_f - entry.expires_at <= race_ttl)
574
+ # When an entry has a positive :race_condition_ttl defined, put the stale entry back into the cache
575
+ # for a brief period while the entry is being recalculated.
576
+ entry.expires_at = Time.now + race_ttl
577
+ write_entry(key, entry, :expires_in => race_ttl * 2)
578
+ else
579
+ delete_entry(key, options)
580
+ end
581
+ entry = nil
582
+ end
583
+ entry
584
+ end
585
+
586
+ def get_entry_value(entry, name, options)
587
+ instrument(:fetch_hit, name, options) { }
588
+ entry.value
589
+ end
590
+
591
+ def save_block_result_to_cache(name, options)
592
+ result = instrument(:generate, name, options) do
593
+ yield(name)
594
+ end
595
+
596
+ write(name, result, options)
597
+ result
598
+ end
599
+ end
600
+
601
+ # This class is used to represent cache entries. Cache entries have a value and an optional
602
+ # expiration time. The expiration time is used to support the :race_condition_ttl option
603
+ # on the cache.
604
+ #
605
+ # Since cache entries in most instances will be serialized, the internals of this class are highly optimized
606
+ # using short instance variable names that are lazily defined.
607
+ class Entry # :nodoc:
608
+ DEFAULT_COMPRESS_LIMIT = 16.kilobytes
609
+
610
+ # Creates a new cache entry for the specified value. Options supported are
611
+ # +:compress+, +:compress_threshold+, and +:expires_in+.
612
+ def initialize(value, options = {})
613
+ if should_compress?(value, options)
614
+ @value = compress(value)
615
+ @compressed = true
616
+ else
617
+ @value = value
618
+ end
619
+
620
+ @created_at = Time.now.to_f
621
+ @expires_in = options[:expires_in]
622
+ @expires_in = @expires_in.to_f if @expires_in
623
+ end
624
+
625
+ def value
626
+ compressed? ? uncompress(@value) : @value
627
+ end
628
+
629
+ # Checks if the entry is expired. The +expires_in+ parameter can override
630
+ # the value set when the entry was created.
631
+ def expired?
632
+ @expires_in && @created_at + @expires_in <= Time.now.to_f
633
+ end
634
+
635
+ def expires_at
636
+ @expires_in ? @created_at + @expires_in : nil
637
+ end
638
+
639
+ def expires_at=(value)
640
+ if value
641
+ @expires_in = value.to_f - @created_at
642
+ else
643
+ @expires_in = nil
644
+ end
645
+ end
646
+
647
+ # Returns the size of the cached value. This could be less than
648
+ # <tt>value.size</tt> if the data is compressed.
649
+ def size
650
+ if defined?(@s)
651
+ @s
652
+ else
653
+ case value
654
+ when NilClass
655
+ 0
656
+ when String
657
+ @value.bytesize
658
+ else
659
+ @s = Marshal.dump(@value).bytesize
660
+ end
661
+ end
662
+ end
663
+
664
+ # Duplicates the value in a class. This is used by cache implementations that don't natively
665
+ # serialize entries to protect against accidental cache modifications.
666
+ def dup_value!
667
+ if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false)
668
+ if @value.is_a?(String)
669
+ @value = @value.dup
670
+ else
671
+ @value = Marshal.load(Marshal.dump(@value))
672
+ end
673
+ end
674
+ end
675
+
676
+ private
677
+ def should_compress?(value, options)
678
+ if value && options[:compress]
679
+ compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
680
+ serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
681
+
682
+ return true if serialized_value_size >= compress_threshold
683
+ end
684
+
685
+ false
686
+ end
687
+
688
+ def compressed?
689
+ defined?(@compressed) ? @compressed : false
690
+ end
691
+
692
+ def compress(value)
693
+ Zlib::Deflate.deflate(Marshal.dump(value))
694
+ end
695
+
696
+ def uncompress(value)
697
+ Marshal.load(Zlib::Inflate.inflate(value))
698
+ end
699
+ end
700
+ end
701
+ end