I joined Rails team and maintain the codes. Some of the objects are controlled by Gem virtus, but I really don't understand like below code is doing.
I understand the result that the attribute 'latest_book' can collect latest book from Books but why it can be done? What 'books=(books)' is doing? and Why 'super books' is here?
class GetBooks
include Virtus.model
include ActiveModel::Model
attribute :books, Array[Book]
attribute :latest_book, Book
def books=(books)
self.latest_book = books.sort_by { |book| book['createdate'] }.last
super books
end
end
Could you help me?
def books=(books)is defining a method calledbooks=which takes a single argumentbooks. Yes, that's confusing. It should probably bedef books=(value)ordef books=(new_books).And yes, the
=is part of the method name.self.books = valueis really syntax sugar forself.books=(value). Again, the method isbooks=.super booksissuper(books).supercalls the next inherited or included method of the same name; it's callingbooks=created byattribute :books, Array[Book]. This is a "method override" which allows you to add to the behavior of an existing method.When
books=is called it updateslatest_booksand then calls its the original method to set thebooksattribute.