如何在超类中创建类似属性的 attr setter 并填充到子类中?

发布于 2024-11-07 11:17:57 字数 942 浏览 0 评论 0原文

我在 Rails 中有一个继承自 ActiveRecord::Base 的父类。我正在尝试在该类中实现自由文本搜索以及其他查询,以便从它继承的所有类都可以将它与自己的字段一起使用,这些字段根据模型而变化:

#
# in base class
#
class GenericBase < ActiveRecord::Base

  named_scope :freetext, lambda { |query|
    if query.present?
      { :conditions => [ self.freetext_fields.join(' LIKE ? or '), 
                         ( ["%#{query}%"]*self.freetext_fields.size ) ].flatten }
    else
      {}
    end
  }

end

#
# in inheriting class
#
class Person < GenericBase
  set_freetext_fields %w(firstname lastname username email)    
end

# or 
class Address < GenericBase
  set_freetext_fields %w(street city)    
end

#
# in controller
#
def search
  @people = Person.freetext(params[:query])
end

在上面的示例中,我如何实现set_freetext_fields setter 是否可以在从 GenericBase 继承的所有模型中轻松使用?这应该与 Rails 中提供的 set_table_name 非常相似。

我想在父模块或 mixin 模块中实现它,以便继承类的 API 尽可能干净。

I have a parent class in rails that inherits from ActiveRecord::Base. I'm trying to implement a freetext search, plus other queries, in that class such that all classes that inherit from it can use it with their own fields, which change based on the model:

#
# in base class
#
class GenericBase < ActiveRecord::Base

  named_scope :freetext, lambda { |query|
    if query.present?
      { :conditions => [ self.freetext_fields.join(' LIKE ? or '), 
                         ( ["%#{query}%"]*self.freetext_fields.size ) ].flatten }
    else
      {}
    end
  }

end

#
# in inheriting class
#
class Person < GenericBase
  set_freetext_fields %w(firstname lastname username email)    
end

# or 
class Address < GenericBase
  set_freetext_fields %w(street city)    
end

#
# in controller
#
def search
  @people = Person.freetext(params[:query])
end

In the example above, how do I implement the set_freetext_fields setter to be easily used in all models that inherit from GenericBase? This should be something very similar to set_table_name available in Rails.

I want to implement it in the parent or a mixin module such that the API for inheriting classes will be as clean as possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

微暖i 2024-11-14 11:17:57

您可以实现如下所示的内容:

module A
    def set_freetext_fields=(*args)
     @a = args
    end

    def some_meth
     @a 
    end
end

class C
 extend A   

 C.set_freetext_fields = %w(firstname lastname username email)
end

puts C.set_freetext_fields

其中CGenericBase

You can implement something like this:

module A
    def set_freetext_fields=(*args)
     @a = args
    end

    def some_meth
     @a 
    end
end

class C
 extend A   

 C.set_freetext_fields = %w(firstname lastname username email)
end

puts C.set_freetext_fields

Where C is GenericBase class

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文