Skip to content

Instantly share code, notes, and snippets.

@garrytan
Last active February 16, 2016 00:53
Show Gist options
  • Select an option

  • Save garrytan/7917647 to your computer and use it in GitHub Desktop.

Select an option

Save garrytan/7917647 to your computer and use it in GitHub Desktop.
LazyGenerate module lets you lazily generate properties for ActiveRecord
# LazyGenerate makes it easy to make new ActiveRecord objects with accessors
# that are generated and saved lazily
#
# To use, add this to your ActiveRecord class:
# extend LazyGenerate
# lazy_generate :my_lazy_property, :generate_lazy_property
#
# Side effect: Save is called on the object upon generation.
#
module LazyGenerate
def lazy_generate(column, generate_method)
class_eval <<-RUBY, __FILE__, __LINE__+1
def #{column}_with_laziness
if existing_value = #{column}_without_laziness
existing_value
else
self.#{column} = new_value = #{generate_method}
save
new_value
end
end
alias_method_chain :#{column}, :laziness
RUBY
end
end
require 'spec_helper'
describe LazyGenerate do
describe '.lazy_generate' do
class LazyGenerateTest
extend LazyGenerate
attr_accessor :value
def generator
'xyz987'
end
def save; end
lazy_generate :value, :generator
end
context 'with an existing value' do
it 'should pass the value if already set' do
obj = LazyGenerateTest.new
obj.value = 'abc123'
obj.value.should eql 'abc123'
end
end
context 'with an existing value' do
it 'should generate the value if not already set' do
LazyGenerateTest.new.value.should eql 'xyz987'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment