Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/ext/string.rb,
lib/ext/translator.rb

Instance Method Summary collapse

Instance Method Details

#cama_add_postfix_file_name(postfix) ⇒ Object

Sample:

'/var/www/media/132/logo.png'.cama_add_postfix_file_name('_2') ==> /var/www/media/132/logo_2.png

131
132
133
# File 'lib/ext/string.rb', line 131

def cama_add_postfix_file_name(postfix)
  File.join(File.dirname(self), "#{File.basename(self, File.extname(self))}#{postfix}#{File.extname(self)}")
end

#cama_add_postfix_url(postfix) ⇒ Object

convert url into custom url with postfix, sample: “localhost/company/rack_multipart20160124_2288_8xcdjs.jpg”.cama_add_postfix_url(‘thumbs/') into


125
126
127
# File 'lib/ext/string.rb', line 125

def cama_add_postfix_url(postfix)
  File.join(File.dirname(self), "#{postfix}#{File.basename(self)}")
end

#cama_fix_filenameObject


104
105
106
107
108
109
110
111
112
113
114
# File 'lib/ext/string.rb', line 104

def cama_fix_filename
  # Sanitize the filename, to prevent hacking
  # https://github.com/carrierwaveuploader/carrierwave/blob/6a1445e0daef29a5d4f799a016359b62d82dbc24/lib/carrierwave/sanitized_file.rb#L322
  sanitize_regexp = /[^[:word:]\.\-\+]/
  name = self.tr("\\", "/") # work-around for IE
  name = File.basename(name)
  name = name.gsub(sanitize_regexp, "_")
  name = "_#{name}" if name =~ /\A\.+\z/
  name = "unnamed" if name.size == 0
  name.mb_chars.to_s
end

#cama_fix_media_keyObject

fix file media keys: avoid duplicated slashes and force to start with slash


97
98
99
100
101
102
# File 'lib/ext/string.rb', line 97

def cama_fix_media_key
  res = self.gsub('../', '/').gsub('./', '/').gsub(/(\/){2,}/, "/")
  res = "/#{res}" unless res.start_with?('/')
  res = res.slice(0...-1) if res.end_with?('/') && res.length > 1
  res
end

#cama_fix_slashObject

remove double or more secuencial slashes, like: '/a//b/c/d///abs'.cama_fix_slash => /a/b/c/d/abs


92
93
94
# File 'lib/ext/string.rb', line 92

def cama_fix_slash
  self.gsub(/(\/){2,}/, "/")
end

#cama_log_style(color = :red) ⇒ Object

Colorized Ruby output color: (:red, :green, :blue, :pink, :light_blue, :yellow)


158
159
160
161
# File 'lib/ext/string.rb', line 158

def cama_log_style(color = :red)
  colors = {red: 31, green: 32, blue: 34, pink: 35, light_blue: 36, yellow: 33}
  "\e[#{colors[color]}m#{self}\e[0m"
end

#cama_parse_image_version(version_name = '', check_url = false) ⇒ Object

Parse the url to get the image version

version_name: (String, default empty) version name,
  if this is empty, this will return the image version for thumb of the image, sample: 'http://localhost/my_image.png'.cama_parse_image_version('') => http://localhost/thumb/my_image.png
  if this is present, this will return the image version generated, sample: , sample: 'http://localhost/my_image.png'.cama_parse_image_version('200x200') => http://localhost/thumb/my_image_200x200.png
check_url: (boolean, default false) if true the image version will be verified, i.e. if the url exist will return version url, if not will return current url

140
141
142
143
144
145
# File 'lib/ext/string.rb', line 140

def cama_parse_image_version(version_name = '', check_url = false)
  res = File.join(File.dirname(self), 'thumb', "#{File.basename(self).parameterize}#{File.extname(self)}")
  res = res.cama_add_postfix_file_name("_#{version_name}") if version_name.present?
  return self if check_url && !res.cama_url_exist?
  res
end

#cama_replace_codes(values, format_code = '[') ⇒ Object

parse all codes in current text to replace with values sample: “Hello [c1]”.cama_replace_codes('World') ==> Hello World


80
81
82
83
84
85
86
87
88
89
# File 'lib/ext/string.rb', line 80

def cama_replace_codes(values, format_code = '[')
  res = self
  values.each do |k, v|
    v = v.join(',') if v.is_a?(Array)
    res = res.gsub("[#{k}]", v.to_s) if format_code == '['
    res = res.gsub("{#{k}}", v.to_s) if format_code == '{'
    res = res.gsub("%{#{k}}", v.to_s) if format_code == '%{'
  end
  res
end

#cama_true?Boolean

check if current string is true or false cases for true: '1' | 'true' cases for false: '0' | 'false' | '' return boolean

Returns:

  • (Boolean)

28
29
30
# File 'lib/ext/string.rb', line 28

def cama_true?
  self == 'true' || self == '1'
end

#cama_url_exist?Boolean

check if the url exist sample: “mydomain.com/myimg.png”.cama_url_exist? return (Boolean) true if the url exist

Returns:

  • (Boolean)

150
151
152
153
154
# File 'lib/ext/string.rb', line 150

def cama_url_exist?
  Net::HTTP.get_response(URI.parse(self)).is_a?(Net::HTTPSuccess)
rescue
  false
end

#is_bool?Boolean

Returns:

  • (Boolean)

20
21
22
# File 'lib/ext/string.rb', line 20

def is_bool?
  self == 'false' || self == 'true'
end

#is_float?Boolean

Returns:

  • (Boolean)

12
13
14
# File 'lib/ext/string.rb', line 12

def is_float?
  self.to_f.to_s == self.to_s
end

#is_number?Boolean

Returns:

  • (Boolean)

16
17
18
# File 'lib/ext/string.rb', line 16

def is_number?
  self.to_f.to_s == self.to_s || self.to_i.to_s == self.to_s
end

#parse_domainObject

parse string into domain owem.tuzitio.com into owem.tuzitio.com


69
70
71
72
73
74
75
76
# File 'lib/ext/string.rb', line 69

def parse_domain
  url = self
  uri = URI.parse(url)
  uri = URI.parse("http://#{url}") if uri.scheme.nil?
  host = (uri.host || self).downcase
  h = host.start_with?('www.') ? host[4..-1] : host
  "#{h}#{":#{uri.port}" unless [80, 443].include?(uri.port)}"
end

#parseCamaClassObject

return cleaned model class name remove decorate remove Cama prefix


119
120
121
# File 'lib/ext/string.rb', line 119

def parseCamaClass
  self.gsub("Decorator","").gsub("CamaleonCms::","")
end

#slugObject

parse string into slug format


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ext/string.rb', line 45

def slug
  #strip the string
  ret = self.strip

  #blow away apostrophes
  ret.gsub! /['`]/,""

  # @ --> at, and & --> and
  ret.gsub! /\s*@\s*/, " at "
  ret.gsub! /\s*&\s*/, " and "

  #replace all non alphanumeric, underscore or periods with underscore
  ret.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '_'

  #convert double underscores to single
  ret.gsub! /_+/,"_"

  #strip off leading/trailing underscore
  ret.gsub! /\A[_\.]+|[_\.]+\z/,""
  ret
end

#strip_tagsObject


8
9
10
# File 'lib/ext/string.rb', line 8

def strip_tags
  ActionController::Base.helpers.strip_tags(self)
end

#to_boolObject

Raises:

  • (ArgumentError)

2
3
4
5
6
# File 'lib/ext/string.rb', line 2

def to_bool
  return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
  return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i)
  raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
end

#to_varObject


32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ext/string.rb', line 32

def to_var
  if is_float?
    self.to_f
  elsif is_number?
    self.to_i
  elsif is_bool?
    self.to_bool
  else
    self
  end
end

#translate(locale = nil) ⇒ Object

Usage The default value if translation is not provided is all text

$ WpPost.post_title
$ => "<!--:en-->And this is how the Universe ended.<!--:--><!--:fr-->Et c'est ainsi que l'univers connu cessa d'exister.<!--:-->"
$ I18n.locale = :en
$ WpPost.post_title.translate
$ => "And this is how the Universe ended."
$ WpPost.post_title.translate(:en)
$ => "And this is how the Universe ended."

Spits the same text out if no translation tags are applied
$ WpPost.post_title
$ => "And this is how the Universe ended."
$ WpPost.post_title.translate(:fr)
$ => "And this is how the Universe ended."

23
24
25
26
27
28
29
30
31
# File 'lib/ext/translator.rb', line 23

def translate(locale = nil)
  locale ||= I18n.locale
  locale = locale.to_sym
  return self if !self.squish.starts_with?("<!--") or self.blank?
  return translations[locale] if translations.has_key?(locale)
  return translations[I18n.default_locale] if translations.has_key?(I18n.default_locale)
  return '' if translations.keys.any?
  self
end

#translationsObject

return hash of translations for this string sample: “hola mundo”, en: “Hello World”


35
36
37
38
# File 'lib/ext/translator.rb', line 35

def translations
  @translations ||= split_locales
  @translations
end

#translations_arrayObject

return aray of translations for this string sample: [“hola mundo”, “Hello World”]


42
43
44
45
# File 'lib/ext/translator.rb', line 42

def translations_array
  r = translations.map{|key, value| value}
  return r.present? ? r : [self]
end