- Softwrap mode:
- Toggle
Blob of vendor/grit/lib/grit/lazy.rb
(raw blob data)
| 1 | ## |
| 2 | # Allows attributes to be declared as lazy, meaning that they won't be |
| 3 | # computed until they are asked for. |
| 4 | # |
| 5 | # Works by delegating each lazy_reader to a cached lazy_source method. |
| 6 | # |
| 7 | # class Person |
| 8 | # lazy_reader :eyes |
| 9 | # |
| 10 | # def lazy_source |
| 11 | # OpenStruct.new(:eyes => 2) |
| 12 | # end |
| 13 | # end |
| 14 | # |
| 15 | # >> Person.new.eyes |
| 16 | # => 2 |
| 17 | # |
| 18 | module Lazy |
| 19 | def lazy_reader(*args) |
| 20 | args.each do |arg| |
| 21 | ivar = "@#{arg}" |
| 22 | define_method(arg) do |
| 23 | if instance_variables.include?(ivar) |
| 24 | val = instance_variable_get(ivar) |
| 25 | return val if val |
| 26 | end |
| 27 | instance_variable_set(ivar, (@lazy_source ||= lazy_source).send(arg)) |
| 28 | end |
| 29 | end |
| 30 | end |
| 31 | end |
| 32 | |
| 33 | Object.extend Lazy unless Object.ancestors.include? Lazy |
