Ruby on rails Rails或Ruby中的空对象模式
如何优雅地处理空对象模式 我知道这个代码是有效的,但是有没有其他方法,如果没有Ruby on rails Rails或Ruby中的空对象模式,ruby-on-rails,ruby,Ruby On Rails,Ruby,如何优雅地处理空对象模式 我知道这个代码是有效的,但是有没有其他方法,如果没有Profileobject。。。它仍然会读取某种方法,如 profile\u对象。方法\u名称 我想避免使用try module User class Profile NoRecommendedProfile = Profile.new def initialize(attributes={}) set_attributes(attributes) end clas
Profile
object。。。它仍然会读取某种方法,如
profile\u对象。方法\u名称
我想避免使用try
module User
class Profile
NoRecommendedProfile = Profile.new
def initialize(attributes={})
set_attributes(attributes)
end
class << self
def from_user(user)
recommended_profile = ProfileService.new(job).call || NoRecommendedProfile
save_profile(user, recommended_profile)
end
end
end
模块用户
班级简介
NoRecommendedProfile=Profile.new
def初始化(属性={})
设置属性(属性)
结束
班级你看过宝石了吗?这是Ruby中空对象的一个非常完整的实现。这很容易自己完成。如果要生成空字符串,可以执行以下操作:
null = Class.new
# => #<Class:0x007ff15d8fc108>
String.new.methods.each do |method|
null.define_singleton_method method do |*|; end
end
# => [:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, :insert, :length, :size, :bytesize, :empty?, ... ]
null.bytesize
# => nil
谢谢,我去看看。
null.upcase.length