Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'activemodel'

  • Loading branch information...
commit ec9e6d677791718fca774150a1bea50e417dc384 2 parents 3304de6 + c8be2db
@treeder treeder authored
View
205 lib/simple_record.rb
@@ -29,11 +29,12 @@
require 'active_support'
require 'active_support/core_ext'
begin
+ # comment out line below to test rails2 validations
require 'active_model'
rescue LoadError => ex
puts "ActiveModel not available, falling back."
end
-require File.expand_path(File.dirname(__FILE__) + "/simple_record/validation")
+require File.expand_path(File.dirname(__FILE__) + "/simple_record/validations")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/attributes")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/active_sdb")
require File.expand_path(File.dirname(__FILE__) + "/simple_record/callbacks")
@@ -178,21 +179,32 @@ class Base < SimpleRecord::ActiveSdb::Base
if defined?(ActiveModel)
+ @@active_model = true
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
+ extend ActiveModel::Callbacks # for ActiveRecord like callbacks
+ include ActiveModel::Validations::Callbacks
+ define_model_callbacks :save, :create, :update, :destroy
+ include SimpleRecord::Callbacks3
+ alias_method :am_valid?, :valid?
+
+
else
+ @@active_model = false
+ puts "using rails2 validations."
attr_accessor :errors
+ include SimpleRecord::Callbacks
end
+ include SimpleRecord::Validations
+
- include SimpleRecord::Validation
include SimpleRecord::Translations
# include SimpleRecord::Attributes
extend SimpleRecord::Attributes::ClassMethods
include SimpleRecord::Attributes
extend SimpleRecord::Sharding::ClassMethods
include SimpleRecord::Sharding
- include SimpleRecord::Callbacks
include SimpleRecord::Json
include SimpleRecord::Logging
extend SimpleRecord::Logging::ClassMethods
@@ -432,8 +444,9 @@ def new_record?
# - :dirty => true - Will only store attributes that were modified. To make it save regardless and have it update the :updated value, include this and set it to false.
# - :domain => Explicitly define domain to use.
#
+
def save(options={})
-# puts 'SAVING: ' + self.inspect if SimpleRecord.logging?
+ puts 'SAVING: ' + self.inspect if SimpleRecord.logging?
# todo: Clean out undefined values in @attributes (in case someone set the attributes hash with values that they hadn't defined)
clear_errors
# todo: decide whether this should go before pre_save or after pre_save? pre_save dirties "updated" and perhaps other items due to callbacks
@@ -444,6 +457,7 @@ def save(options={})
is_create = self[:id].nil?
ok = pre_save(options) # Validates and sets ID
if ok
+ puts 'ok'
begin
dirty = @dirty
# puts 'dirty before=' + @dirty.inspect
@@ -452,35 +466,119 @@ def save(options={})
return true if @dirty.size == 0 # This should probably never happen because after pre_save, created/updated dates are changed
options[:dirty_atts] = @dirty
end
- to_delete = get_atts_to_delete
- SimpleRecord.stats.saves += 1
+ to_delete = get_atts_to_delete
+
if self.class.is_sharded?
options[:domain] = sharded_domain
end
- if super(options)
- self.class.cache_results(self)
- delete_niled(to_delete)
- save_lobs(dirty)
- after_save_cleanup
- if (is_create ? run_after_create : run_after_update) && run_after_save
-# puts 'all good?'
- return true
- else
- return false
- end
+ if @@active_model
+ x = save_super(dirty, is_create, options, to_delete)
+ puts 'save_super result = ' + x.to_s
+ return x
else
- return false
+ puts 'not activemodel callbacks'
+ return save_super(dirty, is_create, options, to_delete)
end
rescue Aws::AwsError => ex
raise ex
end
else
+ puts 'returning false'
+ return false
+ end
+ end
+
+ if @@active_model
+ alias_method :old_save, :save
+
+ def save(options={})
+ puts 'extended save'
+ x = create_or_update
+ puts 'save x=' + x.to_s
+ x
+ end
+ end
+
+ def create_or_update #:nodoc:
+ puts 'create_or_update'
+ ret = true
+ _run_save_callbacks do
+ result = new_record? ? create : update
+ puts 'save_callbacks result=' + result.inspect
+ ret = result
+ end
+ ret
+ end
+
+ def create #:nodoc:
+ puts '3 create'
+ ret = true
+ _run_create_callbacks do
+ x = old_save
+ puts 'create old_save result=' + x.to_s
+ ret = x
+ end
+ ret
+ end
+
+#
+ def update(*) #:nodoc:
+ puts '3 update'
+ ret = true
+ _run_update_callbacks do
+ x = old_save
+ puts 'update old_save result=' + x.to_s
+ ret = x
+ end
+ ret
+ end
+
+
+ def save!(options={})
+ save(options) || raise(RecordNotSaved.new(self))
+ end
+
+ # this is a bit wonky, save! should call this, not sure why it's here.
+ def save_with_validation!(options={})
+ save!
+ end
+
+ def self.create(attributes={})
+# puts "About to create in domain #{domain}"
+ super
+ end
+
+ def self.create!(attributes={})
+ item = self.new(attributes)
+ item.save!
+ item
+ end
+
+
+ def save_super(dirty, is_create, options, to_delete)
+ SimpleRecord.stats.saves += 1
+ if save2(options)
+ self.class.cache_results(self)
+ delete_niled(to_delete)
+ save_lobs(dirty)
+ after_save_cleanup
+ unless @@active_model
+ if (is_create ? run_after_create : run_after_update) && run_after_save
+# puts 'all good?'
+ return true
+ else
+ return false
+ end
+ end
+ return true
+ else
return false
end
end
+
def save_lobs(dirty=nil)
# puts 'dirty.inspect=' + dirty.inspect
dirty = @dirty if dirty.nil?
@@ -590,26 +688,6 @@ def single_clob_id
"lobs/#{self.id}_single_clob"
end
- def save!(options={})
- save(options) || raise(RecordNotSaved.new(nil, self))
- end
-
- # this is a bit wonky, save! should call this, not sure why it's here.
- def save_with_validation!(options={})
- save!
- end
-
- def self.create(attributes={})
-# puts "About to create in domain #{domain}"
- super
- end
-
- def self.create!(attributes={})
- item = self.new(attributes)
- item.save!
- item
- end
-
def self.get_encryption_key()
key = SimpleRecord.options[:encryption_key]
@@ -622,13 +700,18 @@ def self.get_encryption_key()
def pre_save(options)
+
+ ok = true
is_create = self[:id].nil?
- ok = run_before_validation && (is_create ? run_before_validation_on_create : run_before_validation_on_update)
- return false unless ok
+ unless @@active_model
+ ok = run_before_validation && (is_create ? run_before_validation_on_create : run_before_validation_on_update)
+ return false unless ok
+ end
# validate()
# is_create ? validate_on_create : validate_on_update
if !valid?
+ puts 'not valid'
return false
end
#
@@ -638,23 +721,26 @@ def pre_save(options)
# return false
# end
- ok = run_after_validation && (is_create ? run_after_validation_on_create : run_after_validation_on_update)
- return false unless ok
+ unless @@active_model
+ ok = run_after_validation && (is_create ? run_after_validation_on_create : run_after_validation_on_update)
+ return false unless ok
+ end
- ok = respond_to?('before_save') ? before_save : true
- if ok
- if is_create && respond_to?('before_create')
- ok = before_create
- elsif !is_create && respond_to?('before_update')
- ok = before_update
+ # Now for callbacks
+ unless @@active_model
+ ok = respond_to?('before_save') ? before_save : true
+ if ok
+ if is_create && respond_to?('before_create')
+ ok = before_create
+ elsif !is_create && respond_to?('before_update')
+ ok = before_update
+ end
end
- end
- if ok
- ok = run_before_save && (is_create ? run_before_create : run_before_update)
- end
- if ok
- # Now translate all fields into SimpleDB friendly strings
-# convert_all_atts_to_sdb()
+ if ok
+ ok = run_before_save && (is_create ? run_before_create : run_before_update)
+ end
+ else
+
end
prepare_for_update
ok
@@ -756,10 +842,15 @@ def delete(options={})
end
def destroy
- return run_before_destroy && delete && run_after_destroy
+ if @@active_model
+ _run_destroy_callbacks do
+ delete
+ end
+ else
+ return run_before_destroy && delete && run_after_destroy
+ end
end
-
def delete_niled(to_delete)
# puts 'to_delete=' + to_delete.inspect
if to_delete.size > 0
View
2  lib/simple_record/active_sdb.rb
@@ -856,7 +856,7 @@ def put_attributes(attrs)
# - :except => Array of attributes to NOT save
#
# compare to +put+ method
- def save(options={})
+ def save2(options={})
options[:create_domain] = true if options[:create_domain].nil?
pre_save2
atts_to_save = @attributes.dup
View
62 lib/simple_record/callbacks.rb
@@ -1,4 +1,31 @@
-module SimpleRecord::Callbacks
+module SimpleRecord
+
+ # For Rails3 support
+ module Callbacks3
+
+# def destroy #:nodoc:
+# _run_destroy_callbacks { super }
+# end
+#
+# private
+#
+# def create_or_update #:nodoc:
+# puts '3 create_or_update'
+# _run_save_callbacks { super }
+# end
+#
+# def create #:nodoc:
+# puts '3 create'
+# _run_create_callbacks { super }
+# end
+#
+# def update(*) #:nodoc:
+# puts '3 update'
+# _run_update_callbacks { super }
+# end
+ end
+
+ module Callbacks
#this bit of code creates a "run_blank" function for everything value in the @@callbacks array.
#this function can then be inserted in the appropriate place in the save, new, destroy, etc overrides
#basically, this is how we recreate the callback functions
@@ -9,10 +36,10 @@ module SimpleRecord::Callbacks
"after_destroy"]
def self.included(base)
- #puts 'Callbacks included in ' + base.inspect
+ #puts 'Callbacks included in ' + base.inspect
# puts "setup callbacks #{base.inspect}"
- base.instance_eval <<-endofeval
+ base.instance_eval <<-endofeval
def callbacks
@callbacks ||= {}
@@ -20,18 +47,18 @@ def callbacks
end
- endofeval
+ endofeval
- @@callbacks.each do |callback|
- base.class_eval <<-endofeval
+ @@callbacks.each do |callback|
+ base.class_eval <<-endofeval
def run_#{callback}
-# puts 'CLASS CALLBACKS for ' + self.inspect + ' = ' + self.class.callbacks.inspect
+ # puts 'CLASS CALLBACKS for ' + self.inspect + ' = ' + self.class.callbacks.inspect
return true if self.class.callbacks.nil?
cnames = self.class.callbacks['#{callback}']
cnames = [] if cnames.nil?
- #cnames += super.class.callbacks['#{callback}'] unless super.class.callbacks.nil?
-# puts 'cnames for #{callback} = ' + cnames.inspect
+ # cnames += super.class.callbacks['#{callback}'] unless super.class.callbacks.nil?
+ # puts 'cnames for #{callback} = ' + cnames.inspect
return true if cnames.nil?
cnames.each { |name|
#puts 'run_ #{name}'
@@ -39,16 +66,16 @@ def run_#{callback}
return false
end
}
- #super.run_#{callback}
+ # super.run_#{callback}
return true
end
- endofeval
+ endofeval
- #this bit of code creates a "run_blank" function for everything value in the @@callbacks array.
- #this function can then be inserted in the appropriate place in the save, new, destroy, etc overrides
- #basically, this is how we recreate the callback functions
- base.instance_eval <<-endofeval
+ #this bit of code creates a "run_blank" function for everything value in the @@callbacks array.
+ #this function can then be inserted in the appropriate place in the save, new, destroy, etc overrides
+ #basically, this is how we recreate the callback functions
+ base.instance_eval <<-endofeval
# puts 'defining callback=' + callback + ' for ' + self.inspect
#we first have to make an initialized array for each of the callbacks, to prevent problems if they are not called
@@ -69,8 +96,8 @@ def #{callback}(*args)
end
end
- endofeval
- end
+ endofeval
+ end
end
def before_destroy()
@@ -84,4 +111,5 @@ def self.setup_callbacks(base)
end
+ end
end
View
446 lib/simple_record/translations.rb
@@ -1,253 +1,253 @@
# This module defines all the methods that perform data translations for storage and retrieval.
module SimpleRecord
- module Translations
-
- @@offset = 9223372036854775808
- @@padding = 20
- @@date_format = "%Y-%m-%dT%H:%M:%S";
-
- def ruby_to_string_val(att_meta, value)
- if att_meta.type == :int
- ret = Translations.pad_and_offset(value, att_meta)
- elsif att_meta.type == :date
- ret = Translations.pad_and_offset(value, att_meta)
- else
- ret = value.to_s
- end
- ret
- end
+ module Translations
+
+ @@offset = 9223372036854775808
+ @@padding = 20
+ @@date_format = "%Y-%m-%dT%H:%M:%S";
+
+ def ruby_to_string_val(att_meta, value)
+ if att_meta.type == :int
+ ret = Translations.pad_and_offset(value, att_meta)
+ elsif att_meta.type == :date
+ ret = Translations.pad_and_offset(value, att_meta)
+ else
+ ret = value.to_s
+ end
+ ret
+ end
- # Time to second precision
+ # Time to second precision
- def ruby_to_sdb(name, value)
- return nil if value.nil?
- name = name.to_s
+ def ruby_to_sdb(name, value)
+ return nil if value.nil?
+ name = name.to_s
# puts "Converting #{name} to sdb value=#{value}"
# puts "atts_local=" + defined_attributes_local.inspect
- att_meta = get_att_meta(name)
+ att_meta = get_att_meta(name)
- if value.is_a? Array
- ret = value.collect { |x| ruby_to_string_val(att_meta, x) }
- else
- ret = ruby_to_string_val(att_meta, value)
- end
+ if value.is_a? Array
+ ret = value.collect { |x| ruby_to_string_val(att_meta, x) }
+ else
+ ret = ruby_to_string_val(att_meta, value)
+ end
- unless value.blank?
- if att_meta.options
- if att_meta.options[:encrypted]
+ unless value.blank?
+ if att_meta.options
+ if att_meta.options[:encrypted]
# puts "ENCRYPTING #{name} value #{value}"
- ret = Translations.encrypt(ret, att_meta.options[:encrypted])
+ ret = Translations.encrypt(ret, att_meta.options[:encrypted])
# puts 'encrypted value=' + ret.to_s
- end
- if att_meta.options[:hashed]
+ end
+ if att_meta.options[:hashed]
# puts "hashing #{name}"
- ret = Translations.pass_hash(ret)
+ ret = Translations.pass_hash(ret)
# puts "hashed value=" + ret.inspect
- end
- end
- end
+ end
+ end
+ end
- return ret
+ return ret
- end
+ end
- # Convert value from SimpleDB String version to real ruby value.
- def sdb_to_ruby(name, value)
+ # Convert value from SimpleDB String version to real ruby value.
+ def sdb_to_ruby(name, value)
# puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s
- return nil if value.nil?
- att_meta = get_att_meta(name)
-
- if att_meta.options
- if att_meta.options[:encrypted]
- value = Translations.decrypt(value, att_meta.options[:encrypted])
- end
- if att_meta.options[:hashed]
- return PasswordHashed.new(value)
- end
- end
-
+ return nil if value.nil?
+ att_meta = get_att_meta(name)
- if !has_id_on_end(name) && att_meta.type == :belongs_to
- class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length]
- # Camelize classnames with underscores (ie my_model.rb --> MyModel)
- class_name = class_name.camelize
- # puts "attr=" + @attributes[arg_id].inspect
- # puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil?
- ret = nil
- arg_id = name.to_s + '_id'
- arg_id_val = send("#{arg_id}")
- if arg_id_val
- if !cache_store.nil?
+ if att_meta.options
+ if att_meta.options[:encrypted]
+ value = Translations.decrypt(value, att_meta.options[:encrypted])
+ end
+ if att_meta.options[:hashed]
+ return PasswordHashed.new(value)
+ end
+ end
+
+
+ if !has_id_on_end(name) && att_meta.type == :belongs_to
+ class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length]
+ # Camelize classnames with underscores (ie my_model.rb --> MyModel)
+ class_name = class_name.camelize
+ # puts "attr=" + @attributes[arg_id].inspect
+ # puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil?
+ ret = nil
+ arg_id = name.to_s + '_id'
+ arg_id_val = send("#{arg_id}")
+ if arg_id_val
+ if !cache_store.nil?
# arg_id_val = @attributes[arg_id][0]
- cache_key = self.class.cache_key(class_name, arg_id_val)
+ cache_key = self.class.cache_key(class_name, arg_id_val)
# puts 'cache_key=' + cache_key
- ret = cache_store.read(cache_key)
+ ret = cache_store.read(cache_key)
# puts 'belongs_to incache=' + ret.inspect
- end
- if ret.nil?
- to_eval = "#{class_name}.find('#{arg_id_val}')"
+ end
+ if ret.nil?
+ to_eval = "#{class_name}.find('#{arg_id_val}')"
# puts 'to eval=' + to_eval
- begin
- ret = eval(to_eval) # (defined? #{arg}_id)
- rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex
- if ex.message.include? "Couldn't find"
- ret = RemoteNil.new
- else
- raise ex
- end
- end
-
- end
- end
- value = ret
- else
- if value.is_a? Array
- value = value.collect { |x| string_val_to_ruby(att_meta, x) }
- else
- value = string_val_to_ruby(att_meta, value)
- end
+ begin
+ ret = eval(to_eval) # (defined? #{arg}_id)
+ rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex
+ if ex.message.include? "Couldn't find"
+ ret = RemoteNil.new
+ else
+ raise ex
+ end
end
- value
- end
- def string_val_to_ruby(att_meta, value)
- if att_meta.type == :int
- value = Translations.un_offset_int(value)
- elsif att_meta.type == :date
- value = to_date(value)
- elsif att_meta.type == :boolean
- value = to_bool(value)
- end
- value
+ end
+ end
+ value = ret
+ else
+ if value.is_a? Array
+ value = value.collect { |x| string_val_to_ruby(att_meta, x) }
+ else
+ value = string_val_to_ruby(att_meta, value)
end
+ end
+ value
+ end
+
+ def string_val_to_ruby(att_meta, value)
+ if att_meta.type == :int
+ value = Translations.un_offset_int(value)
+ elsif att_meta.type == :date
+ value = to_date(value)
+ elsif att_meta.type == :boolean
+ value = to_bool(value)
+ end
+ value
+ end
- def self.pad_and_offset(x, att_meta=nil) # Change name to something more appropriate like ruby_to_sdb
- # todo: add Float, etc
- # puts 'padding=' + x.class.name + " -- " + x.inspect
- if x.kind_of? Integer
- x += @@offset
- x_str = x.to_s
- # pad
- x_str = '0' + x_str while x_str.size < 20
- return x_str
- elsif x.respond_to?(:iso8601)
- # puts x.class.name + ' responds to iso8601'
- #
- # There is an issue here where Time.iso8601 on an incomparable value to DateTime.iso8601.
- # Amazon suggests: 2008-02-10T16:52:01.000-05:00
- # "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
- #
- if x.is_a? DateTime
- x_str = x.getutc.strftime(@@date_format)
- elsif x.is_a? Time
- x_str = x.getutc.strftime(@@date_format)
- elsif x.is_a? Date
- x_str = x.strftime(@@date_format)
-
- end
- return x_str
- elsif x.is_a? Float
- from_float(x)
- else
- return x
- end
+ def self.pad_and_offset(x, att_meta=nil) # Change name to something more appropriate like ruby_to_sdb
+ # todo: add Float, etc
+ # puts 'padding=' + x.class.name + " -- " + x.inspect
+ if x.kind_of? Integer
+ x += @@offset
+ x_str = x.to_s
+ # pad
+ x_str = '0' + x_str while x_str.size < 20
+ return x_str
+ elsif x.respond_to?(:iso8601)
+ # puts x.class.name + ' responds to iso8601'
+ #
+ # There is an issue here where Time.iso8601 on an incomparable value to DateTime.iso8601.
+ # Amazon suggests: 2008-02-10T16:52:01.000-05:00
+ # "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
+ #
+ if x.is_a? DateTime
+ x_str = x.getutc.strftime(@@date_format)
+ elsif x.is_a? Time
+ x_str = x.getutc.strftime(@@date_format)
+ elsif x.is_a? Date
+ x_str = x.strftime(@@date_format)
+
end
+ return x_str
+ elsif x.is_a? Float
+ from_float(x)
+ else
+ return x
+ end
+ end
- # This conversion to a string is based on: http://tools.ietf.org/html/draft-wood-ldapext-float-00
- # Java code sample is here: http://code.google.com/p/typica/source/browse/trunk/java/com/xerox/amazonws/simpledb/DataUtils.java
- def self.from_float(x)
- return x
+ # This conversion to a string is based on: http://tools.ietf.org/html/draft-wood-ldapext-float-00
+ # Java code sample is here: http://code.google.com/p/typica/source/browse/trunk/java/com/xerox/amazonws/simpledb/DataUtils.java
+ def self.from_float(x)
+ return x
# if x == 0.0
# return "3 000 0.0000000000000000"
# end
- end
+ end
- def wrap_if_required(arg, value, sdb_val)
- return nil if value.nil?
+ def wrap_if_required(arg, value, sdb_val)
+ return nil if value.nil?
- att_meta = defined_attributes_local[arg.to_sym]
- if att_meta && att_meta.options
- if att_meta.options[:hashed]
+ att_meta = defined_attributes_local[arg.to_sym]
+ if att_meta && att_meta.options
+ if att_meta.options[:hashed]
# puts 'wrapping ' + arg_s
- return PasswordHashed.new(sdb_val)
- end
- end
- value
+ return PasswordHashed.new(sdb_val)
end
+ end
+ value
+ end
- def to_date(x)
- if x.is_a?(String)
- DateTime.parse(x)
- else
- x
- end
- end
+ def to_date(x)
+ if x.is_a?(String)
+ DateTime.parse(x)
+ else
+ x
+ end
+ end
- def to_bool(x)
- if x.is_a?(String)
- x == "true" || x == "1"
- else
- x
- end
- end
+ def to_bool(x)
+ if x.is_a?(String)
+ x == "true" || x == "1"
+ else
+ x
+ end
+ end
- def self.un_offset_int(x)
- if x.is_a?(String)
- x2 = x.to_i
+ def self.un_offset_int(x)
+ if x.is_a?(String)
+ x2 = x.to_i
# puts 'to_i=' + x2.to_s
- x2 -= @@offset
+ x2 -= @@offset
# puts 'after subtracting offset='+ x2.to_s
- x2
- else
- x
- end
- end
+ x2
+ else
+ x
+ end
+ end
- def unpad(i, attributes)
- if !attributes[i].nil?
+ def unpad(i, attributes)
+ if !attributes[i].nil?
# puts 'before=' + self[i].inspect
- attributes[i].collect! { |x|
- un_offset_int(x)
+ attributes[i].collect! { |x|
+ un_offset_int(x)
- }
- end
- end
+ }
+ end
+ end
- def unpad_self
- defined_attributes_local.each_pair do |name, att_meta|
- if att_meta.type == :int
- unpad(name, @attributes)
- end
- end
+ def unpad_self
+ defined_attributes_local.each_pair do |name, att_meta|
+ if att_meta.type == :int
+ unpad(name, @attributes)
end
+ end
+ end
- def self.encrypt(value, key=nil)
- key = key || get_encryption_key()
- raise SimpleRecordError, "Encryption key must be defined on the attribute." if key.nil?
- encrypted_value = SimpleRecord::Encryptor.encrypt(:value => value, :key => key)
- encoded_value = Base64.encode64(encrypted_value)
- encoded_value
- end
+ def self.encrypt(value, key=nil)
+ key = key || get_encryption_key()
+ raise SimpleRecordError, "Encryption key must be defined on the attribute." if key.nil?
+ encrypted_value = SimpleRecord::Encryptor.encrypt(:value => value, :key => key)
+ encoded_value = Base64.encode64(encrypted_value)
+ encoded_value
+ end
- def self.decrypt(value, key=nil)
+ def self.decrypt(value, key=nil)
# puts "decrypt orig value #{value} "
- unencoded_value = Base64.decode64(value)
- raise SimpleRecordError, "Encryption key must be defined on the attribute." if key.nil?
- key = key || get_encryption_key()
+ unencoded_value = Base64.decode64(value)
+ raise SimpleRecordError, "Encryption key must be defined on the attribute." if key.nil?
+ key = key || get_encryption_key()
# puts "decrypting #{unencoded_value} "
- decrypted_value = SimpleRecord::Encryptor.decrypt(:value => unencoded_value, :key => key)
+ decrypted_value = SimpleRecord::Encryptor.decrypt(:value => unencoded_value, :key => key)
# "decrypted #{unencoded_value} to #{decrypted_value}"
- decrypted_value
- end
+ decrypted_value
+ end
- def pad_and_offset_ints_to_sdb()
+ def pad_and_offset_ints_to_sdb()
# defined_attributes_local.each_pair do |name, att_meta|
# if att_meta.type == :int && !self[name.to_s].nil?
@@ -256,51 +256,51 @@ def pad_and_offset_ints_to_sdb()
# @attributes[name.to_s] = arr
# end
# end
- end
+ end
- def convert_dates_to_sdb()
+ def convert_dates_to_sdb()
# defined_attributes_local.each_pair do |name, att_meta|
# puts 'int encoding: ' + i.to_s
# end
- end
-
- def self.pass_hash(value)
- hashed = Password::create_hash(value)
- encoded_value = Base64.encode64(hashed)
- encoded_value
- end
+ end
- def self.pass_hash_check(value, value_to_compare)
- unencoded_value = Base64.decode64(value)
- return Password::check(value_to_compare, unencoded_value)
- end
+ def self.pass_hash(value)
+ hashed = Password::create_hash(value)
+ encoded_value = Base64.encode64(hashed)
+ encoded_value
+ end
+ def self.pass_hash_check(value, value_to_compare)
+ unencoded_value = Base64.decode64(value)
+ return Password::check(value_to_compare, unencoded_value)
end
+ end
- class PasswordHashed
- def initialize(value)
- @value = value
- end
+ class PasswordHashed
- def hashed_value
- @value
- end
+ def initialize(value)
+ @value = value
+ end
- # This allows you to compare an unhashed string to the hashed one.
- def ==(val)
- if val.is_a?(PasswordHashed)
- return val.hashed_value == self.hashed_value
- end
- return Translations.pass_hash_check(@value, val)
- end
+ def hashed_value
+ @value
+ end
- def to_s
- @value
- end
+ # This allows you to compare an unhashed string to the hashed one.
+ def ==(val)
+ if val.is_a?(PasswordHashed)
+ return val.hashed_value == self.hashed_value
+ end
+ return Translations.pass_hash_check(@value, val)
+ end
+
+ def to_s
+ @value
end
+ end
end
View
35 lib/simple_record/validation.rb → lib/simple_record/validations.rb
@@ -2,37 +2,46 @@
# ActiveModel does not work the same way so need to continue using this, will change name.
module SimpleRecord
- module Validation
-
- if defined?(:valid?) # from ActiveModel
- alias_method :am_valid?, :valid?
+ module Validations
+
+# if defined?(:valid?) # from ActiveModel
+# alias_method :am_valid?, :valid?
+# end
+
+ def self.included(base)
+ puts 'Validations included ' + base.inspect
+# if defined?(ActiveModel)
+# base.class_eval do
+# alias_method :am_valid?, :valid?
+# end
+# end
end
-
def valid?
puts 'in rails2 valid?'
errors.clear
-# run_callbacks(:validate)
+ if defined?(:am_valid?)
+ # And now ActiveModel validations too
+ am_valid?
+ end
+
+ # run_callbacks(:validate)
validate
+
if new_record?
-# run_callbacks(:validate_on_create)
+ # run_callbacks(:validate_on_create)
validate_on_create
else
-# run_callbacks(:validate_on_update)
+ # run_callbacks(:validate_on_update)
validate_on_update
end
- # And now ActiveModel validations too
- if defined?(:am_valid?)
- am_valid?
- end
errors.empty?
end
-
def invalid?
!valid?
end
View
2  simple_record.gemspec
@@ -25,7 +25,7 @@ Gem::Specification.new do |s|
"lib/simple_record/json.rb",
"lib/simple_record/logging.rb",
"lib/simple_record/password.rb",
- "lib/simple_record/validation.rb",
+ "lib/simple_record/validations.rb",
"lib/simple_record/results_array.rb",
"lib/simple_record/sharding.rb",
"lib/simple_record/stats.rb",
View
115 test/my_model.rb
@@ -4,60 +4,93 @@
class MyModel < MyBaseModel
- has_strings :name, :nickname, :s1, :s2
- has_ints :age, :save_count
- has_booleans :cool
- has_dates :birthday, :date1, :date2, :date3
-
- belongs_to :my_sharded_model
-
- has_clobs :clob1, :clob2
-
- #callbacks
- before_create :set_nickname
-
- before_save :bump_save_count
-
- def set_nickname
- self.nickname = name if self.nickname.blank?
+ has_strings :name, :nickname, :s1, :s2
+ has_ints :age, :save_count
+ has_booleans :cool
+ has_dates :birthday, :date1, :date2, :date3
+
+# validates_presence_of :name
+
+# validate :validate
+# before_create :validate_on_create
+# before_update :validate_on_update
+
+ belongs_to :my_sharded_model
+
+ has_clobs :clob1, :clob2
+
+ attr_accessor :attr_before_save, :attr_after_save, :attr_before_create, :attr_after_create
+
+ #callbacks
+ before_create :set_nickname
+ after_create :after_create
+
+ before_save :before_save
+
+ after_save :after_save
+
+ def set_nickname
+ puts 'before_create set nickname'
+ @attr_before_create = true
+ self.nickname = name if self.nickname.blank?
+ end
+
+ def before_save
+ puts 'before_save'
+ @attr_before_save = true
+ end
+
+ def after_create
+ puts 'after_create'
+ @attr_after_create = true
+ end
+
+ def after_save
+ puts "after_save"
+ @attr_after_save = true
+ bump_save_count
+ end
+
+ def bump_save_count
+ puts 'after_save bump save_count=' + save_count.to_s
+ if save_count.nil?
+ self.save_count = 1
+ else
+ self.save_count += 1
end
-
- def bump_save_count
-# puts 'save_count=' + save_count.to_s
- if save_count.nil?
- self.save_count = 1
- else
- self.save_count += 1
- end
# puts 'save_count=' + self.save_count.to_s
- end
+ end
- def validate
- errors.add("name", "can't be empty.") if name.blank?
- end
+ def validate
+ puts 'MyModel.validate'
+ errors.add("name", "can't be empty.") if name.blank?
+# errors.add("nickname", "can't be empty.") if nickname.blank?
+ end
- def validate_on_create
- errors.add("save_count", "should be zero.") if !save_count.blank? && save_count > 0
- end
+ def validate_on_create
+ puts 'MyModel.validate_on_create'
+ errors.add("save_count", "should be zero.") if !save_count.blank? && save_count > 0
+ end
- def validate_on_update
+ def validate_on_update
+ puts 'MyModel.validate_on_update'
# puts 'save_count = ' + save_count.to_s
- errors.add("save_count", "should not be zero.") if save_count.blank? || save_count == 0
- end
+ errors.add("save_count", "should not be zero.") if save_count.blank? || save_count == 0
+ end
- def atts
- @@attributes
- end
+ def atts
+ @@attributes
+ end
-end
+end
class SingleClobClass < SimpleRecord::Base
- sr_config :single_clob=>true
+ sr_config :single_clob=>true
- has_strings :name
+ has_strings :name
- has_clobs :clob1, :clob2
+ has_clobs :clob1, :clob2
end
View
16 test/test_validations.rb
@@ -15,20 +15,30 @@ class TestSimpleRecord < TestBase
def test_validations
mm = MyModel.new()
- assert mm.invalid?
+ puts 'invalid? ' + mm.invalid?.to_s
+ assert mm.invalid?, "mm is valid. invalid? returned #{mm.invalid?}"
assert mm.errors.size == 1
+ assert !mm.attr_before_create
+ assert !mm.valid?
assert mm.save == false, mm.errors.inspect
+ assert mm.attr_before_create
+ assert !mm.attr_after_save
+ assert !mm.attr_after_create
mm.name = "abcd"
- assert mm.valid?
+ assert mm.valid?, mm.errors.inspect
assert mm.errors.size == 0
mm.save_count = 2
assert mm.invalid?
mm.save_count = nil
-
+ assert mm.valid?
assert mm.save, mm.errors.inspect
+ p mm
+ assert mm.attr_after_save
+ assert mm.attr_after_create
+
assert mm.valid?, mm.errors.inspect
assert mm.save_count == 1
end
Please sign in to comment.
Something went wrong with that request. Please try again.