Class: FriendlyRoutes::Params::CollectionParams

Inherits:
Base
  • Object
show all
Defined in:
lib/friendly_routes/params/collection_params.rb

Overview

Created to work with ActiveRecord collection

Instance Attribute Summary collapse

Attributes inherited from Base

#name, #type

Instance Method Summary collapse

Methods inherited from Base

#optional?, #required?

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

#collectionObject

Instance of ActiveRecord collection

Returns:

  • (Object)

    the current value of collection



9
10
11
# File 'lib/friendly_routes/params/collection_params.rb', line 9

def collection
  @collection
end

#key_attrSymbol, String

name of attribute for matching

Returns:

  • (Symbol, String)

    the current value of key_attr



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

Parameters:

  • id (Integer)

    id of collection member

Returns:

  • (Boolean)


40
41
42
# File 'lib/friendly_routes/params/collection_params.rb', line 40

def allowed?(id)
  @collection.exists?(id)
end

#compose(id) ⇒ String

Generate request value from params

Inverse of #parse

Parameters:

  • id (Integer)

    id of collection member

Returns:

  • (String)

    member key attr



33
34
35
# File 'lib/friendly_routes/params/collection_params.rb', line 33

def compose(id)
  @collection.find(id)[@key_attr]
end

#constraintsObject



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

Parameters:

  • value (String)

    value of item key attr

Returns:

  • (Integer, nil)

    item id or nil if item not found



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