Module: HasScope::ClassMethods
- Defined in:
- lib/has_scope.rb
Instance Method Summary collapse
- #define_scope_helper_methods ⇒ Object
-
#has_scope(*scopes, &block) ⇒ Object
Detects params from url and apply as scopes to your classes.
Instance Method Details
#define_scope_helper_methods ⇒ Object
90 91 92 93 94 95 96 97 98 99 |
# File 'lib/has_scope.rb', line 90 def define_scope_helper_methods scopes_configuration.keys.each do |scope| instance_eval do define_method "#{scope.to_s.singularize}_scope?" do current_scopes.has_key?(scope.to_sym) end end end helper_method *scopes_configuration.keys.map {|scope| "#{scope.to_s.singularize}_scope?" } end |
#has_scope(*scopes, &block) ⇒ Object
Detects params from url and apply as scopes to your classes.
Options
-
:type
- Checks the type of the parameter sent. If set to :booleanit just calls the named scope, without any argument. By default, it does not allow hashes or arrays to be given, except if type :hash or :array are set.
-
:only
- In which actions the scope is applied. By default is :all. -
:except
- In which actions the scope is not applied. By default is :none. -
:as
- The key in the params hash expected to find the scope.Defaults to the scope name.
-
:using
- If type is a hash, you can provide :using to convert the hash toa named scope call with several arguments.
-
:if
- Specifies a method, proc or string to call to determineif the scope should apply
-
:unless
- Specifies a method, proc or string to call to determineif the scope should NOT apply.
-
:default
- Default value for the scope. Whenever supplied the scopeis always called.
-
:allow_blank
- Blank values are not sent to scopes by default. Set to true to overwrite.
Block usage
has_scope also accepts a block. The controller, current scope and value are yielded to the block so the user can apply the scope on its own. This is useful in case we need to manipulate the given value:
has_scope :category do |controller, scope, value|
value != "all" ? scope.by_category(value) : scope
end
has_scope :not_voted_by_me, :type => :boolean do |controller, scope|
scope.not_voted_by(controller.current_user.id)
end
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/has_scope.rb', line 64 def has_scope(*scopes, &block) = scopes. .symbolize_keys! .assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank) if .key?(:using) if .key?(:type) && [:type] != :hash raise "You cannot use :using with another :type different than :hash" else [:type] = :hash end [:using] = Array([:using]) end [:only] = Array([:only]) [:except] = Array([:except]) self.scopes_configuration ||= {} scopes.each do |scope| self.scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block } self.scopes_configuration[scope].merge!() end end |