Build immutable classes #118

Closed
wants to merge 2 commits into
from
View
@@ -201,6 +201,28 @@ You can blueprint the Post class just like anything else:
And `Post.make` will construct a new Post.
+### Immutable Objects
+
+You don't need to expose writer methods for the attributes you wish to leverage in the blueprint.
+
+For example:
+
+ class Post
+ extend Machinist::Machinable
+
+ attr_reader :title
+ attr_reader :body
+ end
+
+The blueprint above will still work:
+
+ Post.blueprint do
+ title { "A title!" }
+ body { "A body!" }
+ end
+
+And `Post.make` will still construct a new Post.
+
### Other Tricks
View
@@ -53,7 +53,11 @@ def make_one_value(attribute, args) #:nodoc:
def assign_attribute(key, value) #:nodoc:
@assigned_attributes[key.to_sym] = value
- @object.send("#{key}=", value)
+ begin
+ @object.send("#{key}=", value)
+ rescue
+ @object.instance_variable_set("@#{key}", value)
+ end
end
def attribute_assigned?(key) #:nodoc:
View
@@ -10,6 +10,11 @@ class Comment
extend Machinist::Machinable
attr_accessor :post, :title
end
+
+ class Immutable
+ extend Machinist::Machinable
+ attr_reader :name
+ end
end
describe Machinist::Machinable do
@@ -72,6 +77,16 @@ class Comment
end
end
+ it "supports immutable classes" do
+ MachinableSpecs::Immutable.blueprint do
+ name { "Mr. Immutable" }
+ end
+
+ post = MachinableSpecs::Immutable.make
+ post.should be_a(MachinableSpecs::Immutable)
+ post.name.should == "Mr. Immutable"
+ end
+
it "fails without a blueprint" do
expect do
MachinableSpecs::Post.make