Created
June 21, 2016 03:46
-
-
Save JunichiIto/9cce41d3e5766f7fe20ff53863585d52 to your computer and use it in GitHub Desktop.
Dynamically parse and calc month number in text.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
require 'date' | |
class SandboxTest < Minitest::Test | |
def format_month(text, current_date) | |
text.gsub(/#\{ *month(?: *([-+]) *(\d+))? *\}/) do | |
op = Regexp.last_match[1] | |
val = Regexp.last_match[2] | |
if op == '+' | |
(current_date >> val.to_i).month | |
elsif op == '-' | |
(current_date << val.to_i).month | |
else | |
current_date.month | |
end | |
end | |
end | |
def test_format_month | |
text = '#{month}月です。' | |
current_date = Date.parse('2016-06-21') | |
assert_equal '6月です。', format_month(text, current_date) | |
text = '#{month + 1}月です。' | |
current_date = Date.parse('2016-06-21') | |
assert_equal '7月です。', format_month(text, current_date) | |
text = '#{month-1}月です。' | |
current_date = Date.parse('2016-06-21') | |
assert_equal '5月です。', format_month(text, current_date) | |
text = '#{month + 1}月です。' | |
current_date = Date.parse('2016-12-21') | |
assert_equal '1月です。', format_month(text, current_date) | |
text = '#{ month - 1 }月です。' | |
current_date = Date.parse('2016-01-21') | |
assert_equal '12月です。', format_month(text, current_date) | |
text = '#{month}月です。#{month+1}月です。' | |
current_date = Date.parse('2016-06-21') | |
assert_equal '6月です。7月です。', format_month(text, current_date) | |
text = '#{month * 5}月です。' | |
current_date = Date.parse('2016-06-21') | |
assert_equal '#{month * 5}月です。', format_month(text, current_date) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment