Guest User

Untitled

a guest
Jul 18th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. ## lib/ext/exclusive_scope.rb
  2.  
  3. module ActiveRecord
  4. module NamedScope
  5. class ExclusiveScope < Scope
  6. def initialize parent_scope, options = {}
  7. super(parent_scope, options)
  8. end
  9.  
  10. private
  11.  
  12. def method_missing *args, &block
  13. with_scope({}, :overwrite) { super }
  14. end
  15. end
  16. end
  17. end
  18.  
  19. class << ActiveRecord::Base
  20. def exclusive_scope options = {}
  21. ActiveRecord::NamedScope::ExclusiveScope.new self, options
  22. end
  23. end
  24.  
  25. ## app/models/event.rb
  26.  
  27. class Event < ActiveRecord::Base
  28. default_scope :conditions => { :campaign_id => nil }
  29. # ...
  30.  
  31. def self.campaign campaign
  32. ActiveRecord::NamedScope::ExclusiveScope.new(self, :conditions => { :campaign_id => campaign })
  33. end
  34.  
  35. # ...
  36. end
  37.  
  38. ## console
  39.  
  40. >> Event.all
  41. => []
  42. >> Event.campaign Campaign.first
  43. => [#<Event id: 1, name: "foo", created_at: "2009-11-25 22:34:26", updated_at: "2009-11-25 22:34:26", user_id: 1, start_time: "2009-11-25 22:34:26", end_time: "2009-11-26 00:34:26", description: nil, metro_area_id: nil, location: nil, street_address: nil, address_line_2: nil, city: nil, us_state: nil, zip_code: nil, delta: true, reminded_at: nil, campaign_id: 1>]
  44. >>
Add Comment
Please, Sign In to add comment