2012-03-14 104 views
0

我有一个方法,从条件数组和条目数组中检索条件和条目,其中检查任意数量的条件的任意数量的条件。条件和项目是哈希基本上,对于提供给方法的条件和项目,找出条件需要检查的项目的属性。这个列表实际上更长,并且正在研究如何使这个更好(看起来这可能更简洁,也许更多rubyesque)没有其他工作(还),所以我想就如何重构这一点的一些输入:案例陈述重构,基本ruby

def check_condition(condition, item) 
    case condition.attribute 
    when :author 
     i = item.author.name; 
    when :title 
     i = item.title 
    when :body 
     i = item.body 
    when :domain 
     i = URI(item.url).host 
    when :account_age 
     i = item.author.author_age 
    end 
    @logger.info "#{i} to be checked if #{condition.query} #{condition.attribute}" 
    test_condition(condition, item, i) 
    end 

编辑:

只是为了更清晰,项目和条件是哈希表(HASHIE ::醪是精确的)那里的条件一般从可能是一个配置文件构成是这样的:

[submitted_link, account_age, is_less_than, 30, remove] 

结果如下:

{subject: submitted_link, attribute: account_age, query: is_less_than, what: 30 action:remove} 

而且你可以看到,如果你愿意的话到底是怎么回事这里全:https://github.com/blueblank/reddit_modbot/blob/master/lib/modbot/modbot_check.rb

EDIT2:

解决的现实是,有些正规化我的条件变量术语和项目所以这可以减少到1线

i = item.send(condition.attribute) 

没有乱七八糟的,影响最小

回答

2

一种替代方法可能涉及将check_condition定义为item.class的方法。因此,而不是...

x = check_condition(c, item) 

...你可能有类似...

x = item.condition(c) 

然后,如果你不喜欢大的情况下,你可以创建一个散列与那些进程内对象的值,通过:author键,:title,

class A 
    def initialize 
    @h = { :a => proc { @author } } 
    end 
    def set x 
    @author = x 
    end 
    def f x 
    @h[x].call 
    end 
end 

o = A.new 
o.set 'Me' 
p(o.f(:a)) 

然而,一旦你做,那么你可能想要采取第三步,即将所有这些对象属性改为Hash中的值,第一步...也许...