Created
December 11, 2013 01:43
-
-
Save swifthand/7903788 to your computer and use it in GitHub Desktop.
Polaroid Preview/Example.
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 Emails::OrganizerFundraisingTips | |
include Polaroid.new(:rsvp_deadline, :meal_page_url) | |
attr_reader :event | |
def initialize(event) | |
@event = event | |
end | |
def rsvp_deadline | |
event.rsvp_confirmation_deadline.to_s :written_date | |
end | |
def meal_page_url | |
event.public_url | |
end | |
end |
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 Polaroid < Module | |
def initialize(*messages) | |
@messages = messages | |
@polaroid_struct_class = ImmutableStruct.new(*messages) | |
define_capture_method | |
freeze | |
end | |
def included(base) | |
base.const_set(:Snapshot, @polaroid_struct_class) | |
base.extend(ClassMethods) | |
end | |
private ####################################################################### | |
def define_capture_method | |
messages = @messages | |
define_method(:take_snapshot) do || | |
self.class::Snapshot.new(*(messages.map { |msg| self.send(msg) })).to_h | |
end | |
end | |
module ClassMethods | |
def build_from_snapshot(snapshot_hash) | |
self::Snapshot.new(snapshot_hash) | |
end | |
end | |
end |
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
email_viewmodel = Emails::OrganizerFundraisingTips.new(some_event) | |
# Capture the object' publicly-observable snapshot | |
snapshot = email_viewmodel.take_snapshot | |
# => {:rsvp_deadline=>"June 25, 2013", :meal_page_url=>"http://www.groupraise.com/events/1159"} | |
# Do a lot of stuff. | |
# Maybe somewhere far away, maybe in a background job: | |
viewmodel_snapshot = Emails::OrganizerFundraisingTips.build_from_snapshot(snapshot) | |
# => #<struct Emails::OrganizerFundraisingTips::Snapshot rsvp_deadline="June 25, 2013", meal_page_url="http://www.groupraise.com/events/1159"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment