Created
April 23, 2013 13:09
-
-
Save eightbitraptor/5443426 to your computer and use it in GitHub Desktop.
Spiking a slimline no work allowed approach to constructors in Ruby.
This file contains 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 'rspec' | |
module Hardline | |
def self.extended(base) | |
base.define_singleton_method(:construct_with) do |*args| | |
base.define_singleton_method(:new) do |*init_args| | |
combined_args = args.zip(init_args) | |
me = self.allocate | |
me.tap do |obj| | |
combined_args.map do |(n, v)| | |
obj.instance_variable_set("@#{n}", v) | |
end | |
end | |
end | |
end | |
end | |
end | |
class Foo | |
extend Hardline | |
construct_with(:var1, :var2) | |
end | |
describe Foo do | |
subject{ Foo.new("hello", "kitty") } | |
it "should create a new object" do | |
subject.should be_a(Foo) | |
end | |
it "should assign instance vars as specified in constructor" do | |
subject.instance_variable_get("@var1").should eq "hello" | |
subject.instance_variable_get("@var2").should eq "kitty" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment