2012-03-14 102 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中的值,第一步...也許...