Class: EacRubyUtils::CustomFormat::String

Inherits:
Object
  • Object
show all
Defined in:
lib/eac_ruby_utils/custom_format.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format, string) ⇒ String

Returns a new instance of String.


22
23
24
25
# File 'lib/eac_ruby_utils/custom_format.rb', line 22

def initialize(format, string)
  @format = format
  @string = string
end

Instance Attribute Details

#formatObject (readonly)

Returns the value of attribute format


20
21
22
# File 'lib/eac_ruby_utils/custom_format.rb', line 20

def format
  @format
end

#stringObject (readonly)

Returns the value of attribute string


20
21
22
# File 'lib/eac_ruby_utils/custom_format.rb', line 20

def string
  @string
end

Instance Method Details

#mappingObject


27
28
29
30
31
# File 'lib/eac_ruby_utils/custom_format.rb', line 27

def mapping
  @mapping ||= format.mapping.select do |k, _v|
    sequences.include?(k)
  end
end

#sequencesObject


33
34
35
# File 'lib/eac_ruby_utils/custom_format.rb', line 33

def sequences
  @sequences ||= string.scan(SEQUENCE_PATTERN).map(&:first).uniq.map(&:to_sym)
end

#source_object_value(object, method) ⇒ Object

Raises:

  • (::ArgumentError)

37
38
39
40
41
42
# File 'lib/eac_ruby_utils/custom_format.rb', line 37

def source_object_value(object, method)
  return object.send(method) if object.respond_to?(method)
  return object[method] if object.respond_to?('[]')

  raise ::ArgumentError, "Methods \"#{method}\" or \"[]\" not found for #{object}"
end

#with(source_object) ⇒ Object


44
45
46
47
48
49
50
# File 'lib/eac_ruby_utils/custom_format.rb', line 44

def with(source_object)
  r = string
  mapping.each do |key, method|
    r = r.gsub(/%#{::Regexp.quote(key)}/, source_object_value(source_object, method).to_s)
  end
  r.gsub('%%', '%')
end