Skip to content

Instantly share code, notes, and snippets.

@tomoyamkung
Created August 6, 2013 08:43
Show Gist options
  • Select an option

  • Save tomoyamkung/6162817 to your computer and use it in GitHub Desktop.

Select an option

Save tomoyamkung/6162817 to your computer and use it in GitHub Desktop.
[Ruby]配列に格納されている文字列を次々にチェックし、あるキーワードから始まっている行があれば置換するという典型処理のスニペット
#! ruby
#-*- encoding: utf-8 -*-
require 'test/unit'
class RadiusImageFilterTest < Test::Unit::TestCase
require_relative 'filter'
def test_execute_hasnot_tag
# setup
content = [
"hoge.png"
]
expected = content
# excercise
actual = RadiusImageFilter.new.execute(content)
# verify
assert_equal(expected, actual)
end
def test_execute_has_tag
# setup
content = [
'{% _RADIUS_IMAGE_:hoge.png %}'
]
expected = [
'<div class="image_frame_shadow_radius"><img src="hoge.png"></div>'
]
# excercise
actual = RadiusImageFilter.new.execute(content)
# verify
assert_equal(1, actual.size)
assert_equal(expected, actual)
end
def test_execute_has_tag_malti
# setup
content = [
'{% _RADIUS_IMAGE_:hoge.png %}',
'{% _RADIUS_IMAGE_:/path/to/var.png %}',
'{% _RADIUS_IMAGE_:path/to/piyo.png %}'
]
expected = [
'<div class="image_frame_shadow_radius"><img src="hoge.png"></div>',
'<div class="image_frame_shadow_radius"><img src="/path/to/var.png"></div>',
'<div class="image_frame_shadow_radius"><img src="path/to/piyo.png"></div>'
]
# excercise
actual = RadiusImageFilter.new.execute(content)
# verify
assert_equal(expected.size, actual.size)
assert_equal(expected, actual)
end
end
#! ruby
#-*- encoding: utf-8 -*-
class RadiusImageFilter
# 置換する行の目印
TAG_KEYWORD = '{% _RADIUS_IMAGE_'
# 置換に使用するテンプレート
# _IMG_ の部分を実際のパスに置換する
HTML_TEMPLATE = '<div class="image_frame_shadow_radius"><img src="_IMG_"></div>'
def execute(content)
return content if not has_tag_line?(content)
dest = Array.new
content.each_with_index do |line, index|
if tag_line?(line)
dest.push(replace_line(line))
else
dest.push(line)
end
end
return dest
end
private
# タグを HTML に置換する
def replace_line(line)
return HTML_TEMPLATE.sub("_IMG_", extract_image_path(line))
end
# 画像パスを抽出する
def extract_image_path(line)
return line.split(":")[1].split(" ")[0]
end
# 引数の文字列がタグから始まっているかを問い合わせる
def tag_line?(line)
return line.start_with?(TAG_KEYWORD)
end
# 配列の中にタグが含まれているかを問い合わせる
def has_tag_line?(content)
return content.join(' ').include?(TAG_KEYWORD)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment