Created
November 25, 2017 15:24
-
-
Save Ptico/43835106350847a4c94aff26c7d12ec0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parts | |
def initialize(parts) | |
@parts = parts | |
end | |
def join(part_divider, word_divider='') | |
@parts.map do |word| | |
word.join(word_divider) | |
end.join(part_divider) | |
end | |
def transform(transformer, part_divider, word_divider='') | |
@parts.map do |word| | |
word.reduce('') do |result, word| | |
word = transformer.call(word) | |
result += word_divider + word | |
end | |
end.join(part_divider) | |
end | |
def last | |
[@parts.last] | |
end | |
end | |
class InternalString | |
MODULE_DIVIDER = '::'.freeze | |
PATH_DIVIDER = '/'.freeze | |
attr_reader :parts | |
def initialize(value) | |
if value.kind_of?(Array) | |
@parts = Parts.new(value) | |
else | |
words = value.to_s.split(/#{MODULE_DIVIDER}|#{PATH_DIVIDER}/) | |
@parts = Parts.new(words.map { |word| word.split(/\_|(?!(^|[a-z]|$))/) }) | |
end | |
end | |
def camelize | |
@parts.transform(:capitalize.to_proc, MODULE_DIVIDER) | |
end | |
def underscore | |
@parts.join(PATH_DIVIDER, '_').downcase | |
end | |
def demodulize | |
@parts.last.join | |
end | |
def foreign_key | |
self.class.new(@parts.last).underscore + '_id' | |
end | |
end | |
original = 'active_support/inflector' | |
str = InternalString.new('active_support/inflector') | |
puts "Original: #{original}" | |
puts "Underscore: #{str.underscore}" | |
puts "Camelize: #{str.camelize}" | |
puts "Demodulize: #{str.demodulize}" | |
puts "Foreign key: #{str.foreign_key}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment