Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/twirp/protoc_plugin/core_ext/string/to_anchor.rb,
lib/twirp/protoc_plugin/core_ext/string/camel_case.rb,
lib/twirp/protoc_plugin/core_ext/string/snake_case.rb,
lib/twirp/protoc_plugin/core_ext/string/capitalize_first.rb

Instance Method Summary collapse

Instance Method Details

#camel_case(uppercase_first_letter = true) ⇒ String

Returns the string converted to either lowerCamelCase or UpperCamelCase.

Inspired by github.com/rails/rails/blob/6f0d1ad14b92b9f5906e44740fce8b4f1c7075dc/activesupport/lib/active_support/inflector/methods.rb#L70

Parameters:

  • uppercase_first_letter (Boolean) (defaults to: true)

    true for UpperCamelCase, false for lowerCamelCase. Defaults to true.

Returns:

  • (String)

    a copy of the chars of self



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/twirp/protoc_plugin/core_ext/string/camel_case.rb', line 13

def camel_case(uppercase_first_letter = true)
  s = if uppercase_first_letter
    capitalize_first
  else
    self
  end

  s.gsub(/_([a-z\d]*)/i) do
    $1.capitalize
  end
end

#capitalize_firstString

Returns:

  • (String)

    a string with the first letter capitalized



9
10
11
12
13
# File 'lib/twirp/protoc_plugin/core_ext/string/capitalize_first.rb', line 9

def capitalize_first
  return "" if empty?

  self[0].upcase + self[1..]
end

#snake_caseString

Returns:

  • (String)

    the converted input



9
10
11
12
13
# File 'lib/twirp/protoc_plugin/core_ext/string/snake_case.rb', line 9

def snake_case
  gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .downcase
end

#to_anchorString

Converts the string to an acceptable URL anchor.

Thw rules for GitHub markdown links are:

- force lowercase
- strip punctuation
- replace spaces with dashes

Returns:

  • (String)

    the string converted to an acceptable URL anchor



11
12
13
# File 'lib/twirp/protoc_plugin/core_ext/string/to_anchor.rb', line 11

def to_anchor
  downcase.gsub(/[^a-z0-9_ -]/, "").tr(" ", "-")
end