Ruby-on-rails 如果字符串为空则返回一些默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4817266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:13:04  来源:igfitidea点击:

If string is empty then return some default value

ruby-on-railsruby

提问by fl00r

Often I need to check if some value is blank and write that "No data present" like that:

通常我需要检查某个值是否为空并像这样写下“不存在数据”:

@user.address.blank? ? "We don't know user's address" : @user.address

And when we have got about 20-30 fields that we need to process this way it becomes ugly.

当我们有大约 20-30 个字段需要以这种方式处理时,它就会变得丑陋。

What I've made is extended String class with ormethod

我所做的是使用or方法扩展 String 类

class String
  def or(what)
    self.strip.blank? ? what : self
  end
end

@user.address.or("We don't know user's address")

Now it is looking better. But it is still raw and rough

现在看起来好多了。但它仍然是原始的和粗糙的

How it would be better to solve my problem. Maybe it would be better to extend ActiveSupport classor use helper method or mixins or anything else. What ruby idealogy, your experience and best practices can tell to me.

如何更好地解决我的问题。也许最好扩展ActiveSupport class或使用辅助方法或 mixin 或其他任何东西。什么 ruby​​ 理念、您的经验和最佳实践可以告诉我。

回答by David Phillips

ActiveSupport adds a presencemethod to all objects that returns its receiver if present?(the opposite of blank?), and nilotherwise.

ActiveSupportpresence向所有对象添加一个方法,该方法返回其接收者 if present?(与blank?),nil否则返回。

Example:

例子:

host = config[:host].presence || 'localhost'

回答by Matt Briggs

Phrogz sort of gave me the idea in PofMagicfingers comment, but what about overriding | instead?

Phrogz 在 PofMagicfingers 评论中给了我这个想法,但是如何覆盖?反而?

class String
  def |(what)
    self.strip.blank? ? what : self
  end
end

@user.address | "We don't know user's address"

回答by Tonttu

Your ormethod might have some unwanted side-effects, since the alternative (default) value is always evaluated, even if the string is not empty.

您的or方法可能有一些不需要的副作用,因为即使字符串不为空,也会始终评估替代(默认)值。

For example

例如

@user.address.or User.make_a_long_and_painful_SQL_query_here

would make extra work even if address is not empty. Maybe you could update that a bit (sorry about confusing one-liner, trying to keep it short):

即使地址不为空,也会做额外的工作。也许你可以更新一下(抱歉混淆了单行,尽量保持简短):

class String
  def or what = ""
    self.strip.empty? ? block_given? ? yield : what : self
  end
end

@user.address.or "We don't know user's address"
@user.address.or { User.make_a_long_and_painful_SQL_query_here }

回答by Phrogz

Since you're doing this in Ruby on Rails, it looks like you're working with a model. Ifyou wanted a reasonable default value everywherein your app, you could (for example) override the addressmethod for your Usermodel.

由于您是在 Ruby on Rails 中执行此操作,因此看起来您正在使用模型。如果您希望应用程序中的任何地方都有一个合理的默认值,您可以(例如)覆盖模型的address方法User

I don't know ActiveRecord well enough to provide good code for this; in Sequel it would be something like:

我不太了解 ActiveRecord,无法为此提供好的代码;在续集中,它会是这样的:

class User < Sequel::Model
  def address        
    if (val=self[:address]).empty?
      "We don't know user's address"
    else
      val
    end
  end
end

...but for the example above this seems like you'd be mixing view logic into your model, which is not a good idea.

...但对于上面的示例,这似乎是将视图逻辑混合到模型中,这不是一个好主意。

回答by maxl0rd

It is probably better to extend ActiveRecord or individual models instead of String.

扩展 ActiveRecord 或单个模型而不是 String 可能更好。

In your view, you might prefer a more explicit pattern like

在您看来,您可能更喜欢更明确的模式,例如

@user.attr_or_default :address, "We don't know the user's address"

回答by Lucio

Ruby:

红宝石:

unless my_str.empty? then my_str else 'default' end

RoR:

回报率:

unless my_str.blank? then my_str else 'default' end