ruby-on-rails - 基本红宝石。为什么这个方法返回零?
问题描述
你好!
我期待#<PrettyThing:0x0055a958175348 @success="anything here">
但我却得到'anything here'
了。知道为什么吗?
class Thing
attr_accessor :success
def execute
self.success = execute!
rescue
self.success = false
ensure
self
end
end
class PrettyThing < Thing
def execute!
'anything here'
end
end
p PrettyThing.new.execute # => 'anything here'
解决方案
尝试:
class Thing
attr_accessor :success
def execute
self.success = execute!
self
rescue
self.success = false
end
end
class PrettyThing < Thing
def execute!
'anything here'
end
end
p PrettyThing.new.execute # => <PrettyThing:0x0000000379ea48 @success="anything here">
您编写它的方式execute
是返回self.success = execute!
. 通过添加self
,您返回 的实例PrettyThing
。
如果您想链接方法,这很方便,例如:
class Thing
attr_accessor :success
def execute
self.success = execute!
self
rescue
self.success = false
end
def foo
puts 'foo'
end
end
class PrettyThing < Thing
def execute!
'anything here'
end
end
p PrettyThing.new.execute.foo # => foo
鉴于您的评论,我想我可能会做更多类似的事情:
class Thing
attr_accessor :success
alias success? success
def foo
puts 'foo'
end
end
class PrettyThing < Thing
def execute
@success = everything_worked
self
end
private
def everything_worked
# your logic goes here
# return true if all is good
# return false or nil if all is not good
true
end
end
pretty_thing = PrettyThing.new.execute
p pretty_thing.success? # => true
如果everything_worked
返回false
or nil
,那么pretty_thing.success?
也将返回false
or nil
。
推荐阅读
- apache-kafka - 通过代码 / api 重置 Kafka 流应用程序
- python - 如何在 Python 中处理来自 xlsx 文件的数据
- mpi - 具有不同操作系统的 MPI 集群
- python - 一次性删除python程序中的所有打印语句
- python - 访问主小部件内的小部件以进行顺序网格化
- typescript - 在 VSCode 中开发扩展时如何从 QuickFix 传递错误详细信息和行号?
- python - 我可以通过 python 使用 Apple 的 SKCloudServiceController 吗?
- python-3.x - 是否可以解决相对进口的问题?
- java - Keycloak 和第三方库中的类加载器出错
- python - 在列表python中合并字典