Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails或Ruby中的空对象模式_Ruby On Rails_Ruby - Fatal编程技术网

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