Class: SimpleRecord::Base

Inherits:
ActiveSdb::Base show all
Extended by:
ActiveModel::Callbacks, ActiveModel::Naming, Attributes::ClassMethods, Logging::ClassMethods, Sharding::ClassMethods
Includes:
ActiveModel::Conversion, ActiveModel::Validations, ActiveModel::Validations::Callbacks, Attributes, Callbacks, Callbacks3, Json, Logging, Sharding, Translations, Validations
Defined in:
lib/simple_record.rb

Constant Summary collapse

@@active_model =
false
@@cache_store =
nil
@@regex_no_id =
/.*Couldn't find.*with ID.*/
@@debug =
""

Class Attribute Summary collapse

Instance Attribute Summary collapse

Attributes inherited from ActiveSdb::Base

#attributes, #id

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Attributes::ClassMethods

are_booleans, are_dates, are_floats, are_ints, belongs_to, define_dirty_methods, defined_attributes, get_sr_config, has_attributes, has_attributes2, has_booleans, has_clobs, has_dates, has_floats, has_ints, has_many, has_one, has_strings, has_virtuals, sr_config

Methods included from Sharding::ClassMethods

find_sharded, is_sharded?, prefix_shard_name, shard, sharded_domains, sharding_options, shards

Methods included from Logging::ClassMethods

usage_line, write_usage

Methods included from Json

#as_json, included

Methods included from Sharding

included, #sharded_domain

Methods included from Attributes

#get_attribute, #get_attribute_sdb, handle_virtuals, included, #set, #set_attribute_sdb

Methods included from Translations

#convert_dates_to_sdb, decrypt, encrypt, from_float, pad_and_offset, #pad_and_offset_ints_to_sdb, pass_hash, pass_hash_check, #ruby_to_sdb, #ruby_to_string_val, #sdb_to_ruby, #string_val_to_ruby, #to_bool, #to_date, un_offset_int, #unpad, #unpad_self, #wrap_if_required

Methods included from Validations

included, #invalid?, #read_attribute_for_validation, #valid?, #validate, #validate_on_create, #validate_on_update

Methods included from Callbacks

#after_destroy, #before_destroy, included, setup_callbacks

Methods inherited from ActiveSdb::Base

#apres_save2, #connection, connection, create_domain, #delete_attributes, delete_domain, #delete_values, find_with_metadata, generate_id, #mark_as_old, #pre_save2, #put, #put_attributes, #reload_attributes, #save2, #save_attributes

Methods included from ActiveSdb::ActiveSdbConnect

#close_connection, #connection, #establish_connection

Constructor Details

#initialize(attrs = {}) ⇒ Base

Returns a new instance of Base.



216
217
218
219
220
221
222
223
224
225
# File 'lib/simple_record.rb', line 216

def initialize(attrs={})
  # todo: Need to deal with objects passed in. iterate through belongs_to perhaps and if in attrs, set the objects id rather than the object itself

  initialize_base(attrs)

  # Convert attributes to sdb values
  attrs.each_pair do |name, value|
    set(name, value, true)
  end
end

Class Attribute Details

.domain_prefixObject

Returns the value of attribute domain_prefix.



279
280
281
# File 'lib/simple_record.rb', line 279

def domain_prefix
  @domain_prefix
end

Instance Attribute Details

#errorsObject

Returns the value of attribute errors.



196
197
198
# File 'lib/simple_record.rb', line 196

def errors
  @errors
end

Class Method Details

.all(*args) ⇒ Object



1001
1002
1003
# File 'lib/simple_record.rb', line 1001

def self.all(*args)
  find(:all, *args)
end

.batch_delete(objects, options = {}) ⇒ Object

Pass in an array of objects



796
797
798
799
800
801
# File 'lib/simple_record.rb', line 796

def self.batch_delete(objects, options={})
  if objects
    # 25 item limit, we should maybe handle this limit in here.
    connection.batch_delete_attributes @domain, objects.collect { |x| x.id }
  end
