【发布时间】:2015-10-11 08:13:31
【问题描述】:
对于 Rails 应用程序:是否存在命名映射到模型对象的空对象的命名约定?
例子:
#app/models/blog.rb
class Blog < ActiveRecord::Base
end
#app/models/null_blog.rb
class NullBlog # Null Objects are POROs, correct?
def title
"No title"
end
end
# so to implement it I can do this:
blogs = ids.map{|id| Blog.find_by(id: id) || NullBlog.new}
# which allows me to do this and it works, even if some of those ids did not find a blog
blogs.each{|blog| blog.title}
NullBlog 是常规的吗?
this article by Avdi Grimm 和 Sandi Metz 的 Nothing is Something 演示都没有提到任何空对象命名约定。
【问题讨论】:
-
顺便说一句,此块
{ |id| Blog.find(id) || NullBlog.new }将不起作用,因为如果未找到记录,带有id的find会引发异常。您可能想改用{ |id| Blog.find_by(id: id) || NullBlog.new }。 -
@spickermann 不错!我会更新代码。
标签: ruby-on-rails ruby null-object-pattern