Last active
September 6, 2016 10:34
-
-
Save mikker/a8e81ca45ced664646a2d1849a3d689f to your computer and use it in GitHub Desktop.
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
require 'ostruct' | |
# Make little bundles of variables using Let {} | |
# | |
# example: | |
# things = Let { | |
# self.posts = Post.all | |
# self.comments = Comment.where(post: posts) | |
# } | |
# | |
# puts things.posts | |
module Let | |
class Object | |
def initialize(&block) | |
obj = OpenStruct.new | |
obj.instance_eval(&block) | |
@to_h = obj.to_h | |
end | |
attr_reader :to_h | |
def method_missing(method, *args, &block) | |
to_h[method] || super | |
end | |
end | |
end | |
def Let(&block) | |
Let::Object.new(&block) | |
end | |
if __FILE__ == $0 | |
require 'test/unit' | |
class LetTest < Test::Unit::TestCase | |
def test_values | |
obj = Let { | |
self.a = 1 | |
self.b = a + 1 | |
} | |
assert_equal 1, obj.a | |
assert_equal 2, obj.b | |
end | |
def test_raises_when_missing | |
assert_raise { Let {}.c } | |
end | |
def test_class_name | |
assert_equal "Let::Object", Let{}.class.to_s | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment