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
|
# File 'lib/snaky_hash/snake.rb', line 19
def self.to_mod(key_type)
Module.new do
case key_type
when :string then
define_method(:convert_key) { |key| key.respond_to?(:to_sym) ? underscore_string(key.to_s) : key }
when :symbol then
define_method(:convert_key) { |key| key.respond_to?(:to_sym) ? underscore_string(key.to_s).to_sym : key }
else
raise ArgumentError, "SnakyHash: Unhandled key_type: #{key_type}"
end
define_method :convert_value do |val, duping = false| case val
when self.class
val.dup
when ::Hash
val = val.dup if duping
self.class.new(val)
when ::Array
val.collect { |e| convert_value(e) }
else
val
end
end
define_method :underscore_string do |str|
str.to_s.strip
.tr(" ", "_")
.gsub(/::/, "/")
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr("-", "_")
.squeeze("_")
.downcase
end
end
end
|