Created
March 3, 2014 17:27
-
-
Save cheeyeo/9330018 to your computer and use it in GitHub Desktop.
Example of ghost loading pattern
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
class Episode | |
def self.lazy_accessor(*names) | |
names.each do |name| | |
attr_writer name | |
define_method(name) do | |
load | |
instance_variable_get("@#{name}") | |
end | |
end | |
end | |
attr_accessor :video, | |
:id, | |
:number, | |
:name, | |
:video_url, | |
:load_state, | |
:data_source | |
# below is a macro which uses meta programming | |
lazy_accessor :description, | |
:synopsis, | |
:publish_time | |
def initialize(attributes={}) | |
attributes.each do |key, value| | |
public_send("#{key}=", value) | |
end | |
@load_state = :ghost | |
end | |
def to_s | |
inspect | |
end | |
def ==(other) | |
other.is_a?(Episode) && other.id == id | |
end | |
def published?(time_now=Time.now) | |
publish_time <= time_now | |
end | |
def load | |
return if load_state == :loaded | |
data_source.load(self) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment