2012-01-19 9 views
0

をリファクタリング、私は(2つの異なるが、非常に類似したクエリを使用してい差がちょうど追加の基準は今mongoidコール

pop_answers = Answer.any_of(
    {:num_likes.gte=>3, :image_filename.exists=>true}, 
).desc(:created_at).skip(to_skip).limit(per_page).map{|a|a} 

pop_answers_in_topic = Answer.any_of(
    {:num_likes.gte=>3, :image_filename.exists=>true, :topic_id=>some_id}, 
).desc(:created_at).skip(to_skip).limit(per_page).map{|a|a} 

である私はこれをリファクタリングするにはどうすればよい?

答えて

0

あなたはにクラスメソッドを追加することができますAnswer

def self.popular(offset, limit, for_topic_id = nil) 
    conditions = { :num_likes.gte => 3, :image_filename.exists => true } 
    conditions[:topic_id] = for_topic_id if(for_topic_id) 
    any_of(conditions).desc(:created_at).skip(offset).limit(limit).map{|a|a} 
end 

それとも、単なる話題のIDよりも期待している場合:

def self.popular(offset, limit, options = { }) 
    conditions = { :num_likes.gte => 3, :image_filename.exists => true }.merge(options) 
    any_of(conditions).desc(:created_at).skip(offset).limit(limit).map{|a|a} 
end 

私はモンゴイドは使用しませんが、面白い.map{|a|a}を削除するか、を代わりに使用することができます。

それとも何かスコープっぽい:

# In answer.rb 
def self.popular(for_topic_id = nil) 
    conditions = { :num_likes.gte => 3, :image_filename.exists => true } 
    conditions[:topic_id] = for_topic_id if(for_topic_id) 
    any_of(conditions) 
end 

# And then where you're using it... 
pop_answers = Answer.popular.desc(:created_at).skip(to_skip).limit(per_page).map{|a|a} 
pop_in_topic = Answer.popular(some_id).desc(:created).skip(to_skip).limit(per_page).map{|a|a} 

そして私はany_ofは本当にあなたがここに探しているされているものならば、おそらくall_ofがより理にかなって疑問があります。