Skip to content

Instantly share code, notes, and snippets.

@mattconnolly
Created April 1, 2014 03:17

Revisions

  1. mattconnolly revised this gist Apr 1, 2014. 1 changed file with 4 additions and 2 deletions.
    6 changes: 4 additions & 2 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -2,10 +2,12 @@ module Let

    def let(name, &block)
    ivar = "@#{name}".to_sym
    unless instance_variable_defined?(ivar)
    if instance_variable_defined?(ivar)
    instance_variable_get(ivar)
    else
    instance_variable_set(ivar, instance_eval(&block))
    end
    instance_variable_get(ivar)

    end

    end
  2. mattconnolly renamed this gist Apr 1, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. mattconnolly created this gist Apr 1, 2014.
    24 changes: 24 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    module Let

    def let(name, &block)
    ivar = "@#{name}".to_sym
    unless instance_variable_defined?(ivar)
    instance_variable_set(ivar, instance_eval(&block))
    end
    instance_variable_get(ivar)
    end

    end

    class Thing
    include Let

    def result
    let(:result) { some_expensive_calculation_that_could_return_nil }
    end
    end

    t = Thing.new
    t.result #=> calculated result that could be nil
    t.result #=> cached result that could be nil