⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 06 - checking whether an object has necessary attributes.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -