added possibility to cast any key to any type using any method
This commit is contained in:
parent
12c09085df
commit
716bc74023
2 changed files with 23 additions and 4 deletions
|
@ -537,13 +537,14 @@ module CouchRest
|
||||||
self.class.casts.each do |k,v|
|
self.class.casts.each do |k,v|
|
||||||
next unless self[k]
|
next unless self[k]
|
||||||
target = v[:as]
|
target = v[:as]
|
||||||
|
v[:send] ||= 'new'
|
||||||
if target.is_a?(Array)
|
if target.is_a?(Array)
|
||||||
klass = ::Extlib::Inflection.constantize(target[0])
|
klass = ::Extlib::Inflection.constantize(target[0])
|
||||||
self[k] = self[k].collect do |value|
|
self[k] = self[k].collect do |value|
|
||||||
klass.new(value)
|
klass.send(v[:send], value)
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
self[k] = ::Extlib::Inflection.constantize(target).new(self[k])
|
self[k] = ::Extlib::Inflection.constantize(target).send(v[:send], self[k])
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -554,4 +555,4 @@ module CouchRest
|
||||||
register_instance_hooks :save, :create, :update, :destroy
|
register_instance_hooks :save, :create, :update, :destroy
|
||||||
|
|
||||||
end # class Model
|
end # class Model
|
||||||
end # module CouchRest
|
end # module CouchRest
|
||||||
|
|
|
@ -88,6 +88,12 @@ class Player < CouchRest::Model
|
||||||
timestamps!
|
timestamps!
|
||||||
end
|
end
|
||||||
|
|
||||||
|
class Event < CouchRest::Model
|
||||||
|
key_accessor :subject, :occurs_at
|
||||||
|
|
||||||
|
cast :occurs_at, :as => 'Time', :send => 'parse'
|
||||||
|
end
|
||||||
|
|
||||||
describe "save bug" do
|
describe "save bug" do
|
||||||
it "should fix" do
|
it "should fix" do
|
||||||
@db = reset_test_db!
|
@db = reset_test_db!
|
||||||
|
@ -314,6 +320,18 @@ describe CouchRest::Model do
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "cast keys to any type" do
|
||||||
|
before(:all) do
|
||||||
|
event_doc = { :subject => "Some event", :occurs_at => Time.now }
|
||||||
|
e = Event.database.save event_doc
|
||||||
|
|
||||||
|
@event = Event.get e['id']
|
||||||
|
end
|
||||||
|
it "should cast created_at to Time" do
|
||||||
|
@event['occurs_at'].should be_an_instance_of(Time)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "saving a model" do
|
describe "saving a model" do
|
||||||
before(:all) do
|
before(:all) do
|
||||||
@obj = Basic.new
|
@obj = Basic.new
|
||||||
|
@ -679,4 +697,4 @@ describe CouchRest::Model do
|
||||||
lambda{Basic.get(@obj.id)}.should raise_error
|
lambda{Basic.get(@obj.id)}.should raise_error
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Add table
Reference in a new issue