end

.batch_save(objects, options = {}) ⇒ Object

Run pre_save on each object, then runs batch_put_attributes Returns



770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/simple_record.rb', line 770

def self.batch_save(objects, options={})
  options[:create_domain] = true if options[:create_domain].nil?
  results = []
  to_save = []
  if objects && objects.size > 0
    objects.each do |o|
      ok = o.pre_save(options)
      raise "Pre save failed on object [" + o.inspect + "]" if !ok
      results << ok
      next if !ok # todo: this shouldn't be here should it?  raises above
      o.pre_save2
      to_save << Aws::SdbInterface::Item.new(o.id, o.attributes, true)
      if to_save.size == 25 # Max amount SDB will accept
        connection.batch_put_attributes(domain, to_save, options)
        to_save.clear
      end
    end
  end
  connection.batch_put_attributes(domain, to_save, options) if to_save.size > 0
  objects.each do |o|
    o.save_lobs(nil)
  end
  results
end

.cache_key(class_name, id) ⇒ Object



1065
1066
1067
# File 'lib/simple_record.rb', line 1065

def self.cache_key(class_name, id)
  return class_name + "/" + id.to_s
end

.cache_results(results) ⇒ Object



1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
# File 'lib/simple_record.rb', line 1044

def self.cache_results(results)
  if !cache_store.nil? && !results.nil?
    if results.is_a?(Array)
      # todo: cache each result
      results.each do |item|
        class_name = item.class.name
        id         = item.id
        cache_key  = self.cache_key(class_name, id)
        #puts 'caching result at ' + cache_key + ': ' + results.inspect
        cache_store.write(cache_key, item, :expires_in =>30)
      end
    else
      class_name = results.class.name
      id         = results.id
      cache_key  = self.cache_key(class_name, id)
      #puts 'caching result at ' + cache_key + ': ' + results.inspect
      cache_store.write(cache_key, results, :expires_in =>30)
    end
  end
end

.cache_storeObject



290
291
292
# File 'lib/simple_record.rb', line 290

def self.cache_store
  return @@cache_store
end

.cache_store=(cache) ⇒ Object

Set the cache to use



286
287
288
# File 'lib/simple_record.rb', line 286

def self.cache_store=(cache)
  @@cache_store = cache
end

.convert_condition_params(options) ⇒ Object



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/simple_record.rb', line 1031

def self.convert_condition_params(options)
  return if options.nil?
  conditions = options[:conditions]
  return if conditions.nil?
  if conditions.size > 1
    # all after first are values
    conditions.collect! { |x|
      Translations.pad_and_offset(x)
    }
  end

end

.count(*args) ⇒ Object



1009
1010
1011
# File 'lib/simple_record.rb', line 1009

def self.count(*args)
  find(:count, *args)
end

.create(attributes = {}) ⇒ Object



548
549
550
551
# File 'lib/simple_record.rb', line 548

def self.create(attributes={})
#            puts "About to create in domain #{domain}"
  super
end

.create!(attributes = {}) ⇒ Object



553
554
555
556
557
# File 'lib/simple_record.rb', line 553

def self.create!(attributes={})
  item = self.new(attributes)
  item.save!
  item
end

.debugObject



1071
1072
1073
# File 'lib/simple_record.rb', line 1071

def self.debug
  @@debug
end

.delete(id) ⇒ Object

Usage: ClassName.delete id



806
807
808
809
# File 'lib/simple_record.rb', line 806

def self.delete(id)
  connection.delete_attributes(domain, id)
  @deleted = true
end

.delete_all(options) ⇒ Object

Pass in the same OPTIONS you’d pass into a find(:all, OPTIONS)



812
813
814
815
816
817
818
819
820
821
# File 'lib/simple_record.rb', line 812

def self.delete_all(options)
  # could make this quicker by just getting item_names and deleting attributes rather than creating objects
  obs = self.find(:all, options)
  i   = 0
  obs.each do |a|
    a.delete
    i+=1
  end
  return i
end

.destroy_all(options) ⇒ Object

Pass in the same OPTIONS you’d pass into a find(:all, OPTIONS)



824
825
826
827
828
829
830
831
832
# File 'lib/simple_record.rb', line 824

def self.destroy_all(options)
  obs = self.find(:all, options)
  i   = 0
  obs.each do |a|
    a.destroy
    i+=1
  end
  return i
end

.domainObject



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/simple_record.rb', line 315

def self.domain
  unless @domain
    # This strips off the module if there is one.
    n2 = name.split('::').last || name
#                puts 'n2=' + n2
    if n2.respond_to?(:tableize)
      @domain = n2.tableize
    else
      @domain = n2.downcase
    end
    set_domain_name @domain
  end
  domain_name_for_class = (SimpleRecord::Base.domain_prefix || "") + @domain.to_s
  domain_name_for_class
end

.extended(base) ⇒ Object



212
213
214
# File 'lib/simple_record.rb', line 212

def self.extended(base)

end

.find(*params) ⇒ Object

Usage: Find by ID:

MyModel.find(ID)

Query example:

MyModel.find(:all, :conditions=>["name = ?", name], :order=>"created desc", :limit=>10)

Extra options:

:per_token => the number of results to return per next_token, max is 2500.
:consistent_read => true/false  --  as per http://developer.amazonwebservices.com/connect/entry.jspa?externalID=3572
:retries => maximum number of times to retry this query on an error response.
:shard => shard name or array of shard names to use on this query.


920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
# File 'lib/simple_record.rb', line 920

def self.find(*params)
  #puts 'params=' + params.inspect

  q_type           = :all
  select_attributes=[]
  if params.size > 0
    q_type = params[0]
  end
  options = {}
  if params.size > 1
    options = params[1]
  end
  conditions = options[:conditions]
  if conditions && conditions.is_a?(String)
    conditions           = [conditions]
    options[:conditions] = conditions
  end

  if !options[:shard_find] && is_sharded?
    # then break off and get results across all shards
    return find_sharded(*params)
  end

  # Pad and Offset number attributes
  params_dup = params.dup
  if params.size > 1
    options = params[1]
    #puts 'options=' + options.inspect
    #puts 'after collect=' + options.inspect
    convert_condition_params(options)
    per_token       = options[:per_token]
    consistent_read = options[:consistent_read]
    if per_token || consistent_read then
      op_dup                   = options.dup
      op_dup[:limit]           = per_token # simpledb uses Limit as a paging thing, not what is normal
      op_dup[:consistent_read] = consistent_read
      params_dup[1]            = op_dup
    end
  end
#            puts 'params2=' + params.inspect

  ret = q_type == :all ? [] : nil
  begin
    results=(*params_dup)
#                puts "RESULT=" + results.inspect
    write_usage(:select, domain, q_type, options, results)
    #puts 'params3=' + params.inspect
    SimpleRecord.stats.selects += 1
    if q_type == :count
      ret = results[:count]
    elsif q_type == :first
      ret = results[:items].first
      # todo: we should store request_id and box_usage with the object maybe?
      cache_results(ret)
    elsif results[:single]
      ret = results[:single]
      cache_results(ret)
    else
      if results[:items] #.is_a?(Array)
        cache_results(results[:items])
        ret = SimpleRecord::ResultsArray.new(self, params, results, next_token)
      end
    end
  rescue Aws::AwsError, SimpleRecord::ActiveSdb::ActiveSdbError => ex
#                puts "RESCUED: " + ex.message
    if (ex.message().index("NoSuchDomain") != nil)
      # this is ok
    elsif (ex.message() =~ @@regex_no_id)
      ret = nil
    else
      raise ex
    end
  end
#            puts 'single2=' + ret.inspect
  return ret
end

.first(*args) ⇒ Object



1005
1006
1007
# File 'lib/simple_record.rb', line 1005

def self.first(*args)
  find(:first, *args)
end

.get_encryption_keyObject



692
693
694
695
696
697
698
699
# File 'lib/simple_record.rb', line 692

def self.get_encryption_key()
  key = SimpleRecord.options[:encryption_key]
#            if key.nil?
#                puts 'WARNING: Encrypting attributes with your AWS Access Key. You should use your own :encryption_key so it doesn\'t change'
#                key = connection.aws_access_key_id # default to aws access key. NOT recommended in case you start using a new key
#            end
  return key
end

.inherited(base) ⇒ Object



251
252
253
254
255
256
257
258
259
260
# File 'lib/simple_record.rb', line 251

def self.inherited(base)
#      puts 'SimpleRecord::Base is inherited by ' + base.inspect
  Callbacks.setup_callbacks(base)

#            base.has_strings :id
  base.has_dates :created, :updated
  base.before_create :set_created, :set_updated
  base.before_update :set_updated

end

.paginate(options = {}) ⇒ Object

This gets less and less efficient the higher the page since SimpleDB has no way to start at a specific row. So it will iterate from the first record and pull out the specific pages.



1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/simple_record.rb', line 1015

def self.paginate(options={})
#            options = args.pop
#            puts 'paginate options=' + options.inspect if SimpleRecord.logging?
  page               = options[:page] || 1
  per_page           = options[:per_page] || 50
#            total    = options[:total_entries].to_i
  options[:page]     = page.to_i # makes sure it's to_i
  options[:per_page] = per_page.to_i
  options[:limit]    = options[:page] * options[:per_page]
#            puts 'paging options=' + options.inspect
  fr                 = find(:all, options)
  return fr

end

.quote_regexp(a, re) ⇒ Object



885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
# File 'lib/simple_record.rb', line 885

