Module: HasHelpers::CoreExt::String

Defined in:
lib/has_helpers/core_ext/string.rb

Instance Method Summary collapse

Instance Method Details

#constant_caseObject

Converts the string into an all-caps, constant identifier format.

Examples

"OneHQ".constant_case # => "ONE_HQ"



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

def constant_case
  to_s.dup.underscore.tap do |string|
    string.strip!
    string.gsub!("&", "_AND_")   # Special char replacement
    string.gsub!(/[\W_]+/, "_")  # Replace whitespace with _
    string.upcase!
    string.sub!(/\A[^A-Z]*/, "") # Remove leading non-alpha characters
    string.sub!(/[_]*\Z/, "")    # Remove trailing underscores
  end
end

#despaceObject



7
8
9
# File 'lib/has_helpers/core_ext/string.rb', line 7

def despace
  to_s.gsub(/\s+/, "_")
end

#to_boolObject



25
26
27
28
29
30
31
# File 'lib/has_helpers/core_ext/string.rb', line 25

def to_bool
  case self
  when /\A(true|t|yes|y|1)\Z/i then true
  when /\A(false|f|no|n|0|)\Z/i then false
  else raise ArgumentError.new("invalid value for Boolean: '#{self}'")
  end
end

#to_class_nameObject



33
34
35
36
37
38
39
40
41
# File 'lib/has_helpers/core_ext/string.rb', line 33

def to_class_name
  titleized = self.titleize
  cn = titleized.delete_prefix("/").gsub(%r<\s+>, "").classify
  if titleized.start_with?("/")
    "::#{cn}"
  else
    cn
  end
end

#to_constant(**options, &block) ⇒ Object

Examples

"Example "



66
67
68
# File 'lib/has_helpers/core_ext/string.rb', line 66

def to_constant(**options, &block)
  ::HasHelpers::Constant::Definition.new(name: self, **options, &block)
end

#to_icon(*args) ⇒ Object

Examples

"calendar".to_icon "plane".to_icon(:flip_horizontal) "arrow_right".to_icon(:orientation => :rotate_90)



58
59
60
61
62
# File 'lib/has_helpers/core_ext/string.rb', line 58

def to_icon(*args)
  options = args.extract_options!
  options.reverse_merge!(attributes: args)
  ::HasHelpers::Icon.new(self, **options)
end

#to_renderableObject



70
71
72
# File 'lib/has_helpers/core_ext/string.rb', line 70

def to_renderable
  to_text_node
end

#to_service(url = nil, **options) ⇒ Object

Examples

"http://example.com&quot;.to_service "Example".to_service("http://example.com&quot;) "Example".to_service("http://example.com&quot;, :external => true)



47
48
49
50
# File 'lib/has_helpers/core_ext/string.rb', line 47

def to_service(url = nil, **options)
  options.reverse_merge!(url: url) if url
  ::Service.new(self, **options)
end

#to_text_node(**options) ⇒ Object



74
75
76
# File 'lib/has_helpers/core_ext/string.rb', line 74

def to_text_node(**options)
  ::HasHelpers::TextNode.new(self, **options)
end