# test refinement to replace monkey patching module StringUtil refine String do def titleize underscore.humanize.gsub(/\b([a-z])/) { $1.capitalize } end def humanize gsub(/_id$/, '').gsub(/_/, ' ').capitalize end def camelize(first_letter_in_uppercase = true) if first_letter_in_uppercase gsub(/\/(.?)/) { '::' + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } else first + camelize[1..-1] end end def underscore gsub(/::/, '/') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_') .downcase end end end # Using StringUtil class Test using StringUtil def initialize(title) @title = title end def titleize @title.titleize end def humanize @title.humanize end end fred = Test.new('bloody_toad') puts fred.humanize puts fred.titleizeOutput:-
Bloody toad Bloody Toad
But perhaps we don't need refinements with use of 'forwardable'
require 'forwardable' # Avoid the monkey patching of String for camelize class CamelString extend Forwardable def_delegators(:@string, *String.public_instance_methods(false)) def initialize(str) @string = str end def camelize(first_letter_in_uppercase = true) if first_letter_in_uppercase @string.gsub(/\/(.?)/) { '::' + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } else @string[0] + camelize[1..-1] end end end test = 'test_case' puts CamelString.new(test).camelize puts CamelString.new(test).camelize false
Output:-
TestCase testCase
require 'forwardable' # Avoid the monkey patching of String for underscore/titleize/humanize class StringExtra extend Forwardable def_delegators(:@string, *String.public_instance_methods(false)) def initialize(str) @string = str end def titleize gsub(/::/, '/') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_') .downcase .gsub(/_id$/, '') .gsub(/_/, ' ').capitalize .gsub(/\b([a-z])/) { $1.capitalize } end def humanize gsub(/_id$/, '').gsub(/_/, ' ').capitalize end def underscore gsub(/::/, '/') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_') .downcase end end test = 'TestCase' puts StringExtra.new(test).underscore puts StringExtra.new(test).titleize puts StringExtra.new(test).humanize
Testcase test_case Test Case
What is more using these two classes I can completely replace the monkey-patching of String in JRubyArt and hence probably ruby-processing................
No comments:
Post a Comment