Tính đến Rails 3.1 cú pháp được đơn giản hóa một chút bằng cách ActiveSupport: : Lo ngại:
Bây giờ bạn có thể làm
require 'active_support/concern'
module M
extend ActiveSupport::Concern
included do
scope :disabled, where(:disabled => true)
end
module ClassMethods
...
end
end
ActiveSupport :: Lo ngại cũng càn quét trong sự phụ thuộc của các mô-đun bao gồm, here is the documentation
[cập nhật, giải quyết aceofbassgreg của bình luận]
Các Rails 3.1 và sau ActiveSupport :: Lo ngại cho phép một bao gồm các phương pháp dụ mô-đun để được bao gồm trực tiếp , do đó không cần thiết phải tạo mô-đun InstanceMethods bên trong mô-đun được bao gồm. Ngoài ra nó không còn cần thiết trong Rails 3.1 và sau đó để bao gồm M :: InstanceMethods và mở rộng M :: ClassMethods. Vì vậy, chúng ta có thể có mã đơn giản như thế này:
require 'active_support/concern'
module M
extend ActiveSupport::Concern
# foo will be an instance method when M is "include"'d in another class
def foo
"bar"
end
module ClassMethods
# the baz method will be included as a class method on any class that "include"s M
def baz
"qux"
end
end
end
class Test
# this is all that is required! It's a beautiful thing!
include M
end
Test.new.foo # ->"bar"
Test.baz # -> "qux"
Nguồn
2013-01-07 23:13:50
Xác thực và mối quan hệ có thể được xác định theo cách này không? – CantGetANick
Không thể nói 100%, nhưng tôi không thể nghĩ tại sao không. –
Yap, Và nó hoạt động. Cảm ơn ví dụ. – CantGetANick