gpt4 book ai didi

ruby-on-rails - 对 Ruby on Rails routes.rb 语法感到困惑

转载 作者:数据小太阳 更新时间:2023-10-29 08:25:59 26 4
gpt4 key购买 nike

假设我的 routes.rb 文件中有以下代码。

  get '/dashboard', to: 'dashboard#index', :as => 'dashboard'

我知道发生了什么(一个公共(public) url 被映射到一个特定的 Controller / View 文件,它将处理并返回请求)。那不是我感到困惑的地方。

作为 Ruby 初学者,我对这是什么 Ruby 代码约定感到困惑。它看起来不像是声明变量或调用方法的正确方法?到底发生了什么,这是调用方法的某种简写形式吗?

get("/dashboard", "dashboard#index", "dashboard")

最佳答案

这是允许将选项 传递给方法的常用方法。像下面这样:

def do_something(subject, options = {})
subject.perform_something
subject.perform_caching if options[:cache]
subject.send_report unless options[:skip_reporting]
# etc.
end

所以你可以调用:

something(some_object)
something(some_object, cache: true)
something(some_object, skip_reporting: true, cache: true)

您甚至可以设置默认值,如下所示:

def do_something_else(subject, options = {})
options = { cache: true, skip_reporting: false }.merge(options)
subject.perform_something
subject.perform_caching if options[:cache]
subject.send_report unless options[:skip_reporting]
end

因此默认情况下,如果没有cache 选项,那么它将是true

关于ruby-on-rails - 对 Ruby on Rails routes.rb 语法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47315898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com