def self.quote_regexp(a, re)
  a =~ re
  #was there a match?
  if $&
    before=$`
    middle=$&
    after =$'

    before =~ /'$/ #is there already a quote immediately before the match?
    unless $&
      return "#{before}'#{middle}'#{quote_regexp(after, re)}" #if not, put quotes around the match
    else
      return "#{before}#{middle}#{quote_regexp(after, re)}" #if so, assume it is quoted already and move on
    end
  else
    #no match, just return the string
    return a
  end
end

.sanitize_sql(*params) ⇒ Object



1075
1076
1077
# File 'lib/simple_record.rb', line 1075

def self.sanitize_sql(*params)
  return ActiveRecord::Base.sanitize_sql(*params)
end

.select(*params) ⇒ Object



997
998
999
# File 'lib/simple_record.rb', line 997

def self.select(*params)
  return find(*params)
end

.set_domain_name(table_name) ⇒ Object

Sets the domain name for this class



306
307
308
# File 'lib/simple_record.rb', line 306

def self.set_domain_name(table_name)
  super
end

.set_domain_prefix(prefix) ⇒ Object

If you want a domain prefix for all your models, set it here.



295
296
297
298
# File 'lib/simple_record.rb', line 295

def self.set_domain_prefix(prefix)
  #puts 'set_domain_prefix=' + prefix
  self.domain_prefix = prefix
end

.set_table_name(table_name) ⇒ Object

Same as set_table_name



301
302
303
# File 'lib/simple_record.rb', line 301

def self.set_table_name(table_name)
  set_domain_name table_name
end

.table_nameObject



1079
1080
1081
# File 'lib/simple_record.rb', line 1079

def self.table_name
  return domain
end

Instance Method Details

#[](attribute) ⇒ Object



396
397
398
# File 'lib/simple_record.rb', line 396

def [](attribute)
  super
end

#[]=(attribute, values) ⇒ Object



391
392
393
394
# File 'lib/simple_record.rb', line 391

def []=(attribute, values)
  make_dirty(attribute, values)
  super
end

#after_save_cleanupObject



1098
1099
1100
# File 'lib/simple_record.rb', line 1098

def after_save_cleanup
  @dirty = {}
end

#cache_storeObject



420
421
422
# File 'lib/simple_record.rb', line 420

def cache_store
  @@cache_store
end

#changedObject



1083
1084
1085
# File 'lib/simple_record.rb', line 1083

def changed
  return @dirty.keys
end

#changed?Boolean

Returns:

  • (Boolean)


1087
1088
1089
# File 'lib/simple_record.rb', line 1087

def changed?
  return @dirty.size > 0
end

#changesObject



1091
1092
1093
1094
1095
1096
# File 'lib/simple_record.rb', line 1091

def changes
  ret = {}
  #puts 'in CHANGES=' + @dirty.inspect
  @dirty.each_pair { |key, value| ret[key] = [value, get_attribute(key)] }
  return ret
end

#clear_errorsObject



383
384
385
386
387
388
389
# File 'lib/simple_record.rb', line 383

def clear_errors
  if defined?(ActiveModel)
    @errors = ActiveModel::Errors.new(self)
  else
    @errors=SimpleRecord_errors.new
  end
end

#createObject

:nodoc:



515
516
517
518
519
520
521
522
523
524
# File 'lib/simple_record.rb', line 515

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

#create_or_updateObject

:nodoc:



504
505
506
507
508
509
510
511
512
513
# File 'lib/simple_record.rb', line 504

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

#created_atObject

an aliased method since many people use created_at/updated_at naming convention



410
411
412
# File 'lib/simple_record.rb', line 410

def created_at
  self.created
end

#defined_attributes_localObject



271
272
273
274
275
# File 'lib/simple_record.rb', line 271

def defined_attributes_local
  # todo: store this somewhere so it doesn't keep going through this
  ret = self.class.defined_attributes
  ret.merge!(self.class.superclass.defined_attributes) if self.class.superclass.respond_to?(:defined_attributes)
end

#delete(options = {}) ⇒ Object



834
835
836
837
838
839
840
841
842
# File 'lib/simple_record.rb', line 834

def delete(options={})
  if self.class.is_sharded?
    options[:domain] = sharded_domain
  end
  super(options)

  # delete lobs now too
  delete_lobs
end

#delete_lobsObject



615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/simple_record.rb', line 615

def delete_lobs
  defined_attributes_local.each_pair do |k, v|
    if v.type == :clob
      if self.class.get_sr_config[:single_clob]
        s3_bucket(false, :s3_bucket=>:new).delete_key(single_clob_id)
        SimpleRecord.stats.s3_deletes += 1
        return
      else
        s3_bucket.delete_key(s3_lob_id(k))
        SimpleRecord.stats.s3_deletes += 1
      end
    end
  end
end

#delete_niled(to_delete) ⇒ Object



854
855
856
857
858
859
860
861
862
863
864
865
866
867
# File 'lib/simple_record.rb', line 854

def delete_niled(to_delete)
#            puts 'to_delete=' + to_delete.inspect
  if to_delete.size > 0
#      puts 'Deleting attributes=' + to_delete.inspect
    SimpleRecord.stats.deletes += 1
    delete_attributes to_delete
    to_delete.each do |att|
      att_meta = get_att_meta(att)
      if att_meta.type == :clob
        s3_bucket.key(s3_lob_id(att)).delete
      end
    end
  end
end

#destroyObject



844
845
846
847
848
849
850
851
852
# File 'lib/simple_record.rb', line 844

def destroy
  if @@active_model
    _run_destroy_callbacks do
      delete
    end
  else
    return run_before_destroy && delete && run_after_destroy
  end
end

#destroyed?Boolean

Returns:

  • (Boolean)


267
268
269
# File 'lib/simple_record.rb', line 267

def destroyed?
  @deleted
end

#domainObject



311
312
313
# File 'lib/simple_record.rb', line 311

def domain
  self.class.domain
end

#domain_ok(ex, options = {}) ⇒ Object



424
425
426
427
428
429
430
431
# File 'lib/simple_record.rb', line 424

def domain_ok(ex, options={})
  if (ex.message().index("NoSuchDomain") != nil)
    dom = options[:domain] || domain
    self.class.create_domain(dom)
    return true
  end
  return false
end

#get_att_meta(name) ⇒ Object



336
337
338
339
340
341
342
343
# File 'lib/simple_record.rb', line 336

def get_att_meta(name)
  name_s   = name.to_s
  att_meta = defined_attributes_local[name.to_sym]
  if att_meta.nil? && has_id_on_end(name_s)
    att_meta = defined_attributes_local[name_s[0..-4].to_sym]
  end
  return att_meta
end

#get_atts_to_deleteObject



750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/simple_record.rb', line 750

def get_atts_to_delete
  to_delete = []
  changes.each_pair do |key, v|
    if v[1].nil?
      to_delete << key
      @attributes.delete(key)
    end
  end
#            @attributes.each do |key, value|
##                puts 'key=' + key.inspect + ' value=' + value.inspect
#                if value.nil? || (value.is_a?(Array) && value.size == 0) || (value.is_a?(Array) && value.size == 1 && value[0] == nil)
#                    to_delete << key
#                    @attributes.delete(key)
#                end
#            end
  return to_delete
end

#has_id_on_end(name_s) ⇒ Object



331
332
333
334
# File 'lib/simple_record.rb', line 331

def has_id_on_end(name_s)
  name_s = name_s.to_s
  name_s.length > 3 && name_s[-3..-1] == "_id"
end

#hashObject



1102
1103
1104
1105
# File 'lib/simple_record.rb', line 1102

def hash
  # same as ActiveRecord
  id.hash
end

#initialize_base(attrs = {}) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/simple_record.rb', line 227

def initialize_base(attrs={})

  #we have to handle the virtuals.
  Attributes.handle_virtuals(attrs)

  clear_errors

  @dirty         = {}

  @attributes    = {} # sdb values
  @attributes_rb = {} # ruby values
  @lobs          = {}
  @new_record    = true

end

#initialize_from_db(attrs = {}) ⇒ Object



243
244
245
246
247
248
# File 'lib/simple_record.rb', line 243

def initialize_from_db(attrs={})
  initialize_base(attrs)
  attrs.each_pair do |k, v|
    @attributes[k.to_s] = v
  end
end

#is_dirty?(name) ⇒ Boolean

Returns:

  • (Boolean)


645
646
647
648
649
650
# File 'lib/simple_record.rb', line 645

def is_dirty?(name)
  # todo: should change all the dirty stuff to symbols?
#            puts '@dirty=' + @dirty.inspect
#            puts 'name=' +name.to_s
  @dirty.include? name.to_s
end

#make_dirty(arg, value) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/simple_record.rb', line 367

def make_dirty(arg, value)
  sdb_att_name = sdb_att_name(arg)
  arg          = arg.to_s

#            puts "Marking #{arg} dirty with #{value}" if SimpleRecord.logging?
  if @dirty.include?(sdb_att_name)
    old = @dirty[sdb_att_name]
#                puts "#{sdb_att_name} was already dirty #{old}"
    @dirty.delete(sdb_att_name) if value == old
  else
    old = get_attribute(arg)
#                puts "dirtifying #{sdb_att_name} old=#{old.inspect} to new=#{value.inspect}" if SimpleRecord.logging?
    @dirty[sdb_att_name] = old if value != old
  end
end

#new_record?Boolean

Returns:

  • (Boolean)


434
435
436
437
# File 'lib/simple_record.rb', line 434

def new_record?
  # todo: new_record in activesdb should align with how we're defining a new record here, ie: if id is nil
  super
end

#old_saveObject

Options:

- :except => Array of attributes to NOT save
- :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.


494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/simple_record.rb', line 494

def save(options={})
  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
  if options[:dirty]
#                puts '@dirtyA=' + @dirty.inspect
    return true if @dirty.size == 0 # Nothing to save so skip it
  end
  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
      if options[:dirty]
#                        puts '@dirty=' + @dirty.inspect
        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


      if self.class.is_sharded?
        options[:domain] = sharded_domain
      end

      if @@active_model
        x = save_super(dirty, is_create, options, to_delete)
#            puts 'save_super result = ' + x.to_s
        return x
      else
#            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

#persisted?Boolean

Returns:

  • (Boolean)


263
264
265
# File 'lib/simple_record.rb', line 263

def persisted?
  !@new_record && !destroyed?
end

#pre_save(options) ⇒ Object



701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/simple_record.rb', line 701

def pre_save(options)


  ok        = true
  is_create = self[:id].nil?
  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
#
##      puts 'AFTER VALIDATIONS, ERRORS=' + errors.inspect
#      if (!errors.nil? && errors.size > 0)
##        puts 'THERE ARE ERRORS, returning false'
#        return false
#      end

  unless @@active_model
    ok = run_after_validation && (is_create ? run_after_validation_on_create : run_after_validation_on_update)
    return false unless ok
  end

  # 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
    if ok
      ok = run_before_save && (is_create ? run_before_create : run_before_update)
    end
  else

  end
  prepare_for_update
  ok
end

#put_lob(k, val, options = {}) ⇒ Object



631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/simple_record.rb', line 631

def put_lob(k, val, options={})
  begin
    s3_bucket(false, options).put(k, val)
  rescue Aws::AwsError => ex
    if ex.include? /NoSuchBucket/
      s3_bucket(true, options).put(k, val)
    else
      raise ex
    end
  end
  SimpleRecord.stats.s3_puts += 1
end

#reloadObject



869
870
871
# File 'lib/simple_record.rb', line 869

def reload
  super()
end

#s3Object



652
653
654
655
656
657
658
# File 'lib/simple_record.rb', line 652

def s3

  return SimpleRecord.s3 if SimpleRecord.s3
  # todo: should optimize this somehow, like use the same connection_mode as used in SR
  # or keep open while looping in ResultsArray.
  Aws::S3.new(SimpleRecord.aws_access_key, SimpleRecord.aws_secret_key)
end

#s3_bucket(create = false, options = {}) ⇒ Object

options:

:s3_bucket => :old/:new/"#{any_bucket_name}". :new if want to use new bucket. Defaults to :old for backwards compatability.


662
663
664
# File 'lib/simple_record.rb', line 662

def s3_bucket(create=false, options={})
  s3.bucket(s3_bucket_name(options[:s3_bucket]), create)
end

#s3_bucket_name(s3_bucket_option = :old) ⇒ Object



666
667
668
669
670
671
672
673
674
675
676
# File 'lib/simple_record.rb', line 666

def s3_bucket_name(s3_bucket_option=:old)
  if s3_bucket_option == :new || SimpleRecord.options[:s3_bucket] == :new
    # this is the bucket that will be used going forward for anything related to s3
    ret = "simple_record_#{SimpleRecord.aws_access_key}"
  elsif !SimpleRecord.options[:s3_bucket].nil? && SimpleRecord.options[:s3_bucket] != :old
    ret = SimpleRecord.options[:s3_bucket]
  else
    ret = SimpleRecord.aws_access_key + "_lobs"
  end
  ret
end

#s3_lob_id(name) ⇒ Object



678
679
680
681
682
683
684
685
# File 'lib/simple_record.rb', line 678

def s3_lob_id(name)
  # if s3_bucket is not nil and not :old, then we use the new key.
  if !SimpleRecord.options[:s3_bucket].nil? && SimpleRecord.options[:s3_bucket] != :old
    "lobs/#{self.id}_#{name}"
  else
    self.id + "_" + name.to_s
  end
end

#save(options = {}) ⇒ Object

Options:

- :except => Array of attributes to NOT save
- :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.


448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/simple_record.rb', line 448

def save(options={})
  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
  if options[:dirty]
#                puts '@dirtyA=' + @dirty.inspect
    return true if @dirty.size == 0 # Nothing to save so skip it
  end
  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
      if options[:dirty]
#                        puts '@dirty=' + @dirty.inspect
        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


      if self.class.is_sharded?
        options[:domain] = sharded_domain
      end

      if @@active_model
        x = save_super(dirty, is_create, options, to_delete)
#            puts 'save_super result = ' + x.to_s
        return x
      else
#            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

#save!(options = {}) ⇒ Object



539
540
541
# File 'lib/simple_record.rb', line 539

def save!(options={})
  save(options) || raise(RecordNotSaved.new(self))
end

#save_lobs(dirty = nil) ⇒ Object



582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
# File 'lib/simple_record.rb', line 582

def save_lobs(dirty=nil)
#            puts 'dirty.inspect=' + dirty.inspect
  dirty = @dirty if dirty.nil?
  all_clobs   = {}
  dirty_clobs = {}
  defined_attributes_local.each_pair do |k, v|
    # collect up the clobs in case it's a single put
    if v.type == :clob
      val          = @lobs[k]
      all_clobs[k] = val
      if dirty.include?(k.to_s)
        dirty_clobs[k] = val
      else
#                        puts 'NOT DIRTY'
      end

    end
  end
  if dirty_clobs.size > 0
    if self.class.get_sr_config[:single_clob]
      # all clobs in one chunk
      # using json for now, could change later
      val = all_clobs.to_json
      puts 'val=' + val.inspect
      put_lob(single_clob_id, val, :s3_bucket=>:new)
    else
      dirty_clobs.each_pair do |k, val|
        put_lob(s3_lob_id(k), val)
      end
    end
  end
end

#save_super(dirty, is_create, options, to_delete) ⇒ Object



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/simple_record.rb', line 560

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

#save_with_validation!(options = {}) ⇒ Object

this is a bit wonky, save! should call this, not sure why it’s here.



544
545
546
# File 'lib/simple_record.rb', line 544

def save_with_validation!(options={})
  save!
end

#sdb_att_name(name) ⇒ Object



345
346
347
348
349
350
351
# File 'lib/simple_record.rb', line 345

def sdb_att_name(name)
  att_meta = get_att_meta(name)
  if att_meta.type == :belongs_to && !has_id_on_end(name.to_s)
    return "#{name}_id"
  end
  name.to_s
end

#set_createdObject



401
402
403
# File 'lib/simple_record.rb', line 401

def set_created
  set(SimpleRecord.options[:created_col] || :created, Time.now)
end

#set_updatedObject



405
406
407
# File 'lib/simple_record.rb', line 405

def set_updated
  set(SimpleRecord.options[:updated_col] || :updated, Time.now)
end

#single_clob_idObject



687
688
689
# File 'lib/simple_record.rb', line 687

def single_clob_id
  "lobs/#{self.id}_single_clob"
end

#strip_array(arg) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/simple_record.rb', line 353

def strip_array(arg)
  if arg.is_a? Array
    if arg.length==1
      ret = arg[0]
    else
      ret = arg
    end
  else
    ret = arg
  end
  return ret
end

#updateObject

:nodoc:



527
528
529
530
531
532
533
534
535
536
# File 'lib/simple_record.rb', line 527

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

#update_attributes(atts) ⇒ Object



874
875
876
877
# File 'lib/simple_record.rb', line 874

def update_attributes(atts)
  set_attributes(atts)
  save
end

#update_attributes!(atts) ⇒ Object



879
880
881
882
# File 'lib/simple_record.rb', line 879

def update_attributes!(atts)
  set_attributes(atts)
  save!
end

#updated_atObject

an aliased method since many people use created_at/updated_at naming convention



415
416
417
# File 'lib/simple_record.rb', line 415

def updated_at
  self.updated
end