私はあなたが言っていることを得る。私は.NETの背景からも来ています。あなたのビジネスロジックを抽象化して&パーシスタンスロジックは良いアイデアです。私はあなたのためにそれを行う宝石をまだ見つけていない。しかし、あなたは簡単に何かを簡単に転がすことができます。最終的には、リポジトリパターンは基本的にあなたの持続層に委譲するクラスです。ここで
は、私が何をすべきかです:
require 'active_support/core_ext/module/attribute_accessors'
class GenericRepository
def initialize(options = {})
@scope = options[:scope]
@association_name = options[:association_name]
end
def self.set_model(model, options = {})
cattr_accessor :model
self.model = model
end
def update(record, attributes)
check_record_matches(record)
record.update_attributes!(attributes)
end
def save(record)
check_record_matches(record)
record.save
end
def destroy(record)
check_record_matches(record)
record.destroy
end
def find_by_id(id)
scoped_model.find(id)
end
def all
scoped_model.all
end
def create(attributes)
scoped_model.create!(attributes)
end
private
def check_record_matches(record)
raise(ArgumentError, "record model doesn't match the model of the repository") if not record.class == self.model
end
def scoped_model
if @scope
@scope.send(@association_name)
else
self.model
end
end
end
そして、あなたは、例えばポストリポジトリを持つことができます。
class PostRepository < GenericRepository
set_model Post
# override all because we also want to fetch the comments in 1 go.
def all
scoped_model.all(:include => :comments)
end
def count()
scoped_model.count
end
end
コントローラでbefore_filterでインスタンシエートするか、初期化するか、どこからでも行うことができます。この場合、私はそれをcurrent_userにスコープして、それらのレコードだけを取り出し、現在のユーザーのために自動的に投稿を作成するようにします。
def initialize
@post_repository = PostRepository.new(:scope => @current_user, :association_name => 'posts')
end
def index
@posts = @post_repository.all
respond_with @posts, :status => :ok
end
私は小さなDIフレームワークであるhttps://github.com/bkeepers/morphineに出くわしました。それはあなたのために働くことができる:)しかし、DIは、ルビーの頻繁に使用されるパターンではありません。また、私は自分のリポジトリをインスタンス化して、現在のユーザーまたは他の何かにそれらをスコープします。
私はあなたが求めるものだけを行う正しい方法を見つけるために探求しています。もし私がこれを見つけたら少し書き上げます。しかし、今のところ、私のコントローラである持続性&の間でクリーンカットを行うだけで十分です。これが適切に行われれば、後で別のシステムに切り替えるのは面倒ではありません。または、キャッシングなどを追加してください。
http://lancecarlson.github.com/2012/05/15/dci-and-decoupling-business-logic-from-ruby-on-rails.htmlこれは誰かがBobさんの記事に返信してください。もっと来る。 – SpoBo
私はまた、リポジトリパターンを実装する宝石を探しています。 – Andrew