I've got a class to encapsulates mime types for communicating with an external system. here is the part of the class that is relevant for the issue.
我有一个类来封装mime类型,用于与外部系统通信。这是与该问题相关的类的一部分。
module Types
class MetaType
def self.validator(&block)
define_singleton_method :is_valid?, &block
end
end
class Float < MetaType
validator { |v| v.is_a? Numeric }
end
class String < MetaType
validator { |v| v.is_a? String }
end
Map = { :Time => Float, :Float => Float , :String => String }
def self.get_type(name)
name = name.intern
raise ArgumentError, "Unknown type #{name}" unless Map.has_key? name
return Map[name]
end
end
Here is the spec
这是规格
describe Types do
context "When calling get_type with 'Float'" do
subject { Types.get_type('Float') }
it "should validate a float" do
expect(subject.is_valid? 3.5).to be_true
end
end
context "When calling get_type with 'String'" do
subject { Types.get_type('String') }
it "should validate a string" do
expect(subject.is_valid? "tmp").to be_true
end
end
end
The output of the spec
规范的输出
Types
When calling get_type with 'Float'
should validate a float
When calling get_type with 'String'
should validate a string (FAILED - 1)
Failures:
1) Types When calling get_type with 'String' should validate a string
Failure/Error: expect(subject.is_valid? "tmp").to be_true
expected: true value
got: false
# ./tmp/type_error.rb:37:in `block (3 levels) in <top (required)>'
The code doesn't pass for the string.
I've tried within the validator function of the metaclass to puts val.is_a? String
but that did prints false?
When i try puts "tmp".is_a? String
i have true which is what I expect...
代码不会传递给字符串。我已经尝试在元类的验证器函数中放入val.is_a?字符串,但确实打印错误?当我尝试把“tmp”.is_a? Stringi是真的,这是我所期待的......
The code works with int, float, bool, hash, but i can't get it to work with String and i do not see any error.
I can't get around for that issue, and any help would be greatly appreciated.
Thank you
代码使用int,float,bool,hash,但我无法使用String,我没有看到任何错误。我无法解决这个问题,任何帮助将不胜感激。谢谢
1 个解决方案
#1
3
I think there's a name * going on here.
我想这里有一个名字冲突。
validator { |v| v.is_a? String }
In this case String
is not what you think it is. It's Types::MetaType::String
. And, of course, value "tmp"
is not of this type. You want to refer to top-level core class String
, like this:
在这种情况下,String不是您认为的那样。它的类型:: MetaType :: String。当然,价值“tmp”不属于这种类型。您想引用*核心类String,如下所示:
class String < MetaType
validator { |v| v.is_a? ::String }
end
#1
3
I think there's a name * going on here.
我想这里有一个名字冲突。
validator { |v| v.is_a? String }
In this case String
is not what you think it is. It's Types::MetaType::String
. And, of course, value "tmp"
is not of this type. You want to refer to top-level core class String
, like this:
在这种情况下,String不是您认为的那样。它的类型:: MetaType :: String。当然,价值“tmp”不属于这种类型。您想引用*核心类String,如下所示:
class String < MetaType
validator { |v| v.is_a? ::String }
end