我正在开发一个类似DataMapper的小型ODM项目,我正在尝试使用该ActiveModel::Validations组件.但是,我在编写测试时遇到了问题 - 我使用匿名类来构造我的测试模式,但是当运行验证器时,ActiveModel::Name类会抛出错误:
Class name cannot be blank. You need to supply a name argument when anonymous class given
这是一个重现的简单代码示例:
require 'active_model'
book_class = Class.new do
include ActiveModel::Validations
validates_presence_of :title
def title; ""; end # This will fail validation
end
book_class.new.valid? # => throws error
Run Code Online (Sandbox Code Playgroud)
只有在验证程序失败时才会引发异常 - 我猜测在尝试构造验证错误消息时会发生问题.所以我的问题是:
我正在编写一个类方法来创建另一个类方法.似乎是围绕着如何一些陌生感class_eval和instance_eval类方法的范围内进行操作.为了显示:
class Test1
def self.add_foo
self.class_eval do # does what it says on the tin
define_method :foo do
puts "bar"
end
end
end
end
Test1.add_foo # creates new instance method, like I'd expect
Test1.new.foo # => "bar"
class Test2
def self.add_foo
self.instance_eval do # seems to do the same as "class_eval"
define_method :foo do
puts "bar"
end
end
end
end
Test2.add_foo # what is happening here?!
Test2.foo # => NoMethodError
Test2.new.foo # => "bar"
class Test3 …Run Code Online (Sandbox Code Playgroud)