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
FOLDER_LENGTH_LIMIT =
50
HR_TEXT =
"" * 35
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
}
HR_TAG =
"<hr>"

Class Method Summary collapse

Class Method Details

.ampersand_to_entity(str) ⇒ Object

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



159
160
161
# File 'lib/helper.rb', line 159

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

.convert_to_windows_path(path) ⇒ Object

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



152
153
154
# File 'lib/helper.rb', line 152

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

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

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

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



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/helper.rb', line 275

def copy_files(from, dest_dir, check_timestamp: true, exception: 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
    begin
      FileUtils.copy(path, dest)
    rescue StandardError => e
      raise if exception
      error "#{path} はコピー出来ませんでした"
    end
  end
end

.date_string_to_time(date) ⇒ Object

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



301
302
303
304
305
306
307
308
309
310
# File 'lib/helper.rb', line 301

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



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

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)


46
47
48
# File 'lib/helper.rb', line 46

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

.erb_copy(src, dst, _binding) ⇒ Object

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



376
377
378
379
380
# File 'lib/helper.rb', line 376

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

.extract_illust_chuki(str) ⇒ Object

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



166
167
168
169
170
171
172
173
# File 'lib/helper.rb', line 166

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)


317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/helper.rb', line 317

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



52
53
54
# File 'lib/helper.rb', line 52

def $stdin.getch
  WinAPI._getch.chr
end

.numeric_length(len) ⇒ Object

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



385
386
387
388
# File 'lib/helper.rb', line 385

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

.open_browser(url) ⇒ Object



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

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



59
60
61
62
63
64
65
# File 'lib/helper.rb', line 59

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



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

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



15
16
17
# File 'lib/web/helper4web.rb', line 15

def print_horizontal_rule(io = $stdout)
  io.puts HR_TEXT
end

.os_cygwin?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/helper.rb', line 29

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

.os_mac?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/helper.rb', line 25

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

.os_windows?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/helper.rb', line 21

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

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

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



123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/helper.rb', line 123

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


100
101
102
# File 'lib/helper.rb', line 100

def print_horizontal_rule(io = $stdout)
  io.puts HR_TEXT
end

.replace_filename_special_chars(str, invalid_replace = false) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/helper.rb', line 104

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

エンティティ復号



141
142
143
144
145
146
147
# File 'lib/helper.rb', line 141

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

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



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
249
250
251
252
# File 'lib/helper.rb', line 216

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

伏せ字にする

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



336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/helper.rb', line 336

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

.truncate_folder_title(title, limit = ) ⇒ Object



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

def truncate_folder_title(title, limit = Inventory.load["folder-length-limit"])
  limit ||= FOLDER_LENGTH_LIMIT
  return title if title.length <= limit
  title[0...limit].strip
end

.truncate_path(path, limit = , extname: nil) ⇒ Object

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



353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/helper.rb', line 353

def truncate_path(path, limit = Inventory.load["filename-length-limit"], extname: nil)
  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の変数がなんの型かシンボルで取得



263
264
265
# File 'lib/helper.rb', line 263

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

.variable_type_to_description(type) ⇒ Object

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



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/helper.rb', line 192

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