Class: Scopie::Base
- Inherits:
-
Object
- Object
- Scopie::Base
- Defined in:
- lib/scopie/base.rb
Class Method Summary collapse
-
.has_scope(*scopes, **options) ⇒ Object
Detects params from url and apply as scopes to your classes.
- .scopes_configuration ⇒ Object
Instance Method Summary collapse
- #apply_scopes(target, hash, method = nil) ⇒ Object
- #current_scopes(hash, method = nil) ⇒ Object
- #scopes_configuration ⇒ Object
Class Method Details
.has_scope(*scopes, **options) ⇒ Object
Detects params from url and apply as scopes to your classes.
Options
-
:type
- Coerces the type of the parameter sent. -
:only
- In which actions the scope is applied. -
:except
- In which actions the scope is not applied. -
:as
- The key in the params hash expected to find the scope.Defaults to the scope name.
-
: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.
Method usage
You can also define a method having the same name as a scope. The current scope, value and params are yielded to the block so the user can apply the scope on its own. The method can return new scope or the boolean value. In the latter case will be used not modified scope. This is useful in case we need to manipulate the given value:
has_scope :category
def category(scope, value, _hash)
value != 'all' && scope.by_category(value)
end
has_scope :not_voted_by_me, type: :boolean
def not_voted_by_me(scope, _value, _hash)
scope.not_voted_by(controller.current_user.id) # The controller method is available in the scopie_rails gem
end
50 51 52 53 54 55 56 57 |
# File 'lib/scopie/base.rb', line 50 def self.has_scope(*scopes, **) @scopes_configuration ||= {} () scopes.each do |scope| @scopes_configuration[scope.to_sym] = end end |
.scopes_configuration ⇒ Object
5 6 7 |
# File 'lib/scopie/base.rb', line 5 def self.scopes_configuration instance_variable_get(:@scopes_configuration) || {} end |
Instance Method Details
#apply_scopes(target, hash, method = nil) ⇒ Object
59 60 61 62 63 64 65 |
# File 'lib/scopie/base.rb', line 59 def apply_scopes(target, hash, method = nil) current_scopes_values(hash, method).each do |scope_name, value| target = apply_scope(scope_name, target, value, hash) end target end |
#current_scopes(hash, method = nil) ⇒ Object
67 68 69 70 71 72 |
# File 'lib/scopie/base.rb', line 67 def current_scopes(hash, method = nil) hsh = current_scopes_values(hash, method) hsh.update(hsh) do |_, value| value.coerced end end |
#scopes_configuration ⇒ Object
9 10 11 |
# File 'lib/scopie/base.rb', line 9 def scopes_configuration self.class.scopes_configuration end |