-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcore_extensions.rb
80 lines (64 loc) · 1.32 KB
/
core_extensions.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
require 'i18n'
class Object
def present?
!blank?
end
def blank?
respond_to?(:empty?) ? empty? : !self
end
# from https://gist.github.com/Integralist/9503099
def symbolize_keys
return self.reduce({}) do |memo, (k, v)|
memo.tap { |m| m[k.to_sym] = v.symbolize_keys }
end if self.is_a? Hash
return self.reduce([]) do |memo, v|
memo << v.symbolize_keys; memo
end if self.is_a? Array
self
end
end
class String
def capitalize_first
self[0] = self[0].capitalize
self
end
alias_method :ucfirst, :capitalize_first
def uncapitalize
self[0, 1].downcase + self[1..-1]
end
def uppercase?
match(/\p{Upper}/).present?
end
def lowercase?
!uppercase?
end
def capitalized?
self[0, 1].uppercase?
end
def score
tr(' ', '_')
end
def descore
tr('_', ' ')
end
def translate(opts = {})
I18n.t(self, opts)
end
alias_method :t, :translate
def pluralize(count = 0)
"#{self}#{count == 1 ? '' : 's'}"
end
def pluralize_num(count = 0)
"#{count} #{self.pluralize(count)}"
end
end
def t(key, opts = {})
if I18n.locale == :en && opts.blank?
key
elsif key.is_a?(Symbol)
I18n.t(key, opts)
else
res = key.clone.uncapitalize.translate(opts)
key.capitalized? ? res.capitalize_first : res.uncapitalize
end
end