Last active
August 29, 2015 14:01
-
-
Save samrayner/cfbf8e666018bb0dbbda to your computer and use it in GitHub Desktop.
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
class Tableless | |
include ActiveModel::Validations | |
include ActiveModel::Conversion | |
extend ActiveModel::Naming | |
attr_accessor :new_record | |
def initialize(attributes={}) | |
self.new_record = attributes.blank? | |
attributes && attributes.each do |name, value| | |
send("#{name}=", value) if respond_to? name.to_sym | |
end | |
end | |
def new_record? | |
return self.new_record | |
end | |
def persisted? | |
false | |
end | |
def self.inspect | |
if self.respond_to?(:attributes) | |
"#<#{self.to_s} #{self.attributes.collect{ |e| ":#{ e }" }.join(', ')}>" | |
else | |
"#<#{self.to_s}>" | |
end | |
end | |
end | |
#rspec | |
include ActiveModel::Lint::Tests | |
describe Tableless do | |
describe "#initialize" do | |
before do | |
class Person < Tableless | |
attr_accessor :name | |
end | |
end | |
it "takes an array of attributes and sets them" do | |
person = Person.new(name: "Sam") | |
person.name.should == "Sam" | |
end | |
it "does not set undefined attributes" do | |
person = Person.new(name: "Sam", title: "Prof") | |
expect { person.title }.to raise_error(NoMethodError) | |
end | |
end | |
describe "#new_record?" do | |
it "should return true for a new object" do | |
tableless = Tableless.new | |
tableless.new_record?.should == true | |
end | |
it "should return false for an object with attributes set" do | |
tableless = Tableless.new(name: "Sam") | |
tableless.new_record?.should == false | |
end | |
end | |
describe "#persisted?" do | |
it "should not be persisted" do | |
tableless = Tableless.new | |
tableless.persisted?.should be_false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment