-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.rb
92 lines (76 loc) · 2.17 KB
/
utils.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# Emulate only what we need from activesupport
module Tacokit
module Utils
def deep_transform_keys(hash, &block)
_deep_transform_keys_in_object(hash, &block)
end
def extract_options(*args)
opts = args.last.is_a?(Hash) ? args.pop : {}
[args, opts]
end
# rubocop:disable Style/DotPosition
def underscore(string)
string.gsub(/::/, "/").
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
gsub(/([a-z\d])([A-Z])/, '\1_\2').
tr("-", "_").
downcase
end
# rubocop:enable Style/DotPosition
def camelize(string, lower = false)
string = string.to_s.gsub(/(?:^|_)(.)/) { Regexp.last_match(1).upcase }
string = string[0].chr.downcase + string[1..-1] if lower
string
end
def blank?(obj)
obj.respond_to?(:empty?) ? obj.empty? : !obj
end
def present?(obj)
!blank?(obj)
end
def camel_path(path)
camelize(path.to_s, :lower)
end
alias camp camel_path
def camel_join(*paths)
path_join paths.map { |p| camel_path(p) }
end
def path_join(*paths)
paths.join("/")
end
# Returns a resource path for a given resource name and id
def resource_path(resource_name, identifier, *paths)
path_join resource_name, resource_id(identifier), *paths
end
def resource_id(identifier)
identifier.respond_to?(:id) ? identifier.id : identifier
end
def constantize(class_name)
Tacokit.const_get(camelize(singularize(class_name.to_s)))
rescue NameError
nil
end
def singularize(string)
string.gsub(/s$/, "")
end
def base_path(base, *paths)
return base if paths.empty?
resource = paths.shift
resource = resource.id if resource.respond_to?(:id)
path_join base, resource, *paths
end
private
def _deep_transform_keys_in_object(object, &block)
case object
when Hash
object.each_with_object({}) do |(key, value), result|
result[yield(key)] = _deep_transform_keys_in_object(value, &block)
end
when Array
object.map { |e| _deep_transform_keys_in_object(e, &block) }
else
object
end
end
end
end