Module: Ankoder::CoreExtension::HashExtension
- Included in:
- Hash
- Defined in:
- lib/ankoder/ext.rb
Instance Method Summary collapse
-
#method_missing(m, *args) ⇒ Object
The hash keys are available by calling the method name “key”.
-
#type_cast! ⇒ Object
Cast each value of the hash in the right format (integer, float, time, boolean).
-
#underscore_keys! ⇒ Object
Replace “-” by “_” in all keys of the hash.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args) ⇒ Object
The hash keys are available by calling the method name “key”
h = {"profile_id" => 54, "video_id" => 12}
h.profile_id
=> 54
42 43 44 45 46 47 48 |
# File 'lib/ankoder/ext.rb', line 42 def method_missing(m, *args) if has_key? m.to_s self[m.to_s] else raise NoMethodError, "undefined method `#{m.to_s}' for #{self.class}" end end |
Instance Method Details
#type_cast! ⇒ Object
Cast each value of the hash in the right format (integer, float, time, boolean)
24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/ankoder/ext.rb', line 24 def type_cast! self.keys.each do |k| self[k] = self[k].type_cast! if self[k].is_a?(Hash) self[k] = self[k].to_i if self[k] =~ /^[0-9]+$/ self[k] = self[k].to_f if self[k] =~ /^[0-9]+\.[0-9]+$/ self[k] = Time.parse(self[k]) if self[k] =~ /[a-z]+ [a-z]+ [0-9]+ [0-9]{2}:[0-9]{2}:[0-9]{2} [a-z0-9\+]+ [0-9]{4}/i self[k] = true if self[k] == "true" self[k] = false if self[k] == "false" self[k] = nil if self[k] == {} end self end |
#underscore_keys! ⇒ Object
Replace “-” by “_” in all keys of the hash
14 15 16 17 18 19 20 21 |
# File 'lib/ankoder/ext.rb', line 14 def underscore_keys! self.keys.each do |k| self[k] = self[k].underscore_keys! if self[k].is_a?(Hash) self[k.to_s.gsub("-", "_")] = self[k] delete(k) if k.to_s =~ /-/ end self end |