Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to set a base serial number #115

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions lib/machinist/blueprint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module Machinist

# A Blueprint defines a method of constructing objects of a particular class.
class Blueprint
@@serial_number_base = 0

# Construct a blueprint for the given +klass+.
#
Expand Down Expand Up @@ -66,13 +67,21 @@ def new_serial_number #:nodoc:
if parent_blueprint
parent_blueprint.new_serial_number
else
@serial_number ||= 0
@serial_number ||= self.class.serial_number_base
@serial_number += 1
sprintf("%04d", @serial_number)
end
end

private
def self.serial_number_base
@@serial_number_base || 0
end

def self.serial_number_base=(value)
@@serial_number_base = value || 0
end

private

def find_blueprint_in_superclass_chain(klass)
until has_blueprint?(klass) || klass.nil?
Expand Down
13 changes: 13 additions & 0 deletions spec/active_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@
post.author.should_not be_new_record
post.author.username.should =~ /^post_author_\d+$/
end

it "handles serial number base override" do
User.blueprint do
username { "user_#{sn}" }
end
Machinist::Blueprint.serial_number_base = 10000

User.make!.username.should == "user_10001"
User.make!.username.should == "user_10002"
Machinist::Blueprint.serial_number_base = 500
User.make!.username.should == "user_10003"
Machinist::Blueprint.serial_number_base = nil
end
end

context "error handling" do
Expand Down
10 changes: 10 additions & 0 deletions spec/blueprint_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@
blueprint.make.name.should == "Fred 0002"
end

it "allows serial number start value to be overridden" do
Machinist::Blueprint.serial_number_base = 1000
blueprint = Machinist::Blueprint.new(OpenStruct) do
name { "Fred #{sn}" }
end
blueprint.make.name.should == "Fred 1001"
blueprint.make.name.should == "Fred 1002"
Machinist::Blueprint.serial_number_base = nil
end

it "provides access to the object being constructed within the blueprint" do
blueprint = Machinist::Blueprint.new(OpenStruct) do
title { "Test" }
Expand Down