如何解决如何在Ruby中动态创建类方法?
在Rails中,我们可以调用“ Person.find_by_attribute”,其中“属性”由“ Person”迁移中的属性动态放置。我想在没有导轨的Person类中复制此逻辑,并为属性调用“ find_by_attribute”。我到目前为止所拥有的:
int max = 0;
foreach(var l in myList)
{
if(l.Count > max)
max = l.Count;
}
但是,这样定义find_by可能会使该类迅速膨胀。如何实现动态清晰度设置?
解决方法
我有理由确定这不是Rails
的工作方式,但这是一些可能对您有帮助的实施方式:
您所定义的是一个Singleton
类,在进行该设计之前,您应该了解如何在此类中动态定义属性记录。这可能是一个不错的选择,但是您应该为该类提供访问点,以搜索在其他地方定义的记录。无论如何,以下内容将帮助您入门:
class Person
@@attributes = { id: Integer,nice_attribute: String }
# getter method
def self.attribute_types
@@attributes
end
attribute_types.keys.each do |attr|
define_singleton_method :"find_by_#{attr}" do |value|
# logic
end
end
end
然后您将可以呼叫Person.find_by_id
或Person.find_by_nice_attribute
实现时,最好有一个PersonRecord
模块来从数据库中收集记录,而Person
类可能是这样的实例:
class Person
def initialise(opts ={})
define_find_by_methods
end
def attribute_keys
# stub method,but should be collecting this information dynamically
[ :id,:nice_attribute ]
end
def define_find_by_methods
attribute_keys.each do |attr|
# no longer using define_singleton_method here and define_method is a class method you will have to send it to self.class
self.class.send(:define_method,:"find_by_#{attr}") do |val|
# logic
end
end
end
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。