【问题标题】:How to define a class like ActiveSupport::StringInquirer如何定义像 ActiveSupport::StringInquirer 这样的类
【发布时间】:2019-09-13 12:01:06
【问题描述】:

定义一个用字符串初始化的类,例如如果方法 'abc?' 'abc' 将返回 true被称为。任何其他带有尾随“?”的方法将返回假。所有其他没有尾随“?”的方法将提出NoMethodError

【问题讨论】:

    标签: ruby-on-rails ruby activesupport


    【解决方案1】:

    您可以使用method_missing 来回复没有方法的消息。

    method_missing 中,我们可以检查方法名称,如果它以? 结尾,则检查它减去? 是否等于字符串(self)。

    当使用method_missing 时,自定义还定义respond_to?

    class StringInquirer < String
      private
    
      def method_missing(method_name, *args, &block)
        if method_name.to_s.end_with?('?')
          self == method_name.to_s.delete('?')
        else
          super
        end
      end
    
      def respond_to?(method_name, include_private = false)
        method_name.to_s.ends_with('?') || super
      end
    end
    
    name = StringInquirer.new('sally')
    name.sally? # => true
    

    注意这是区分大小写的。

    name.Sally? # => false
    

    【讨论】:

      【解决方案2】:
      class NewStrInq < String
        def initialize(val)
          self.class.send(:define_method, "#{val}?") do
            true
          end
        end
        def method_missing(method)
          method.to_s[-1] == '?' ? false : (raise NoMethodError)
        end
      end
      

      【讨论】:

      • 虽然此代码可能会回答该问题,但它并未就其回答该问题的原因提供指导。请提供有关您正在做什么以及为什么会起作用的信息。
      • 您在类上定义方法,所以所有实例都会定义方法。 NewStrInq.new('abc'); NewStrInq.new('abcc').abc? # =&gt; true。如果你想这样做,你想在单例(又名幽灵)类上定义方法。
      【解决方案3】:
      class StringInquirer < String
        def initialize(str)
          define_singleton_method(str + '?') { true }
          super(str)
        end
      end
      
      name = StringInquirer.new('sally')
      name.sally? # => true
      name.kim? # => NoMethodError
      name.nil? # => false
      

      通过为以问号结尾的所有方法提高NoMethodError,您将失去nil?等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-24
        • 2017-07-06
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 2022-09-24
        • 1970-01-01
        相关资源
        最近更新 更多