Created
April 27, 2017 08:37
-
-
Save tjmw/266c78d78e6b215ebbf4197b6dc00e3a to your computer and use it in GitHub Desktop.
Quack like an ActiveRecord object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FakeRecord | |
# ActiveModel plumbing to make `form_for` work | |
extend ActiveModel::Naming | |
include ActiveModel::Conversion | |
include ActiveModel::Validations | |
attr_accessor :foo, :bar | |
validates :foo, presence: true | |
def initialize(attributes = {}) | |
self.foo = attributes[:foo] | |
end | |
def save | |
return false unless valid? | |
# Do something... | |
true | |
rescue MyError | |
errors.add(:foo, "Something went wrong") | |
false | |
end | |
def persisted? | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This can be made simpler by including
ActiveModel::Model
which will define the constructor and#persisted?
for us. https://github.com/rails/rails/blob/master/activemodel/lib/active_model/model.rb#L59-L97