06 - checking whether an object has necessary attributes.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 45 行

RB
45
字号
class Object  def must_have_instance_variables(*args)    vars = instance_variables.inject({}) { |h,var| h[var] = true; h }    args.each do |var|      unless vars[var]        raise ArgumentError, %{Instance variable "@#{var} not defined"}       end    end  endend#---module LightEmitting  def LightEmitting_setup    must_have_instance_variables :light_color, :light_intensity    @on = false  end  # Methods that use @light_color and @light_intensity follow...end#---class Request  def initialize    gather_parameters # This is a virtual method defined by subclasses    must_have_instance_variables :action, :user, :authentication  end  # Methods that use @action, @user, and @authentication follow...end#---class Object  def must_support(*args)    args.each do |method|       unless respond_to? method        raise ArgumentError, %{Must support "#{method}"}      end    end  endendobj = "a string"obj.must_support :to_s, :size, "+".to_symobj.must_support "+".to_sym, "-".to_sym# ArgumentError: Must support "-"#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?