dry form_helper using meta programming.

not sure if this improves readability, but codeclimate should be happier...
This commit is contained in:
Reinier Balt 2014-02-10 22:30:06 +01:00
parent 5de96d7eda
commit a7807a4b66
2 changed files with 40 additions and 13 deletions

View file

@ -4,6 +4,16 @@ module RecurringTodos
def initialize(recurring_todo)
@recurring_todo = recurring_todo
@method_map = {
# delegate daily_xxx to daily_pattern.xxx
"daily" => {prefix: "", method: daily_pattern},
"weekly" => {prefix: "", method: weekly_pattern},
"monthly" => {prefix: "", method: monthly_pattern},
"yearly" => {prefix: "", method: yearly_pattern},
# delegate on_xxx to weekly_pattern.on_xxx
"on" => {prefix: "on_", method: weekly_pattern}
}
end
def create_pattern(pattern_class)
@ -29,20 +39,13 @@ module RecurringTodos
end
def method_missing(method, *args)
if method.to_s =~ /^daily_(.+)$/
daily_pattern.send($1, *args)
elsif method.to_s =~ /^weekly_(.+)$/
weekly_pattern.send($1, *args)
elsif method.to_s =~ /^monthly_(.+)$/
monthly_pattern.send($1, *args)
elsif method.to_s =~ /^yearly_(.+)$/
yearly_pattern.send($1, *args)
elsif method.to_s =~ /^on_(.+)$/ # on_monday, on_tuesday, etc.
weekly_pattern.send(method, *args)
else
# no match, let @recurring_todo handle it, or fail
@recurring_todo.send(method, *args)
# delegate daily_xxx to daily_pattern, weekly_xxx to weekly_pattern, etc.
if method.to_s =~ /^([^_]+)_(.+)$/
return @method_map[$1][:method].send(@method_map[$1][:prefix]+$2, *args) unless @method_map[$1].nil?
end
# no match, let @recurring_todo handle it, or fail
@recurring_todo.send(method, *args)
end
end

View file

@ -0,0 +1,24 @@
require_relative '../../test_helper'
module RecurringTodos
class AttributeHandlerTest < ActiveSupport::TestCase
fixtures :users
def test_method_missing
rt = users(:admin_user).recurring_todos.first
rt.every_other1 = 42
rt.every_day = 'smtwtfs'
rt.save
h = FormHelper.new(rt)
assert_equal 42, h.daily_every_x_days, "should be passed to DailyRepeatPattern"
assert_equal 42, h.weekly_every_x_week, "should be passed to WeeklyRepeatPattern"
assert_equal 42, h.monthly_every_x_day, "should be passed to MonthlyRepeatPattern"
assert_equal 42, h.yearly_every_x_day, "should be passed to YearlyRepeatPattern"
assert h.on_monday, "should be passed to WeeklyRepeatPattern"
end
end
end