Ruby on Rails 3.2.2 と Squeel gem を使用しています。次のステートメントがあり、 Mixin モジュールmy_squeel_query
でメソッドをリファクタリングしようとしています(多くのモデルで使用されているため)。
# Note: 'article_comment_associations' and 'model_as_like_article_comment_associations'
# refer to database table names.
class Article < ActiveRecord::Base
def my_squeel_query
commenters.
.where{
article_comment_associations.article_id.eq(my{self.id}) & ...
}
end
end
class ModelAsLikeArticle < ActiveRecord::Base
def my_squeel_query
commenters.
.where{
model_as_like_article_comment_associations.article_id.eq(my{self.id}) & ...
}
end
end
私の問題は、Mixin モジュールで動的な名前を生成してステートメントをリファクタリングできないことです。つまり、次のようなものを使用して、関連する名前を動的に生成できます。article_comment_associations
model_as_like_article_comment_associations
String
"#{self.class.to_s.singularize}_comment_associations"
class Article < ActiveRecord::Base
include MyModule
end
class ModelAsLikeArticle < ActiveRecord::Base
include MyModule
end
module MyModule
def my_squeel_query
commenters.
.where{
# Note: This code doesn't work. It is just an sample.
"#{self.class.to_s.singularize}_comment_associations".article_id.eq(my{self.id}) & ...
}
end
end
しかし、私の場合ではないので、名前を「構築」しmy_squeel_query
てモデル間で「共有」することはできません。
Squeel gem に関連する関連付け名を動的に生成するにはどうすればよいですか? 別の方法でリファクタリングを検討する必要がありますか? 何についてアドバイスしますか?