Module: Helper

Defined in:
lib/helper.rb,
lib/web/helper4web.rb

Overview

雑多なお助けメソッド群

Defined Under Namespace

Modules: CacheLoader Classes: AsyncCommand, InvalidVariableName, InvalidVariableType, UnknownVariableType

Constant Summary collapse

HOST_OS =
RbConfig::CONFIG["host_os"]
FILENAME_LENGTH_LIMIT =
50
ENTITIES =
{ quot: '"', amp: "&", nbsp: " ", lt: "<", gt: ">", copy: "(c)", "#39" => "'" }
INTEGER_CLASS =
RUBY_VERSION >= "2.4.0" ? Integer : Fixnum
TYPE_OF_VALUE =
{
  TrueClass => :boolean, FalseClass => :boolean, INTEGER_CLASS => :integer,
  Float => :float, String => :string
}

Class Method Summary collapse

Class Method Details

.ampersand_to_entity(str) ⇒ Object

アンパサンドをエンティティに変換



155
156
157
# File 'lib/helper.rb', line 155

def ampersand_to_entity(str)
  str.gsub(/&(?!amp;)/mi, "&amp;")
end

.convert_to_windows_path(path) ⇒ Object

CYGWINのパスからwindowsのパスへと変換(cygpathを呼び出すだけ)



148
149
150
# File 'lib/helper.rb', line 148

def convert_to_windows_path(path)
  `cygpath -aw \"#{path}\"`.strip
end

.copy_files(from, dest_dir, check_timestamp: true) ⇒ Object

ファイルを指定したディレクトリにまとめてコピーする 指定したディレクトリが存在しなければ作成する

from: ファイルパスをまとめた Array dest_dir: コピー先のディレクトリ check_timestamp: タイムスタンプを比較して新しければコピーする



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/helper.rb', line 271

def copy_files(from, dest_dir, check_timestamp: true)
  from.each do |path|
    basename = File.basename(path)
    dirname = File.basename(File.dirname(path))
    save_dir = File.join(dest_dir, dirname)
    unless File.directory?(save_dir)
      FileUtils.mkdir_p(save_dir)
    end
    dest = File.join(save_dir, basename)
    if check_timestamp && File.exist?(dest)
      src_mtime = File.mtime(path)
      dest_mtime = File.mtime(dest)
      next if dest_mtime >= src_mtime
    end
    FileUtils.copy(path, dest)
  end
end

.date_string_to_time(date) ⇒ Object

日付形式の文字列をTime型に変換する



292
293
294
295
296
297
298
299
300
301
# File 'lib/helper.rb', line 292

def date_string_to_time(date)
  case date
  when Time
    date
  when String
    Time.parse(date.sub(/[\((].+?[\))]/, "").tr("年月日時分秒@;", "///::: :")).getlocal
  end
rescue ArgumentError
  nil
end

.determine_osObject



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

def determine_os
  case
  when os_windows?
    :windows
  when os_mac?
    :mac
  when os_cygwin?
    :cygwin
  else
    :other
  end
end

.engine_jruby?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/helper.rb', line 44

def engine_jruby?
  @@engine_is_jruby ||= RUBY_ENGINE == "jruby"
end

.erb_copy(src, dst, _binding) ⇒ Object

src をERBとして読み込んでから dst に書き出す



360
361
362
363
364
# File 'lib/helper.rb', line 360

def erb_copy(src, dst, _binding)
  data = File.read(src, mode: "r:BOM|UTF-8")
  result = ERB.new(data, nil, "-").result(_binding)
  File.write(dst, result)
end

.extract_illust_chuki(str) ⇒ Object

文章の中から挿絵注記を分離する



162
163
164
165
166
167
168
169
# File 'lib/helper.rb', line 162

def extract_illust_chuki(str)
  illust_chuki_array = []
  extracted_str = str.gsub(/[  \t]*?([#挿絵(.+?)入る])\n?/) do
    illust_chuki_array << $1
    ""
  end
  [extracted_str, illust_chuki_array]
end

.file_latest?(path) ⇒ Boolean

指定のファイルが前回のチェック時より新しいかどうか

初回チェック時は無条件で新しいと判定

Returns:

  • (Boolean)


308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/helper.rb', line 308

def file_latest?(path)
  @@file_mtime_list ||= {}
  fullpath = File.expand_path(path)
  last_mtime = @@file_mtime_list[fullpath]
  mtime = File.mtime(fullpath)
  if mtime == last_mtime
    result = false
  else
    result = true
    @@file_mtime_list[fullpath] = mtime
  end
  result
end

.getchObject



50
51
52
# File 'lib/helper.rb', line 50

def $stdin.getch
  WinAPI._getch.chr
end

.numeric_length(len) ⇒ Object

カンマ付き数字列を数値に変換



369
370
371
372
# File 'lib/helper.rb', line 369

def numeric_length(len)
  return len unless len.is_a?(String)
  len.delete(",").to_i
end

.open_browser(url) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/helper.rb', line 81

def open_browser(url)
  case determine_os
  when :windows
    escaped_url = url.gsub("%", "%^").gsub("&", "^&")
    # MEMO: start の引数を "" で囲むと動かない
    system(%!start #{escaped_url}!)
  when :cygwin
    system(%!cygstart #{url}!)
  when :mac
    system(%!open "#{url}"!)
  else
    open_browser_linux(url, "ブラウザが見つかりませんでした")
  end
end

.open_browser_linux(address, error_message) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/helper.rb', line 57

def open_browser_linux(address, error_message)
  %w(xdg-open firefox w3m).each do |browser|
    system(%!#{browser} "#{address}"!)
    return if $?.success?
  end
  error error_message
end

.open_directory(path, confirm_message = nil) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/helper.rb', line 65

def open_directory(path, confirm_message = nil)
  if confirm_message
    return unless Narou::Input.confirm(confirm_message, false, false)
  end
  case determine_os
  when :windows
    system(%!explorer "file:///#{path.encode(Encoding::Windows_31J)}"!)
  when :cygwin
    system(%!cygstart "#{path}"!)
  when :mac
    system(%!open "#{path}"!)
  else
    open_browser_linux(path, "フォルダが開けませんでした")
  end
end

.original_print_horizontal_ruleObject



12
13
14
# File 'lib/web/helper4web.rb', line 12

def print_horizontal_rule
  puts "" * 35
end

.os_cygwin?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/helper.rb', line 27

def os_cygwin?
  @@os_is_cygwin ||= HOST_OS =~ /cygwin/i
end

.os_mac?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/helper.rb', line 23

def os_mac?
  @@os_is_mac ||= HOST_OS =~ /darwin/i
end

.os_windows?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/helper.rb', line 19

def os_windows?
  @@os_is_windows ||= HOST_OS =~ /mswin(?!ce)|mingw|bccwin/i
end

.pretreatment_source(src, encoding = Encoding::UTF_8) ⇒ Object

ダウンロードした文字列をエンコード及び不正な文字列除去、改行コード統一



119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/helper.rb', line 119

def pretreatment_source(src, encoding = Encoding::UTF_8)
  encoding_class = Encoding.find(encoding)
  src.force_encoding(encoding)
     .tap do |this|
       if encoding_class != Encoding::UTF_8
         this.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace)
       end
     end
     .scrub("?")
     .gsub("\r", "")
     .gsub(/&#x([0-9a-f]+);/i) { [$1.hex].pack("U") }
     .gsub(/&#(\d+);/) { [$1.to_i].pack("U") }
end


96
97
98
# File 'lib/helper.rb', line 96

def print_horizontal_rule
  puts "" * 35
end

.replace_filename_special_chars(str, invalid_replace = false) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/helper.rb', line 100

def replace_filename_special_chars(str, invalid_replace = false)
  result = str.tr("/:*?\"<>|.`", "/:*?”〈〉|.`").gsub("\\", "").gsub("\t", "").gsub("\n", "")
  if Inventory.load("local_setting")["normalize-filename"]
    begin
      result.unicode_normalize!
    rescue Encoding::CompatibilityError
    end
  end
  if invalid_replace
    org_encoding = result.encoding
    result = result.encode(Encoding::Windows_31J, invalid: :replace, undef: :replace, replace: "_")
                   .encode(org_encoding)
  end
  result
end

.restore_entity(str) ⇒ Object

エンティティ復号



137
138
139
140
141
142
143
# File 'lib/helper.rb', line 137

def restore_entity(str)
  result = str.dup
  ENTITIES.each do |key, value|
    result.gsub!("&#{key};", value)
  end
  result
end

.string_cast_to_type(value, type) ⇒ Object

文字列データを指定された型にキャストする



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/helper.rb', line 212

def string_cast_to_type(value, type)
  result = nil
  case type
  when :boolean
    case value.strip.downcase
    when "true"
      result = true
    when "false"
      result = false
    else
      raise InvalidVariableType, type
    end
  when :integer
    begin
      result = Integer(value)
    rescue
      raise InvalidVariableType, type
    end
  when :float
    begin
      result = Float(value)
    rescue
      raise InvalidVariableType, type
    end
  when :directory, :file
    if File.method("#{type}?").call(value)
      result = File.expand_path(value)
    else
      raise InvalidVariableType, type
    end
  when :string, :select, :multiple
    result = value
  else
    raise UnknownVariableType, type
  end
  result
end

.to_unprintable_words(string, mask = "●") ⇒ Object

伏せ字にする

数字やスペース、句読点、感嘆符はそのままにする



327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/helper.rb', line 327

def to_unprintable_words(string, mask = "")
  result = "".dup
  string.each_char do |char|
    result += case char
              when /[0-90-9  、。!?!?]/
                char
              else
                mask
              end
  end
  result
end

.truncate_path(path, limit = FILENAME_LENGTH_LIMIT) ⇒ Object

長過ぎるファイルパスを詰める ファイル名部分のみを詰める。拡張子は維持する



344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/helper.rb', line 344

def truncate_path(path, limit = FILENAME_LENGTH_LIMIT)
  dirname = File.dirname(path)
  extname = File.extname(path)
  basename = File.basename(path, extname)
  if basename.length > limit
    basename = basename[0...limit]
    dirname = nil if dirname == "."
    [dirname, "#{basename}#{extname}"].compact.join("/")
  else
    path
  end
end

.type_of_value(value) ⇒ Object

Rubyの変数がなんの型かシンボルで取得



259
260
261
# File 'lib/helper.rb', line 259

def type_of_value(value)
  TYPE_OF_VALUE[value.class]
end

.variable_type_to_description(type) ⇒ Object

与えられた型情報の意味文字列を取得



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/helper.rb', line 188

def variable_type_to_description(type)
  case type
  when :boolean
    "true/false  "
  when :integer
    "整数        "
  when :float
    "小数点数    "
  when :string, :select
    "文字列      "
  when :multiple
    "文字列(複数)"
  when :directory
    "フォルダパス"
  when :file
    "ファイルパス"
  else
    raise UnknownVariableType, type
  end
end