Module: SearchObject::Helper
- Defined in:
- lib/search_object/helper.rb
Overview
:api: private
Class Method Summary collapse
- .camelize(text) ⇒ Object
-
.deep_copy(object) ⇒ Object
rubocop:disable Metrics/MethodLength.
- .define_module(&block) ⇒ Object
- .ensure_included(item, collection) ⇒ Object
- .normalize_search_handler(handler, name) ⇒ Object
- .slice_keys(hash, keys) ⇒ Object
- .stringify_keys(hash) ⇒ Object
- .underscore(text) ⇒ Object
Class Method Details
.camelize(text) ⇒ Object
22 23 24 |
# File 'lib/search_object/helper.rb', line 22 def camelize(text) text.to_s.gsub(/(?:^|_)(.)/) { Regexp.last_match[1].upcase } end |
.deep_copy(object) ⇒ Object
rubocop:disable Metrics/MethodLength
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/search_object/helper.rb', line 59 def deep_copy(object) # rubocop:disable Metrics/MethodLength case object when Array object.map { |element| deep_copy(element) } when Hash object.inject({}) do |result, (key, value)| result[key] = deep_copy(value) result end when NilClass, FalseClass, TrueClass, Symbol, Method, Numeric object else object.dup end end |
.define_module(&block) ⇒ Object
43 44 45 46 47 48 49 |
# File 'lib/search_object/helper.rb', line 43 def define_module(&block) Module.new do define_singleton_method :included do |base| base.class_eval(&block) end end end |
.ensure_included(item, collection) ⇒ Object
35 36 37 38 39 40 41 |
# File 'lib/search_object/helper.rb', line 35 def ensure_included(item, collection) if collection.include? item item else collection.first end end |
.normalize_search_handler(handler, name) ⇒ Object
51 52 53 54 55 56 57 |
# File 'lib/search_object/helper.rb', line 51 def normalize_search_handler(handler, name) case handler when Symbol then ->(scope, value) { method(handler).call scope, value } when Proc then handler else ->(scope, value) { scope.where name => value unless value.blank? } end end |
.slice_keys(hash, keys) ⇒ Object
15 16 17 18 19 20 |
# File 'lib/search_object/helper.rb', line 15 def slice_keys(hash, keys) keys.inject({}) do |memo, key| memo[key] = hash[key] if hash.key? key memo end end |
.stringify_keys(hash) ⇒ Object
8 9 10 11 12 13 |
# File 'lib/search_object/helper.rb', line 8 def stringify_keys(hash) # Note(rstankov): From Rails 5+ ActionController::Parameters aren't Hash # In a lot of cases `stringify_keys` is used on action params hash = hash.to_unsafe_h if hash.respond_to? :to_unsafe_h Hash[(hash || {}).map { |k, v| [k.to_s, v] }] end |
.underscore(text) ⇒ Object
26 27 28 29 30 31 32 33 |
# File 'lib/search_object/helper.rb', line 26 def underscore(text) text.to_s .tr('::', '_') .gsub(/([A-Z]+)([A-Z][a-z])/) { "#{Regexp.last_match[1]}_#{Regexp.last_match[2]}" } .gsub(/([a-z\d])([A-Z])/) { "#{Regexp.last_match[1]}_#{Regexp.last_match[2]}" } .tr('-', '_') .downcase end |