Created
July 18, 2011 03:42
-
-
Save kwatch/1088503 to your computer and use it in GitHub Desktop.
simulate named_scope by higher-order function + partial application in Python
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
| ## | |
| ## named_scope example in Rails2 | |
| ## (http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality) | |
| ## | |
| class User < ActiveRecord::Base | |
| named_scope :active, :conditions => {:active => true} | |
| named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } } | |
| end | |
| # same as User.find(:all, :conditions => {:active => true}) | |
| active_users = User.active | |
| # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago]) | |
| recent_users = User.recent | |
| # They're nest-able too! | |
| recent_active_users = User.active.recent | |
| ## | |
| ## simulate named_scope with higher-order function + partial application | |
| ## in Python | |
| ## | |
| def find_all(model_klass): | |
| def func(**kwargs): | |
| return model_klass.find('all', **kwargs) | |
| return func | |
| def active(function): | |
| def func(**kwargs): | |
| if not kwargs.has_key('conditions'): | |
| kwargs['conditions'] = [] | |
| kwargs['conditions'].append('active = true') | |
| ## or | |
| #kwargs.setdefault('conditions', []).append('active = true') | |
| return function(**kwargs) | |
| return func | |
| import time | |
| def recent(function): | |
| def func(**kwargs): | |
| now = time.time() | |
| sec = 60*60*24*7 | |
| if not kwargs.has_key('conditions'): | |
| kwargs['conditions'] = [] | |
| kwargs['conditions'].append('created_at > ' + (now - sec)) | |
| ## or | |
| #kwargs.setdefault('conditions', []).append('created_at > ' + (now - sec)) | |
| return function(**kwargs) | |
| return func | |
| func = find_all(User) | |
| users = find_all(User)() # same as func() | |
| active_users = active(find_all(User))() | |
| recent_active_users = recent(active(find_all(User)))() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment