fetch()函数

来源:互联网 发布:sum服务器监控软件 编辑:程序博客网 时间:2024/06/03 21:47

你可能还想在 new 动作中限制允许传入的属性。不过此时无法再根键上调用 require 方法,因为此时根键还不存在:

using fetch you can supply a default and use

the Strong Parameters API from there.

params.fetch(:blog, {}).permit(:title, :author)

fetch(key, *args)Link
Returns a parameter for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise anActionController::ParameterMissing error; if more arguments are given, then that will be returned; if a block is given, then that will be run and its result returned.

params = ActionController::Parameters.new(person: { name: ‘Francesco’ })
params.fetch(:person) # => {“name”=>”Francesco”}
params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
params.fetch(:none, ‘Francesco’) # => “Francesco”
params.fetch(:none) { ‘Francesco’ } # => “Francesco”

fetch(name, options = nil)Link
Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned.

If there is no such data in the cache (a cache miss), then nil will be returned. However, if a block has been passed, that block will be passed the key and executed in the event of a cache miss. The return value of the block will be written to the cache under the given cache key, and that return value will be returned.

cache.write(‘today’, ‘Monday’)
cache.fetch(‘today’) # => “Monday”

cache.fetch(‘city’) # => nil
cache.fetch(‘city’) do
‘Duckburgh’
end
cache.fetch(‘city’) # => “Duckburgh”

fetch(key, *extras)Link
Same as Hash#fetch where the key passed as argument can be either a string or a symbol:

counters = ActiveSupport::HashWithIndifferentAccess.new
counters[:foo] = 1

counters.fetch(‘foo’) # => 1
counters.fetch(:bar, 0) # => 0
counters.fetch(:bar) { |key| 0 } # => 0
counters.fetch(:zoo) # => KeyError: key not found: “zoo”

0 0
原创粉丝点击