为什么回调在Ruby on Rails中使用符号 [英] Why do callbacks use symbols in Ruby on Rails

查看:73
本文介绍了为什么回调在Ruby on Rails中使用符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解何时以及何时不使用Rails中的符号。我知道没有很多方法,符号与字符串并不太相似。我还理解符号是好的键,因为同名的符号在内存中占据一个地址。



我很难理解的是,为什么Rails决定在某些情况下使用符号。如果我有回调

  before_action:ask_stack_overflow_question 

def ask_stack_overflow_question
表示为什么只使用符号?
end

我不太明白为什么将此方法视为符号?为什么我需要保持方法不变?



我在文档中找不到任何答案。



谢谢

解决方案

这并不像看起来那么棘手。



调用 before_action 时,您不希望立即执行该方法,但是必须描述要以某种方式执行的操作。此处使用符号表示要调用的方法的名称



因此,如果将其捕获为 name ,然后在代码中的某个位置,将其在适当的时间转换为 send(name)



两者之间有很大差异。即时版本为:

  before_action method_name 

具有立即执行 method_name 的效果,因为Ruby将被迫运行 method_name 找出返回的内容,然后将其作为参数传递给 before_action



约定是:

  before_action:方法名

这只是对 before_action 的礼貌请求,传入一个符号作为参数。您会把它留给 before_action 来处理,但是它认为合适,因此它可能会或可能不会在将来执行该方法,具体取决于情况。 / p>

这是Ruby中非常很少例外的工作方式。我能想到的唯一一个当立即被指定而不是作为代表符号时不会立即执行方法的是古怪的 alias 构造。


I am struggling to understand when and when not to use symbols in Rails. I understand that symbols are not too dissimilar from a string without many of the methods. I also understand the symbols make good keys as symbols of the same name occupy one address in memory.

What I struggle to understand is why Rails decides to use symbols in some cases. If I had the callback

before_action :ask_stack_overflow_question

def ask_stack_overflow_question
  puts "why did I just use a symbol?"
end

I don't quite understand why the treat the method as a symbol? Why would I need to keep a method constant?

I can't find any answer to this in the documentation.

Thank you

解决方案

This isn't as tricky as it seems.

When calling before_action you do not want the method to be executed immediately, but you have to describe that action you want to have performed somehow. A symbol is used here to represent the name of the method to call.

So if this is captured as name, then later, somewhere in the code, this is converted into a send(name) at the appropriate time.

There's a big difference between these two. The immediate version is:

before_action method_name

Which has the effect of executing method_name immediately, as Ruby will be compelled to run method_name to find out what it returns, then pass that through to before_action as an argument.

The deferred convention is:

before_action :method_name

Which is simply a polite request to before_action, passing in a symbol as an argument. You're leaving it up to before_action to deal with this however it sees fit, so it may or may not execute that method in the future, it depends on the situation.

This is how it works within Ruby with very few exceptions. The only one I can think of that doesn't immediately execute a method when it's specified immediately instead of as a representative symbol is the quirky alias construct.

这篇关于为什么回调在Ruby on Rails中使用符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