Lets say I am wrapping an ActiveRecord class for some reason and I have defined a create class method.
class BusCreator
def self.create(attr)
bus = Bus.new(attr)
bus.departure_time = bus.arrival_time - bus.trip_duration
bus.save
bus
end
end
What’s the best way to also define a create! method on BusCreator? Obviously, it should execute the same logic as BusCreator.create but should call save! instead of save.
The best answer depends to some extent on what you want
create!to do. If you want it to do the same thing ascreate, but raise an exception on failure, you could do something like this:Otherwise this is simply a matter of extracting the common elements of the methods into a different method which acts as a helper:
There are lots of style options here, if you really wanted to minimize duplication you could do something like this: