View on GitHub
Register a block as simple hash transformation that runs before expanding the pattern.
@return [Mustermann::Expander] the expander
@overload cast
Register a block as simple hash transformation that runs before expanding the pattern for all entries.
@example casting everything that implements to_param to param
expander.cast { |o| o.to_param if o.respond_to? :to_param }
@yield every key/value pair
@yieldparam key [Symbol] omitted if block takes less than 2
@yieldparam value [Object] omitted if block takes no arguments
@yieldreturn [Hash{Symbol: Object}] will replace key/value pair with returned hash
@yieldreturn [nil, false] will keep key/value pair in hash
@yieldreturn [Object] will replace value with returned object
@overload cast(*type_matchers)
Register a block as simple hash transformation that runs before expanding the pattern for certain entries.
@example convert user to user_id
expander = Mustermann::Expander.new('/users/:user_id')
expand.cast(:user) { |user| { user_id: user.id } }
expand.expand(user: User.current) # => "/users/42"
@example convert user, page, image to user_id, page_id, image_id
expander = Mustermann::Expander.new('/users/:user_id', '/pages/:page_id', '/:image_id.jpg')
expand.cast(:user, :page, :image) { |key, value| { "#{key}_id".to_sym => value.id } }
expand.expand(user: User.current) # => "/users/42"
@example casting to multiple key/value pairs
expander = Mustermann::Expander.new('/users/:user_id/:image_id.:format')
expander.cast(:image) { |i| { user_id: i.owner.id, image_id: i.id, format: i.format } }
expander.expander(image: User.current.avatar) # => "/users/42/avatar.jpg"
@example casting all ActiveRecord objects to param
expander.cast(ActiveRecord::Base, &:to_param)
@param [Array<Symbol, Regexp, #===>] type_matchers
To identify key/value pairs to match against.
Regexps and Symbols match against key, everything else matches against value.
@yield every key/value pair
@yieldparam key [Symbol] omitted if block takes less than 2
@yieldparam value [Object] omitted if block takes no arguments
@yieldreturn [Hash{Symbol: Object}] will replace key/value pair with returned hash
@yieldreturn [nil, false] will keep key/value pair in hash
@yieldreturn [Object] will replace value with returned object
@overload cast(*cast_objects)
@param [Array<#cast>] cast_objects
Before expanding, will call #cast on these objects for each key/value pair.
Return value will be treated same as block return values described above.