【问题标题】:ruby test if a subdomain belongs to a domainruby 测试子域是否属于域
【发布时间】:2013-12-06 00:26:04
【问题描述】:

是否可以在 rails 中检查子域是否属于域? 示例:

blog.example.com belongs to example.com ? yes
blog.foo.com belongs to example.com? no
example.com belongs to example.com? yes

我需要深度测试,而不仅仅是类似字符串的测试

【问题讨论】:

    标签: ruby-on-rails ruby dns


    【解决方案1】:

    如果关系只是确定一个子域是否是另一个域的一部分(并且您知道子域和域),那么匹配就是一个简单的比较。

    s1 = 'blog.example.com'
    s2 = 'blog.foo.com'
    s3 = 'example.com'
    s4 = 'blog.counterexample.com'
    
    d = 'example.com'
    
    s1.end_with?(".#{d}") || s1 == d
    # => true
    s2.end_with?(".#{d}") || s2 == d
    # => false
    s3.end_with?(".#{d}") || s3 == d
    # => true
    s4.end_with?(".#{d}") || s4 == d
    # => false
    

    否则,如果您需要将子域分解为域,那么您需要更精细的东西。在这种情况下,我鼓励您使用公共后缀列表,您可以使用Public Suffix gem

    domain = PublicSuffix.parse("google.com")
    # => #
    
    domain.tld
    # => "com"
    domain.sld
    # => "google"
    domain.trd
    # => nil
    
    domain.domain
    # => "google.com"
    domain.subdomain
    # => nil
    

    顺便说一句,Rails 背后的语言是 Ruby,这是一个 Ruby 问题,而不是真正的 Rails 问题。

    【讨论】:

    • PublicSuffix 我认为适合我。我想解析 http 响应找到源域/子域并测试源域/子域是否属于 ruby​​ 代码中的 Prefixed_Domain。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多