Module: Subby

Defined in:
lib/subby/case_changer.rb,
lib/subby/base.rb

Overview

Subby is a module for substituting string case variations.

It has one class method, ::sub, and a supporting sub-module which converts the strings from one case to another.

Defined Under Namespace

Modules: CaseChanger

Constant Summary collapse

CASES =

Cases and Examples

Case                Example
-------------------------------
camel               applePie
class | module      ApplePie
constant            APPLE_PIE
dash                apple-pie
lower               apple pie
sentence            Apple pie
snake | underscore  apple_pie
title               Apple Pie
upper               APPLE PIE
%w( camel class constant dash lower module sentence snake title underscore upper )

Class Method Summary collapse

Class Method Details

.sub(text = "", string_in = "", string_out = "", opts = {}) ⇒ String

Substitutes string case variations in text. By default this method command is greedy. It will substitute all string_in case variations that it knows. The case variations with examples are listed above in the CASES constant.

Examples:

Default usage

Subby.sub("apple pie applePie apple_pie", "applePie", "chocolateCake")
# => "chocolate cake chocolateCake chocolate_cake"

Change one case to another

Subby.sub("apple pie applePie apple_pie", "applePie", "applePie",
  :case_in => :camel,
  :case_out => :snake)
# => "apple pie apple_pie apple_pie"

Only target certain cases

Subby.sub("apple pie applePie apple_pie", "applePie", "chocolateCake",
  :case_in => [:camel, :snake])
# => "apple pie chocolateCake chocolate_cake"

Parameters:

  • text (String) (defaults to: "")

    The text to be scanned for substitutions.

  • string_in (String) (defaults to: "")

    The string to be replaced.

  • string_out (String) (defaults to: "")

    The replacement string.

  • opts (Hash) (defaults to: {})

    Options

    • :case_in: Takes a CASE or [CASE]. Operates only on the given cases in order specified.

    • :case_out: Takes a CASE. All incoming cases will be converted to this case.

Returns:

  • (String)

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/subby/base.rb', line 48

def self.sub( text="", string_in="", string_out="", opts={} )

  # Setup
  res = text.to_s
  case_in = self.normalize_options( opts )[:case_in]
  case_out = self.normalize_options( opts )[:case_out]

  # Main Loop
  case_in.each do |case_in|
    res = res.gsub(
      CaseChanger.send( case_in, string_in ),
      CaseChanger.send( (case_out || case_in), string_out) )
  end

  res
end