Skip to content

Commit

Permalink
initial implementation + specs
Browse files Browse the repository at this point in the history
  • Loading branch information
garybernhardt committed Jan 26, 2012
1 parent f3de871 commit 273e101
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
25 changes: 25 additions & 0 deletions cls.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module Cls
def self.included(base)
base.send :extend, ClassMethods
end

module ClassMethods
def takes(*args)
define_initialize(args)
end

def define_initialize(args)
assignments = args.map { |a| "@#{a} = #{a}" }.join("\n")
self.class_eval %{
def initialize(#{args.join(", ")})
#{assignments}
end
}
end

def let(name, &block)
define_method(name, &block)
end
end
end

61 changes: 61 additions & 0 deletions spec/cls_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
require "./cls"

class NamePresenter
include Cls
attr_reader :name
takes(:name)
let(:yelled_name) { @name.upcase }
let(:name_with_argument) { |other| }
let(:increment) { @value ||= 0; @value += 1 }
end

describe Cls do
describe "initializers" do
it "takes initializer arguments" do
NamePresenter.new("Bob").name.should == "Bob"
end

it "errors when there are too many initializer arguments" do
expect do
NamePresenter.new("Bob", "Smith")
end.to raise_error(ArgumentError)
end

it "errors when there are too few initializer arguments" do
expect do
NamePresenter.new
end.to raise_error(ArgumentError)
end
end

describe "let methods" do
let(:presenter) { NamePresenter.new("Bob") }

it "defines methods" do
presenter.yelled_name.should == "BOB"
end

it "does not cache method return values" do
presenter.increment.should_not == presenter.increment
end

it "errors when there are too many method arguments" do
expect do
presenter.yelled_name("extra argument")
end.to raise_error(ArgumentError)
end

it "errors when there are too few method arguments" do
expect do
presenter.name_with_argument
end.to raise_error(ArgumentError)
end
end

it "doesn't pollute other classes" do
expect do
Class.new { takes :name }
end.to raise_error(NameError)
end
end

0 comments on commit 273e101

Please sign in to comment.