Skip to content

Instantly share code, notes, and snippets.

@tjmw
Created April 27, 2017 08:37
Show Gist options
  • Save tjmw/266c78d78e6b215ebbf4197b6dc00e3a to your computer and use it in GitHub Desktop.
Save tjmw/266c78d78e6b215ebbf4197b6dc00e3a to your computer and use it in GitHub Desktop.
Quack like an ActiveRecord object
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
@tjmw
Copy link
Author

tjmw commented Nov 27, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment