Last active
October 14, 2015 00:27
-
-
Save joakimk/4279504 to your computer and use it in GitHub Desktop.
An example of "functional core, imperative shell" as far as I understand it. For more info about this concept, see https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell.
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
# Written for this gist, but inspired by production code (I haven't run this code). | |
# Imperative shell | |
class Timer | |
def initialize(record) | |
@record = record | |
end | |
def start | |
save_changes clock.start | |
end | |
def stop | |
save_changes clock.stop | |
end | |
private | |
# Only place where we know where the data is comming from and how it's persisted. | |
def clock | |
Clock.new(@record.total_working_time) | |
end | |
def save_changes(clock) | |
@record.update_attribute(:total_working_time, clock.accumulated_time) | |
end | |
end | |
# Functional core | |
class Timer | |
class Clock | |
def initialize(accumulated_time, started_at = nil) | |
@accumulated_time = accumulated_time | |
@started_at = started_at | |
end | |
attr_reader :accumulated_time | |
def start | |
self.class.new(@accumulated_time, Time.now) | |
end | |
def stop | |
self.class.new(@accumulated_time + (Time.now - @started_at), nil) | |
end | |
end | |
end | |
# Example usage: | |
record = Record.first | |
Timer.new(record).start | |
sleep 10 | |
Timer.new(record).stop | |
Timer.new(record).start | |
sleep 3 | |
Timer.new(record).stop | |
record.total_working_time # 13 |
I think github is working on the gist pages today. I've gotten several flashes of unstyled content (usually happens when you don't handle assets correctly and deploy without downtime).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That intendation went haywire