Created
October 13, 2014 20:58
-
-
Save olistik/754208b9e104aa093054 to your computer and use it in GitHub Desktop.
Callbacks or Object Form?
This file contains hidden or 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
# Given: | |
require 'active_record' | |
require 'sqlite3' | |
ActiveRecord::Base.establish_connection( | |
adapter: 'sqlite3', | |
database: 'mydbfile.sqlite' | |
) | |
ActiveRecord::Schema.define do | |
create_table 'users', force: true do |t| | |
t.string 'name' | |
end | |
end | |
class Geocoder | |
def initialize(user) | |
# stuff | |
end | |
def process | |
# stuff | |
end | |
end | |
# option A: Callbacks in 14 lines of code | |
ActiveRecord::Base.class_eval do | |
def without_halting_save | |
yield | |
true | |
end | |
end | |
class User < ActiveRecord::Base | |
before_save :geocode | |
def geocode | |
without_halting_save { Geocoder.new(self).process } | |
end | |
end | |
user = User.new(name: 'foo') | |
user.save | |
# option B: Object Form in 15 lines of code | |
class User < ActiveRecord::Base | |
end | |
class UserForm | |
def initialize(user:) | |
@user = user | |
end | |
def save | |
geocoder = Geocoder.new(@user) | |
geocoder.process | |
@user.save | |
end | |
end | |
user = User.new(name: 'foo') | |
form = UserForm.new(user: user) | |
form.save |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment