Class: FriendlyRoutes::Params::CollectionParams
- Defined in:
- lib/friendly_routes/params/collection_params.rb
Overview
Created to work with ActiveRecord collection
Instance Attribute Summary collapse
-
#collection ⇒ Object
Instance of ActiveRecord collection.
-
#key_attr ⇒ Symbol, String
name of attribute for matching.
Attributes inherited from Base
Instance Method Summary collapse
-
#allowed?(id) ⇒ Boolean
Check if value can be composed.
-
#compose(id) ⇒ String
Generate request value from params.
- #constraints ⇒ Object
-
#initialize(name, collection, key_attr, optional: true) ⇒ CollectionParams
constructor
A new instance of CollectionParams.
-
#parse(value) ⇒ Integer?
Parse values from request.
Methods inherited from Base
Constructor Details
#initialize(name, collection, key_attr, optional: true) ⇒ CollectionParams
Returns a new instance of CollectionParams.
12 13 14 15 16 17 |
# File 'lib/friendly_routes/params/collection_params.rb', line 12 def initialize(name, collection, key_attr, optional: true) super(:collection, name, optional) @collection = collection @key_attr = key_attr check_params end |
Instance Attribute Details
#collection ⇒ Object
Instance of ActiveRecord collection
9 10 11 |
# File 'lib/friendly_routes/params/collection_params.rb', line 9 def collection @collection end |
#key_attr ⇒ Symbol, String
name of attribute for matching
9 10 11 |
# File 'lib/friendly_routes/params/collection_params.rb', line 9 def key_attr @key_attr end |
Instance Method Details
#allowed?(id) ⇒ Boolean
Check if value can be composed
40 41 42 |
# File 'lib/friendly_routes/params/collection_params.rb', line 40 def allowed?(id) @collection.find_by(id: id).present? end |
#compose(id) ⇒ String
Generate request value from params
Inverse of #parse
33 34 35 |
# File 'lib/friendly_routes/params/collection_params.rb', line 33 def compose(id) @collection.find(id)[@key_attr] end |
#constraints ⇒ Object
19 20 21 |
# File 'lib/friendly_routes/params/collection_params.rb', line 19 def constraints Regexp.new @collection.all.map(&@key_attr).compact.map(&:downcase).join('|') end |
#parse(value) ⇒ Integer?
Parse values from request
Inverse of #compose
26 27 28 |
# File 'lib/friendly_routes/params/collection_params.rb', line 26 def parse(value) @collection.find_by(@key_attr => value).try(:id) end |