I've been reading about the repository pattern:
https://blog.spacesnottabs.io/2019/01/30/the-repository-pattern-for-ruby/
and it would be great to have the ability to convert an ActiveRecord object and convert it to an ActiveModel object so that it maintains methods like .attributes
and its validations, but loses all of the methods that would make a call to the database like .save
or .items
.
E.g. Consider this class:
class TodoList < ActiveRecord::Base
has_many :items
validates :name, presence: true
end
I would like to be able to do something like:
> todoList = TodoList.first # first AR record from the database
> todoListModel = todoList.to_ar_model # converts from ActiveRecord to ActiveModel
> todoListModel.class
=> ActiveModel
> todoListModel.save
=> NoMethodError
> todoListModel.items
=> NoMethodError
> todoListModel.valid?
=> true
I know of the to_model method, but it's not what I want: https://api.rubyonrails.org/classes/ActiveModel/Conversion.html#method-i-to_model