【问题标题】:Type Checking does not work with Ruby and Liquid类型检查不适用于 Ruby 和 Liquid
【发布时间】:2017-01-15 02:21:51
【问题描述】:

我目前正在使用 Jekyll 制作我的博客。 Jekyll 自定义插件使用 Ruby,而 Jekyll 使用 Liquid。我目前正在通过自定义液体标签获取输入并在那里进行处理。我想检查字符串是否包含整数。所以我有以下代码。我意识到输入不是 String 类型,而是 Jekyll::Token 类型。所以我将输入更改为字符串,但我无法检测字符串是否包含整数。这是我的代码:

module Jekyll
    class TypecheckTag < Liquid::Tag

        def is_int(word)
            return word.count("0-3000") > 0
        end 

        def initialize(tag_name, word, tokens)
            super
            @word = word.to_s

        end

        def render(context)
            if /\A\d+\z/.match(@word)
                @result = 'int'
            else
                @result = 'string'
            end
        end


    end
end

Liquid::Template.register_tag('typecheck', Jekyll::TypecheckTag)

不幸的是,即使我们有一个字符串“16”,它也总是返回'string'。

【问题讨论】:

    标签: ruby jekyll liquid


    【解决方案1】:

    以下代码可以正常工作

    def render(input_str) if /\A[-+]?\d+\z/.match(input_str.strip) @result = 'int' else @result = 'string' end end

    带输出的示例输入

    p render('16') # "int"
    p render('16a') # "string"
    p render('16  ')  # "int"
    p render('asd') #"string"
    p render('') #"string"
    

    我使用strip 因为render('16 ') # "int" 如果你不想忽略它。希望对你有帮助。

    【讨论】:

    • 这不是我想要的,但我通过上下文获取值解决了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多