Created
January 21, 2013 13:40
-
-
Save kwatch/4586127 to your computer and use it in GitHub Desktop.
モデルクラスから Query クラス (or Collection クラス) を分離すれば、黒魔術を一切使わなくても named_scope が実現できることを示すサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## モデルクラスから Query クラス (or Collection クラス) を分離すれば、 | |
| ## 黒魔術を一切使わなくても named_scope が実現できることを示すサンプル | |
| class ORM::Entity | |
| end | |
| class ORM::Query # or ORM::Collection | |
| def where(*args) ... end | |
| def order_by(*args) ... end | |
| def limit(n) ... end | |
| def offset(n) ... end | |
| def all() ... end | |
| def first() ... end | |
| end | |
| class SalesOrder < ORM::Entity | |
| set_table_name 'sales_orders' | |
| end | |
| class SalesOrders < ORM::Query | |
| set_entity_class SalesOrder | |
| def active | |
| where(:deleted => nil) | |
| self | |
| end | |
| def top(n) | |
| order_by("amount desc") | |
| limit(n) | |
| self | |
| end | |
| ### if you prefer... | |
| #def self.method_missing(meth, *args) | |
| # self.new.__send__(meth, *args) | |
| #end | |
| end | |
| ## main | |
| if __FILE__ == $0 | |
| sales = SalesOrders.new.active().top(10).all() | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment