Module: J1::Utils
- Extended by:
- Utils
- Included in:
- Utils
- Defined in:
- lib/j1/utils.rb,
lib/j1/utils/ansi.rb,
lib/j1/utils/exec1.rb,
lib/j1/utils/exec2.rb,
lib/j1/utils/win_tz.rb,
lib/j1/utils/platforms.rb
Defined Under Namespace
Modules: Ansi, Exec1, Exec2, Platforms, WinTZ Classes: GracefulQuit
Constant Summary collapse
- SLUGIFY_MODES =
Constants for use in #slugify
%w(raw default pretty ascii).freeze
- SLUGIFY_RAW_REGEXP =
Regexp.new('\\s+').freeze
- SLUGIFY_DEFAULT_REGEXP =
Regexp.new("[^[:alnum:]]+").freeze
- SLUGIFY_PRETTY_REGEXP =
Regexp.new("[^[:alnum:]._~!$&'()+,;=@]+").freeze
- SLUGIFY_ASCII_REGEXP =
Regexp.new("[^[A-Za-z0-9]]+").freeze
Instance Method Summary collapse
-
#add_permalink_suffix(template, permalink_style) ⇒ Object
Add an appropriate suffix to template so that it matches the specified permalink style.
-
#deep_merge_hashes(master_hash, other_hash) ⇒ Object
Non-destructive version of deep_merge_hashes! See that method.
-
#deep_merge_hashes!(target, overwrite) ⇒ Object
Merges a master hash with another hash, recursively.
- #duplicable?(obj) ⇒ Boolean
-
#has_yaml_header?(file) ⇒ Boolean
Determines whether a given file has.
- #is_project? ⇒ Boolean
- #is_project_setup? ⇒ Boolean
- #is_windows? ⇒ Boolean
- #mergable?(value) ⇒ Boolean
-
#merged_file_read_opts(site, opts) ⇒ Object
Returns merged option hash for File.read of self.site (if exists) and a given param ————————————————————————–.
-
#parse_date(input, msg = "Input could not be parsed.") ⇒ Object
Parse a date/time and throw an error if invalid.
-
#pluralized_array_from_hash(hash, singular_key, plural_key) ⇒ Object
Read array from the supplied hash favouring the singular key and then the plural key, and handling any nil entries.
-
#safe_glob(dir, patterns, flags = 0) ⇒ Object
Work the same way as Dir.glob but seperating the input into two parts (‘dir’ + ‘/’ + ‘pattern’) to make sure the first part(‘dir’) does not act as a pattern.
-
#slugify(string, mode: nil, cased: false) ⇒ Object
Slugify a filename or title.
-
#stringify_hash_keys(hash) ⇒ Object
Apply #to_s to all keys in the Hash.
-
#strip_heredoc(str) ⇒ Object
Takes an indented string and removes the preceding spaces on each line.
-
#symbolize_hash_keys(hash) ⇒ Object
Apply #to_sym to all keys in the hash.
-
#titleize_slug(slug) ⇒ Object
Takes a slug and turns it into a simple title.
- #transform_keys(hash) ⇒ Object
- #value_from_plural_key(hash, key) ⇒ Object
- #value_from_singular_key(hash, key) ⇒ Object
Instance Method Details
#add_permalink_suffix(template, permalink_style) ⇒ Object
Add an appropriate suffix to template so that it matches the specified permalink style.
template - permalink template without trailing slash or file extension permalink_style - permalink style, either built-in or custom
The returned permalink template will use the same ending style as specified in permalink_style. For example, if permalink_style contains a trailing slash (or is :pretty, which indirectly has a trailing slash), then so will the returned template. If permalink_style has a trailing “:output_ext” (or is :none, :date, or :ordinal) then so will the returned template. Otherwise, template will be returned without modification.
Examples:
add_permalink_suffix("/:basename", :pretty)
# => "/:basename/"
add_permalink_suffix("/:basename", :date)
# => "/:basename:output_ext"
add_permalink_suffix("/:basename", "/:year/:month/:title/")
# => "/:basename/"
add_permalink_suffix("/:basename", "/:year/:month/:title")
# => "/:basename"
Returns the updated permalink template
305 306 307 308 309 310 311 312 313 314 315 316 |
# File 'lib/j1/utils.rb', line 305 def add_permalink_suffix(template, permalink_style) case permalink_style when :pretty template << "/" when :date, :ordinal, :none template << ":output_ext" else template << "/" if permalink_style.to_s.end_with?("/") template << ":output_ext" if permalink_style.to_s.end_with?(":output_ext") end template end |
#deep_merge_hashes(master_hash, other_hash) ⇒ Object
Non-destructive version of deep_merge_hashes! See that method.
Returns the merged hashes.
85 86 87 |
# File 'lib/j1/utils.rb', line 85 def deep_merge_hashes(master_hash, other_hash) deep_merge_hashes!(master_hash.dup, other_hash) end |
#deep_merge_hashes!(target, overwrite) ⇒ Object
Merges a master hash with another hash, recursively.
master_hash - the “parent” hash whose values will be overridden other_hash - the other hash whose values will be persisted after the merge
This code was lovingly stolen from some random gem: gemjack.com/gems/tartan-0.1.1/classes/Hash.html
Thanks to whoever made it.
98 99 100 101 102 103 104 |
# File 'lib/j1/utils.rb', line 98 def deep_merge_hashes!(target, overwrite) merge_values(target, overwrite) merge_default_proc(target, overwrite) duplicate_frozen_values(target) target end |
#duplicable?(obj) ⇒ Boolean
110 111 112 113 114 115 116 117 |
# File 'lib/j1/utils.rb', line 110 def duplicable?(obj) case obj when nil, false, true, Symbol, Numeric false else true end end |
#has_yaml_header?(file) ⇒ Boolean
Determines whether a given file has
Returns true if the YAML front matter is present. rubocop: disable PredicateName
194 195 196 197 198 |
# File 'lib/j1/utils.rb', line 194 def has_yaml_header?(file) !!(File.open(file, "rb", &:readline) =~ %r!\A---\s*\r?\n!) rescue EOFError false end |
#is_project? ⇒ Boolean
44 45 46 47 48 49 50 51 52 |
# File 'lib/j1/utils.rb', line 44 def is_project? path = File.(Dir.pwd) puts "Check consistency of the J1 project ..." if File.exist?(path + '/package.json') && File.exist?(path + '/_config.yml') return true else puts "\e[31m" + "FATAL: Path #{path} seems not a J1 project folder" + "\e[0m" end end |
#is_project_setup? ⇒ Boolean
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/j1/utils.rb', line 54 def is_project_setup? path = File.(Dir.pwd) puts "Check setup state of the J1 project ..." if File.exist?(path + '/package-lock.json') && File.exist?(path + '/Gemfile.lock') return true else puts "\e[31m" + "FATAL: Project in path #{path} seems not initialized" + "\e[0m" puts "INFO: Consider to run 'j1 setup' in order to prepare the project for first use" end end |
#is_windows? ⇒ Boolean
65 66 67 68 |
# File 'lib/j1/utils.rb', line 65 def is_windows? #noinspection RubyResolve RbConfig::CONFIG["host_os"] =~ %r!mswin|mingw|cygwin!i end |
#mergable?(value) ⇒ Boolean
106 107 108 |
# File 'lib/j1/utils.rb', line 106 def mergable?(value) value.is_a?(Hash) || value.is_a?(Drops::Drop) end |
#merged_file_read_opts(site, opts) ⇒ Object
Returns merged option hash for File.read of self.site (if exists) and a given param
354 355 356 357 358 359 360 |
# File 'lib/j1/utils.rb', line 354 def merged_file_read_opts(site, opts) merged = (site ? site.file_read_opts : {}).merge(opts) if merged["encoding"] && !merged["encoding"].start_with?("bom|") merged["encoding"].insert(0, "bom|") end merged end |
#parse_date(input, msg = "Input could not be parsed.") ⇒ Object
Parse a date/time and throw an error if invalid
input - the date/time to parse msg - (optional) the error message to show the user
Returns the parsed date if successful, throws a FatalException if not
184 185 186 187 188 |
# File 'lib/j1/utils.rb', line 184 def parse_date(input, msg = "Input could not be parsed.") Time.parse(input).localtime rescue ArgumentError raise Errors::InvalidDateError, "Invalid date '#{input}': #{msg}" end |
#pluralized_array_from_hash(hash, singular_key, plural_key) ⇒ Object
Read array from the supplied hash favouring the singular key and then the plural key, and handling any nil entries.
hash - the hash to read from singular_key - the singular key plural_key - the plural key
Returns an array
127 128 129 130 131 132 133 |
# File 'lib/j1/utils.rb', line 127 def pluralized_array_from_hash(hash, singular_key, plural_key) [].tap do |array| value = value_from_singular_key(hash, singular_key) value ||= value_from_plural_key(hash, plural_key) array << value end.flatten.compact end |
#safe_glob(dir, patterns, flags = 0) ⇒ Object
Work the same way as Dir.glob but seperating the input into two parts (‘dir’ + ‘/’ + ‘pattern’) to make sure the first part(‘dir’) does not act as a pattern.
For example, Dir.glob(“path[/*”) always returns an empty array, because the method fails to find the closing pattern to ‘[’ which is ‘]’
Examples:
safe_glob("path[", "*")
# => ["path[/file1", "path[/file2"]
safe_glob("path", "*", File::FNM_DOTMATCH)
# => ["path/.", "path/..", "path/file1"]
safe_glob("path", ["**", "*"])
# => ["path[/file1", "path[/folder/file2"]
dir - the dir where glob will be executed under
(the dir will be included to each result)
patterns - the patterns (or the pattern) which will be applied under the dir flags - the flags which will be applied to the pattern
Returns matched pathes
342 343 344 345 346 347 348 349 |
# File 'lib/j1/utils.rb', line 342 def safe_glob(dir, patterns, flags = 0) return [] unless Dir.exist?(dir) pattern = File.join(Array(patterns)) return [dir] if pattern.empty? Dir.chdir(dir) do Dir.glob(pattern, flags).map { |f| File.join(dir, f) } end end |
#slugify(string, mode: nil, cased: false) ⇒ Object
Slugify a filename or title.
string - the filename or title to slugify mode - how string is slugified cased - whether to replace all uppercase letters with their lowercase counterparts
When mode is “none”, return the given string.
When mode is “raw”, return the given string, with every sequence of spaces characters replaced with a hyphen.
When mode is “default” or nil, non-alphabetic characters are replaced with a hyphen too.
When mode is “pretty”, some non-alphabetic characters (._~!$&‘()+,;=@) are not replaced with hyphen.
When mode is “ascii”, some everything else except ASCII characters a-z (lowercase), A-Z (uppercase) and 0-9 (numbers) are not replaced with hyphen.
If cased is true, all uppercase letters in the result string are replaced with their lowercase counterparts.
Examples:
slugify("The _config.yml file")
# => "the-config-yml-file"
slugify("The _config.yml file", "pretty")
# => "the-_config.yml-file"
slugify("The _config.yml file", "pretty", true)
# => "The-_config.yml file"
slugify("The _config.yml file", "ascii")
# => "the-config.yml-file"
Returns the slugified string
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'lib/j1/utils.rb', line 240 def slugify(string, mode: nil, cased: false) mode ||= "default" return nil if string.nil? unless SLUGIFY_MODES.include?(mode) return cased ? string : string.downcase end # Replace each character sequence with a hyphen # -------------------------------------------------------------------------- re = case mode when "raw" SLUGIFY_RAW_REGEXP when "default" SLUGIFY_DEFAULT_REGEXP when "pretty" # "._~!$&'()+,;=@" is human readable (not URI-escaped) in URL # and is allowed in both extN and NTFS. SLUGIFY_PRETTY_REGEXP when "ascii" # For web servers not being able to handle Unicode, the safe # method is to ditch anything else but latin letters and numeric # digits. SLUGIFY_ASCII_REGEXP end # Strip according to the mode slug = string.gsub(re, "-") # Remove leading/trailing hyphen slug.gsub!(%r!^\-|\-$!i, "") slug.downcase! unless cased slug end |
#stringify_hash_keys(hash) ⇒ Object
Apply #to_s to all keys in the Hash
hash - the hash to which to apply this transformation
Returns a new hash with stringified keys
173 174 175 |
# File 'lib/j1/utils.rb', line 173 def stringify_hash_keys(hash) transform_keys(hash) { |key| key.to_s rescue key } end |
#strip_heredoc(str) ⇒ Object
Takes an indented string and removes the preceding spaces on each line
72 73 74 |
# File 'lib/j1/utils.rb', line 72 def strip_heredoc(str) str.gsub(%r!^[ \t]{#{(str.scan(%r!^[ \t]*(?=\S)!).min || "").size}}!, "") end |
#symbolize_hash_keys(hash) ⇒ Object
Apply #to_sym to all keys in the hash
hash - the hash to which to apply this transformation
Returns a new hash with symbolized keys
164 165 166 |
# File 'lib/j1/utils.rb', line 164 def symbolize_hash_keys(hash) transform_keys(hash) { |key| key.to_sym rescue key } end |
#titleize_slug(slug) ⇒ Object
Takes a slug and turns it into a simple title.
78 79 80 |
# File 'lib/j1/utils.rb', line 78 def titleize_slug(slug) slug.split("-").map!(&:capitalize).join(" ") end |
#transform_keys(hash) ⇒ Object
151 152 153 154 155 156 157 |
# File 'lib/j1/utils.rb', line 151 def transform_keys(hash) result = {} hash.each_key do |key| result[yield(key)] = hash[key] end result end |
#value_from_plural_key(hash, key) ⇒ Object
139 140 141 142 143 144 145 146 147 148 149 |
# File 'lib/j1/utils.rb', line 139 def value_from_plural_key(hash, key) if hash.key?(key) || (hash.default_proc && hash[key]) val = hash[key] case val when String val.split when Array val.compact end end end |
#value_from_singular_key(hash, key) ⇒ Object
135 136 137 |
# File 'lib/j1/utils.rb', line 135 def value_from_singular_key(hash, key) hash[key] if hash.key?(key) || (hash.default_proc && hash[key]) end |