Module: Rory::Support
- Defined in:
- lib/rory/support.rb
Overview
Support methods for utility functionality such as string modification - could also be accomplished by monkey-patching String class.
Class Method Summary collapse
- .camelize(string) ⇒ Object
- .constantize(string) ⇒ Object
- .encode_as_json(object) ⇒ Object
- .require_all_files_in_directory(path) ⇒ Object
- .tokenize(string) ⇒ Object
- .try_to_hash(object) ⇒ Object
Class Method Details
.camelize(string) ⇒ Object
7 8 9 10 |
# File 'lib/rory/support.rb', line 7 def camelize(string) string = string.sub(/^[a-z\d]*/) { $&.capitalize } string = string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub('/', '::') end |
.constantize(string) ⇒ Object
12 13 14 15 16 17 |
# File 'lib/rory/support.rb', line 12 def constantize(string) camelized = camelize(string) camelized.split('::').inject(Object) { |scope, const| scope.const_get(const) } end |
.encode_as_json(object) ⇒ Object
33 34 35 |
# File 'lib/rory/support.rb', line 33 def encode_as_json(object) try_to_hash(object).to_json end |
.require_all_files_in_directory(path) ⇒ Object
27 28 29 30 31 |
# File 'lib/rory/support.rb', line 27 def require_all_files_in_directory(path) Dir[Pathname.new(path).join('**', '*.rb')].each do |file| require file end end |
.tokenize(string) ⇒ Object
19 20 21 22 23 24 25 |
# File 'lib/rory/support.rb', line 19 def tokenize(string) return nil if string.nil? string = string.to_s.gsub(/&/, ' and '). gsub(/[ \/]+/, '_'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). downcase end |
.try_to_hash(object) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/rory/support.rb', line 37 def try_to_hash(object) if object.is_a?(Array) object.map { |val| try_to_hash(val) } elsif object.is_a?(Hash) Hash[object.map { |key, val| [key, try_to_hash(val)] }] elsif object.respond_to?(:to_hash) object.to_hash else object end end |