Class: ProductScope
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- ProductScope
- Extended by:
- Scopes::Dynamic
- Defined in:
- app/models/product_scope.rb
Overview
ProductScope is model for storing named scopes with their arguments, to be used with ProductGroups.
Each product Scope can be applied to Product (or product scope) with #apply_on method which returns new combined named scope
Instance Method Summary collapse
-
#apply_on(another_scope) ⇒ Object
Applies product scope on Product model or another named scope.
-
#check_validity_of_scope ⇒ Object
checks validity of the named scope (if its safe and can be applied on Product).
-
#is_ordering? ⇒ Boolean
test ordering scope by looking for name pattern or missed arguments.
-
#products ⇒ Object
Get all products with this scope.
- #to_s ⇒ Object
- #to_sentence ⇒ Object
Methods included from Scopes::Dynamic
Instance Method Details
#apply_on(another_scope) ⇒ Object
Applies product scope on Product model or another named scope
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'app/models/product_scope.rb', line 25 def apply_on(another_scope) array = *self.arguments if Product.respond_to?(self.name.intern) relation2 = if (array.blank? || array.size < 2) Product.send(self.name.intern, array.try(:first)) else Product.send(self.name.intern, *array) end else relation2 = Product.({self.name.intern => array}).relation end unless another_scope.class == ActiveRecord::Relation another_scope = another_scope.send(:relation) end another_scope.merge(relation2) end |
#check_validity_of_scope ⇒ Object
checks validity of the named scope (if its safe and can be applied on Product)
50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'app/models/product_scope.rb', line 50 def check_validity_of_scope errors.add(:name, "is not a valid scope name") unless Product.respond_to?(self.name.intern) apply_on(Product).limit(0) != nil rescue Exception => e unless Rails.env.production? puts "name: #{self.name}" puts "arguments: #{self.arguments.inspect}" puts e. puts e.backtrace end errors.add(:arguments, "are incorrect") end |
#is_ordering? ⇒ Boolean
test ordering scope by looking for name pattern or missed arguments
65 66 67 |
# File 'app/models/product_scope.rb', line 65 def is_ordering? name =~ /^(ascend_by|descend_by)/ || arguments.blank? end |
#products ⇒ Object
Get all products with this scope
18 19 20 21 22 |
# File 'app/models/product_scope.rb', line 18 def products if Product.respond_to?(name) Product.send(name, *arguments) end end |
#to_s ⇒ Object
75 76 77 |
# File 'app/models/product_scope.rb', line 75 def to_s to_sentence end |
#to_sentence ⇒ Object
69 70 71 72 73 |
# File 'app/models/product_scope.rb', line 69 def to_sentence result = I18n.t(:sentence, :scope => [:product_scopes, :scopes, self.name], :default => "") result = I18n.t(:name, :scope => [:product_scopes, :scopes, self.name]) if result.blank? result % [*self.arguments] end |