Class: Esse::Hstring

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/esse/primitives/hstring.rb

Overview

The idea here is to add useful methods to the ruby core objects without monkey patching. And on this state and not thinking about to add ActiveSupport dependency

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Hstring

Returns a new instance of Hstring.



40
41
42
# File 'lib/esse/primitives/hstring.rb', line 40

def initialize(value)
  @value = value.to_s
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



13
14
15
# File 'lib/esse/primitives/hstring.rb', line 13

def value
  @value
end

Class Method Details

.def_conventional(bang_method, conv_method = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/esse/primitives/hstring.rb', line 15

def self.def_conventional(bang_method, conv_method = nil)
  conv_method ||= bang_method.to_s.sub(/[!?]*$/, '')
  if public_instance_methods.include?(conv_method)
    msg = format(
      'Equivalent %<conv>p already defined for the bang method %<bang>p',
      conv: conv_method.to_s,
      bang: bang_method.to_s,
    )
    raise(SyntaxError, msg)
  end

  unless public_instance_methods.include?(bang_method)
    msg = format(
      'Undefined method %<bang>p for %<klass>p',
      bang: bang_method.to_s,
      klass: self,
    )
    raise(SyntaxError, msg)
  end

  define_method(conv_method) do |*args|
    self.class.new(self).public_send(bang_method, *args)
  end
end

Instance Method Details

#camelize!Object



44
45
46
47
# File 'lib/esse/primitives/hstring.rb', line 44

def camelize!
  @value = @value.split(/(?=[_A-Z])/).map { |str| str.tr('_', '').capitalize }.join
  self
end

#demodulize!Object



50
51
52
53
# File 'lib/esse/primitives/hstring.rb', line 50

def demodulize!
  @value = @value.split('::').last
  self
end

#modulize!Object



56
57
58
59
# File 'lib/esse/primitives/hstring.rb', line 56

def modulize!
  @value = @value.split(%r{::|\\|/}).map { |part| self.class.new(part).camelize.to_s }.join('::')
  self
end

#presence!Object



78
79
80
81
82
83
# File 'lib/esse/primitives/hstring.rb', line 78

def presence!
  return @value = nil if @value == ''
  return @value = nil unless @value

  @value
end

#underscore!Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/esse/primitives/hstring.rb', line 62

def underscore!
  @value = @value
    .sub(/^::/, '')
    .gsub('::', '/')
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .tr('-', '_')
    .tr('.', '_')
    .gsub(/\s/, '_')
    .gsub(/__+/, '_')
    .downcase

  self
end