首页 > 解决方案 > 基本红宝石。为什么这个方法返回零?

问题描述

你好!

我期待#<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'

标签: ruby-on-railsruby

解决方案


尝试:

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返回falseor nil,那么pretty_thing.success?也将返回falseor nil


推荐阅读