Rails测试一个值是否适合列的类型

时间:2014-07-31 19:10:51

标签: ruby-on-rails ruby ruby-on-rails-4

我需要检查一个值是否适合列的类型,如

  1.is_a? Product.columns_hash["id"].type
"a".is_a? Product.columns_hash["id"].type

Product.columns_hash["id"].type返回:integer而不是Integer类。

1 个答案:

答案 0 :(得分:3)

不确定为什么你需要这样做但这应该有效

1.is_a? Product.columns_hash["id"].type.to_s.classify.constantize
#=> true
"a".is_a? Product.columns_hash["id"].type.to_s.classify.constantize
#=> false

您能否为此指定一个目的,因为它可能更容易通过其他约定来处理。

如果您愿意,可以将其修补到Symbol

class Symbol
  def to_constant
    self.to_s.classify.constantize
  end
end

然后致电

1.is_a? Product.columns_hash["id"].type.to_constant

小心改变基类。技术上也是> 2.0你可以做到这一点

module ColumnChecker
  refine Symbol do 
    def to_constant
      self.to_s.classify.constantize
    end
  end
end 

class YourFilterClass
  using ColumnChecker

  1.is_a? Product.columns_hash["id"].type.to_constant
end

从Ruby 2.0开始,这在技术上是更安全的方法