MooseX::Types 强制转换和 $self
无论如何,有没有办法让 $self
进入 MooseX::Types
强制转换?我在对象中有其他数据,我想用它们来将 String
强制转换为 Object
。或者,是否有类似 Class::MOP
的 initializer
的东西可以允许我执行此操作 - 它必须在 之前 触发类型检查。
请求的伪代码:
with 'DBHandle';
has 'database' => ( isa => 'Str', is => 'ro', default => 'Db' );
has 'schema' => ( isa => 'Str', is => 'ro', default => 'schema' );
has 'table' => ( isa => 'Str', is => 'ro', default => 'column );
has 'columns' => ( isa => DBCols, is => 'ro', default => sub {[qw/foo bar baz/]} );
在这里,我希望“列”强制转换为 DBCols
—— DBCols(对象)的 ArrayRef —— 需要使用 catalog
、在类中找到 schema
和 col
属性,并使用 DBHandle
提供的 dbh/singleton。
为了减少这种虚假性,实际情况只是稍微复杂一些。我能够使用 around
完成上述任务,现在我想做的是创建一个允许此语法的属性特征:
has 'column_id' => (
isa => Int
, is => 'ro'
, traits => ['DBKey']
, default => 5
, column => 'foo'
);
其中属性特征 column
由 < 提供code>DBKey,以与上述列
相同的方式强制转换为DBCol
:这需要能够访问类数据库
>、schema
、table
以及 dbh
的单例。
Is there anyway to get $self
into a MooseX::Types
coercion? I have other data in the object that I want to use to seed my coercion from a String
to an Object
. Alternatively, is there anything like Class::MOP
's initializer
that will permit me to do this -- it would have to fire before the type checks.
Requested pseudo code:
with 'DBHandle';
has 'database' => ( isa => 'Str', is => 'ro', default => 'Db' );
has 'schema' => ( isa => 'Str', is => 'ro', default => 'schema' );
has 'table' => ( isa => 'Str', is => 'ro', default => 'column );
has 'columns' => ( isa => DBCols, is => 'ro', default => sub {[qw/foo bar baz/]} );
Here, I want "columns" to coerce to a DBCols
-- an ArrayRef of DBCol's (objects) -- requiring the use of catalog
, schema
, and col
attributes found in the class, and with a dbh/singleton provided by DBHandle
.
To make this less-pseudo, the actually situation is only slightly more complex. I was able to accomplish the above with around
, now what I want I to do is create an attribute trait that would permit this syntax:
has 'column_id' => (
isa => Int
, is => 'ro'
, traits => ['DBKey']
, default => 5
, column => 'foo'
);
Where the attribute trait column
provided by DBKey
, coerces to DBCol
the same way that the above columns
would: this would require the ability to access the classes database
, schema
, table
, and again the singleton for the dbh
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这很好,但是强制转换确实被设计为全局的,而且还没有人编写过“上下文相关的强制转换”,因为没有人真正确定如何编写。 有效的列名,定义为这个对象的
columns
HashRef中的一个条目”就很有用了。)(实际上,s/coercions/typeconstraints/——仅仅说“这个Str必须是一个 通常使用
around
和/或BUILD
和BUILDARGS
的某种组合来解决这个问题。No. It'd be nice, but coercions are really designed to be global, and no one has written a "context-sensitive coercion" yet, because no one's really sure how to. (Actually, s/coercions/type constraints/ -- it'd be useful just to say "this Str must be a valid column name, defined as an entry in this object's
columns
HashRef".)People usually solve this problem with
around
and/or some combination ofBUILD
andBUILDARGS
.