Method: Mustermann::Expander#cast
- Defined in:
- lib/mustermann/expander.rb
#cast {|key, value| ... } ⇒ Mustermann::Expander #cast(*type_matchers) {|key, value| ... } ⇒ Mustermann::Expander #cast(*cast_objects) ⇒ Mustermann::Expander
Register a block as simple hash transformation that runs before expanding the pattern.
Overloads:
-
#cast {|key, value| ... } ⇒ Mustermann::Expander
Register a block as simple hash transformation that runs before expanding the pattern for all entries.
Examples:
casting everything that implements to_param to param
expander.cast { |o| o.to_param if o.respond_to? :to_param }Yields:
-
every key/value pair
Yield Parameters:
-
key
(Symbol)
—
omitted if block takes less than 2
-
value
(Object)
—
omitted if block takes no arguments
Yield Returns:
-
(Hash{Symbol: Object})
—
will replace key/value pair with returned hash
-
(nil, false)
—
will keep key/value pair in hash
-
(Object)
—
will replace value with returned object
-
-
#cast(*type_matchers) {|key, value| ... } ⇒ Mustermann::Expander
Register a block as simple hash transformation that runs before expanding the pattern for certain entries.
Examples:
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"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"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"casting all ActiveRecord objects to param
expander.cast(ActiveRecord::Base, &:to_param)Parameters:
-
type_matchers
(Array<Symbol, Regexp, #===>)
—
To identify key/value pairs to match against. Regexps and Symbols match against key, everything else matches against value.
Yields:
-
every key/value pair
Yield Parameters:
-
key
(Symbol)
—
omitted if block takes less than 2
-
value
(Object)
—
omitted if block takes no arguments
Yield Returns:
-
(Hash{Symbol: Object})
—
will replace key/value pair with returned hash
-
(nil, false)
—
will keep key/value pair in hash
-
(Object)
—
will replace value with returned object
-
type_matchers
(Array<Symbol, Regexp, #===>)
—
-
#cast(*cast_objects) ⇒ Mustermann::Expander
Parameters:
-
cast_objects
(Array<#cast>)
—
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.
-
cast_objects
(Array<#cast>)
—
Returns:
-
(Mustermann::Expander)
—
the expander
115 116 117 118 |
# File 'lib/mustermann/expander.rb', line 115 def cast(*types, &block) caster.register(*types, &block) self end |