2011-06-24 5 views
0

Ruby on Rails 3.0.7を使用していて、whereメソッドに応答して「カスタム」データ構造を初期化する方法を知りたい一般的なRoR AssociationCollectionオブジェクトの場合と同様に動作します。例えばInitialize `where`メソッドに応答する「カスタム」データ構造を構築する

# The following code should work after build the 'test_data' as well... 
# but how to build that? 

test_data.where(:test_attribute => 'test_value') 
+0

あなたは私はあなたを思っているあなたの変数名から[スコープ](http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#method-i-scope) – rubyprince

+0

について尋ねていますあなたの単体テストでこの振る舞いを望んでいますか?もしそうなら、あなたのモデルとその方法を模擬してみてください。それ以外の場合はわかりません:) – jaydel

+0

@jaydel - いいえ、 "test"は単なる名前です。 – user502052

答えて

1

私はあなたが後にしているものに完全に明確ではないんだけど、あなたは(たとえば)の周りに検索を行うためにwhereを使用ハッシュの配列をラッパーを作成することができます。

class Search 
    def initialize(data) 
    @data = data 
    end 

    def where(filters={}) 
    @data.select do |item| 
     filters.all?{|key, value| item[key] == value } 
    end 
    end 
end 



data = [ 
    { :name => 'Sam', :age => 27, :gender => 'M' }, 
    { :name => 'Sue', :age => 27, :gender => 'F' }, 
    { :name => 'Bob', :age => 32, :gender => 'M' } 
] 

search = Search.new(data) 
search.where(:age => 27)  # returns array containing Sam and Sue hashes 
search.where(:gender => 'M') # returns array containing Sam and Bob hashes 
search.where(:age => 27, :gender => 'M') # returns array containing just Sam