class FriendlyRoutes::Params::CollectionParams
Created to work with ActiveRecord collection
@attr [Object] collection Instance of ActiveRecord collection @attr [Symbol, String] key_attr
name of attribute for matching
Attributes
collection[RW]
key_attr[RW]
Public Class Methods
new(name, collection, key_attr, optional: true)
click to toggle source
Calls superclass method
FriendlyRoutes::Params::Base::new
# 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 @collection_ids = collection.pluck(:id) end
Public Instance Methods
allowed?(id_or_instance)
click to toggle source
(see Base#allowed?
) @param [Integer|Object] id_or_instance collection instance or it id @return [Boolean]
# File lib/friendly_routes/params/collection_params.rb, line 43 def allowed?(id_or_instance) if id_or_instance.is_a?(ActiveRecord::Base) @collection_ids.include?(id_or_instance.id) else @collection.find_by(id: id_or_instance).present? end end
compose(id_or_instance)
click to toggle source
(see Base#compose
) @param [Integer|Object] id_or_instance collection instance or it id @return [String] member key attr
# File lib/friendly_routes/params/collection_params.rb, line 34 def compose(id_or_instance) instance = id_or_instance instance = @collection.find(id_or_instance) unless instance.is_a?(ActiveRecord::Base) instance[@key_attr] end
constraints()
click to toggle source
# File lib/friendly_routes/params/collection_params.rb, line 20 def constraints Regexp.new @collection.all.map(&@key_attr).compact.map(&:downcase).join('|') end
parse(value)
click to toggle source
(see Base#parse
) @param [String] value value of item key attr @return [Integer, nil] item id or nil if item not found
# File lib/friendly_routes/params/collection_params.rb, line 27 def parse(value) @collection.find_by(@key_attr => value).try(:id) end
Private Instance Methods
check_params()
click to toggle source
# File lib/friendly_routes/params/collection_params.rb, line 53 def check_params if @collection.nil? || @key_attr.nil? raise ArgumentError, 'Collection or key attribute not passed' end end