Module: DataMapper::Shim::ClassMethods

Defined in:
lib/data_mapper/shim.rb

Defined Under Namespace

Classes: Property

Constant Summary collapse

EmailAddress =

RFC2822 (No attribution reference available)

begin
  alpha = "a-zA-Z"
  digit = "0-9"
  atext = "[#{alpha}#{digit}\!\#\$\%\&\'\*+\/\=\?\^\_\`\{\|\}\~\-]"
  dot_atom_text = "#{atext}+([.]#{atext}*)*"
  dot_atom = "#{dot_atom_text}"
  qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
  text = "[\\x01-\\x09\\x11\\x12\\x14-\\x7f]"
  quoted_pair = "(\\x5c#{text})"
  qcontent = "(?:#{qtext}|#{quoted_pair})"
  quoted_string = "[\"]#{qcontent}+[\"]"
  atom = "#{atext}+"
  word = "(?:#{atom}|#{quoted_string})"
  obs_local_part = "#{word}([.]#{word})*"
  local_part = "(?:#{dot_atom}|#{quoted_string}|#{obs_local_part})"
  no_ws_ctl = "\\x01-\\x08\\x11\\x12\\x14-\\x1f\\x7f"
  dtext = "[#{no_ws_ctl}\\x21-\\x5a\\x5e-\\x7e]"
  dcontent = "(?:#{dtext}|#{quoted_pair})"
  domain_literal = "\\[#{dcontent}+\\]"
  obs_domain = "#{atom}([.]#{atom})*"
  domain = "(?:#{dot_atom}|#{domain_literal}|#{obs_domain})"
  addr_spec = "#{local_part}\@#{domain}"
  pattern = /^#{addr_spec}$/n
end

Instance Method Summary collapse

Instance Method Details

#after(event, callback = nil, &block) ⇒ Object

Callbacks



516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/data_mapper/shim.rb', line 516

def after(event, callback = nil, &block)
  case event
  when :create
    callback ? after_create(callback, &block) : after_create(&block)
  when :save
    callback ? after_save(callback, &block) : after_save(&block)
  when :destroy
    callback ? after_destroy(callback, &block) : after_destroy(&block)
  else
    raise "Implement `after #{event.inspect}` in DataMapper::Shim"
  end
end

#all(*args) ⇒ Object

Finders



159
160
161
162
163
164
165
# File 'lib/data_mapper/shim.rb', line 159

def all(*args)
  if args.empty?
    scoped
  else
    where(*args)
  end
end

#before(event, callback = nil, &block) ⇒ Object



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/data_mapper/shim.rb', line 529

def before(event, callback = nil, &block)
  case event
  when :create
    callback ? before_create(callback, &block) : before_create(&block)
  when :save
    callback ? before_save(callback, &block) : before_save(&block)
  when :destroy
    callback ? before_destroy(callback, &block) : before_destroy(&block)
  when :valid?
    # Per http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html,
    # before_validation callbacks in AR cause a #save call to fail if they
    # return false. Since this wasn't the case in DM, we need to wrap
    # before_validation callbacks in a proc that always returns true.
    if callback
      raise "Need to handle before_validation with callback AND block" unless block.nil?
      callback_with_true_return = proc do |*args|
        self.__send__ callback
        true
      end
      before_validation &callback_with_true_return
    else
      block_with_true_return = block && proc { |*args| self.instance_eval █ true }
      before_validation &block_with_true_return
    end
  when :update
    callback ? before_update(callback, &block) : before_update(&block)
  else
    raise "Add before case statement for #{event} event"
  end
end

#belongs_to(name, options = {}) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/data_mapper/shim.rb', line 478

def belongs_to(name, options = {})
  relationship_options = {}

  if options.has_key?(:nullable) && options.delete(:nullable) == false
    validates_presence_of name
  end

  if foreign_key = options.delete(:child_key)
    if foreign_key.is_a?(Enumerable) && foreign_key.length == 1
      foreign_key = foreign_key.first
    end

    relationship_options.merge! :foreign_key => foreign_key
  end

  if class_name = options.delete(:class_name)
    relationship_options.merge! :class_name => class_name
  end

  if foreign_key = options.delete(:parent_key)
    warn "Not handling parent_key options in belongs_to"
  end

  if inverse_of = options.delete(:inverse_of)
    relationship_options.merge! :inverse_of => inverse_of
  end

  if autosave = options.delete(:autosave)
    relationship_options.merge! :autosave => autosave
  end

  handle_leftover_options(options)
  attr_accessible name
  super name, relationship_options
end

#first(*args) ⇒ Object



167
168
169
170
171
172
173
# File 'lib/data_mapper/shim.rb', line 167

def first(*args)
  if args.empty?
    scoped.first
  else
    where(*args).first
  end
end

#get(*args) ⇒ Object



175
176
177
# File 'lib/data_mapper/shim.rb', line 175

def get(*args)
  find_by_id(*args)
end

#has(cardinality, name, options = {}) ⇒ Object

Relationships



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
# File 'lib/data_mapper/shim.rb', line 385

def has(cardinality, name, options = {})
  relationship_options = {}

  if class_name = options.delete(:class_name)
    relationship_options.merge! :class_name => class_name
  end

  if foreign_key = options.delete(:child_key)
    relationship_options.merge! :foreign_key => foreign_key
  end

  if key = options.delete(:association_foreign_key)
    relationship_options.merge! :association_foreign_key => key
  end

  if order = options.delete(:order)
    relationship_options.merge! :order => order
  end

  if inverse_of = options.delete(:inverse_of)
    relationship_options.merge! :inverse_of => inverse_of
  end

  if mutable = options.delete(:mutable)
    # no-op, ActiveRecord relationships are mutable by default
  end

 if constraint = options.delete(:constraint)
    # https://github.com/datamapper/dm-constraints for more information on
    # all possible values for :constraint
    case constraint
    when :protect
      relationship_options[:dependent] = :restrict

      # DataMapper returns false if a model can't be destroyed.
      # Here, we capture the exception AR raises if a model
      # can't be destroyed due to an association.
      self.instance_eval do
        define_method(:destroy) do |*args|
          begin
            super(*args)
          rescue ActiveRecord::DeleteRestrictionError => e
            false
          end
        end
      end
    when :destroy
      relationship_options[:dependent] = :destroy
    when :destroy!
      relationship_options[:dependent] = :delete_all
    when :set_nil
      relationship_options[:dependent] = :nullify
    when :skip
      # no-op
    end
  end

  if through = options.delete(:through)
    if through == Resource
      cardinality = -1
    else
      relationship_options.merge! :through => through
    end
  end

  case cardinality
  when -1
    if relationship_options.key?(:dependent)
      case dependent = relationship_options.delete(:dependent)
      when :destroy
        before_destroy do
          self.__send__(name).each do |record|
            record.destroy
          end
        end
      when :restrict
        warn "ActiveRecord's HABTM doesn't support :dependent => :restrict; implement relationship as a has_many :through instead"
      else
        raise "Missing implementation for :#{dependent} constraint on #{name} for #{self}"
      end
    end

    has_and_belongs_to_many name, relationship_options
  when 1
    has_one name, relationship_options
  when n
    has_many name, relationship_options
  end

  attr_accessible name
  handle_leftover_options(options)
end

#nObject

As in ‘has n, :messages’



125
126
127
# File 'lib/data_mapper/shim.rb', line 125

def n
  1/0.0
end

#propertiesObject



138
139
140
# File 'lib/data_mapper/shim.rb', line 138

def properties
  @__datamapper_shim_properties ||= Set.new
end

#property(name, type, options = {}) ⇒ Object

Model definition



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/data_mapper/shim.rb', line 180

def property(name, type, options = {})
  properties << Property.new(name, type)

  case
  when type == Boolean
    # property :trial, Boolean
    #
    # If the :trial column in the DB is created with TINYINT(4),
    # Rails doesn't map it to a boolean type,
    # so we need to coerce it here if necessary.
    define_method name do
      value = read_attribute(name)
      if value.is_a? Integer
        value.zero? ? false : true
      else
        value
      end
    end
  when type.is_a?(Enum)
    warn "Rails 4 handles enums out of the box."

    # Attribute accessors for the property
    self.instance_eval do
      define_method(name) do
        type[read_attribute(name)]
      end

      define_method("#{name}=") do |value|
        value = value.is_a?(Integer) ? value : type[value]
        write_attribute(name, value)
      end
    end

    @__datamapper_shim_enums ||= {}
    @__datamapper_shim_enums[name] = type

    # Substitute enum values in where clauses
    # Note, we don't define this on ActiveRecord::Relation
    def self.where(opts, *rest)
      @__datamapper_shim_enums.each do |name, enum|
        if opts.is_a?(Hash) && opts.has_key?(name) && !opts[name].is_a?(Integer)
          opts[name] = enum[opts[name]]
        end
      end

      super
    end
  when type == Json
    serialize name, JSON
  when type == List
    serialize name, List.new
  when type == ParanoidDateTime
    self.instance_eval do
      define_method :destroy do
        update_attribute(name, Time.zone.try(:now) || Time.now)
      end
    end

    default_scope where(:deleted_at => nil)

    def self.with_deleted
      self.unscoped.where("`#{self.table_name}`.deleted_at IS NOT NULL").scoping do
        yield if block_given?
      end
    end
  when type == Yaml
    serialize name
  end

  if type == DateTime || type == ParanoidDateTime
    # ActiveRecord maps datetime columns to TimeWithZone,
    # which can have some slight inconsistencies with DateTime
    self.instance_eval do
      define_method "#{name}" do
        read_attribute(name).try(:to_datetime)
      end
    end
  end

  if options.has_key?(:default)
    default = options.delete(:default)
    # :if => :class guarantees that the default value is always returned
    attr_default(name, :if => :class, :persisted => false) do |record|
      if record.new_record? && !record.__send__(:"#{name}_changed?")
        default.respond_to?(:call) ? default.call : default
      else
        record.instance_eval do
          read_attribute(name)
        end
      end
    end
  end

  if reader = options.delete(:reader)
    self.instance_eval do
      define_method name do
        read_attribute(name)
      end
    end

    case reader
    when :private
      private name
    when :protected
      protected name
    else
      raise "option :#{reader} for :reader not handled in shim"
    end
  end

  if writer = options.delete(:writer)
    self.instance_eval do
      define_method(:"#{name}=") do |value|
        write_attribute(name, value)
      end
    end

    case writer
    when :protected
      protected :"#{name}="
      attr_protected name
    when :private
      private :"#{name}="
      attr_protected name
    else
      raise "option :#{writer} for :writer not handled in shim"
    end
  else
    attr_accessible name
  end

  # http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Property
  # No validation necessary here, as these just create a database index.
  options.delete(:index)
  options.delete(:unique_index)

  # DataMapper does some default validation on certain datatypes, e.g.
  # Strings can't have a length longer than 50 chars. ActiveRecord doesn't
  # do any such validations, so we can ignore this option.
  options.delete(:auto_validation)

  # http://stackoverflow.com/questions/95061/stop-activerecord-from-loading-blob-column
  # No obvious way to lazily load an attribute
  options.delete(:lazy)

  # Primary keys

  if options.delete(:key)
    @__datamapper_shim_primary_keys ||= []
    @__datamapper_shim_primary_keys << name

    if @__datamapper_shim_primary_keys.length == 1
      self.primary_key = @__datamapper_shim_primary_keys.first
    else
      self.primary_keys = *@__datamapper_shim_primary_keys
    end

    validates_presence_of name
  end

  # Validations

  validation_options = {}

  if length = options.delete(:length) || options.delete(:size)
    validation_options.merge! :length => { :maximum => length }
  end

  if unique = options.delete(:unique)
    validation_options.merge! :uniqueness => true
  end

  if format = options.delete(:format)
    if format == :email_address
      validation_options.merge! :format => { :with => EmailAddress }
    else
      validation_options.merge! :format => { :with => format }
    end
  end

  # This needs to be checked last due to how
  # :allow_nil works.
  if options.has_key?(:nullable)
    if options.delete(:nullable) == false
      if type == Boolean
        # http://stackoverflow.com/questions/7781174/rspec-validation-failed-attribute-cant-be-blank-but-it-isnt-blank
        validation_options.merge! :inclusion => { :in => [true, false, 0, 1] }
      else
        validation_options.merge! :presence => true
      end
    else
      # Can't add an :allow_nil option unless there's an actual
      # validation happening.
      unless validation_options.empty?
        validation_options.merge! :allow_nil => true
      end
    end
  end

  validates(name, validation_options) unless validation_options.empty?
  handle_leftover_options(options)
end

#storage_namesObject



142
143
144
145
146
147
148
149
150
# File 'lib/data_mapper/shim.rb', line 142

def storage_names
  storage = Object.new
  storage.instance_variable_set :@model, self

  def storage.[]=(repo, name)
    @model.table_name = name
  end
  storage
end

#timestamps(suffix) ⇒ Object



152
153
154
155
# File 'lib/data_mapper/shim.rb', line 152

def timestamps(suffix)
  # ActiveRecord handles timestamps (created_at, updated_at)
  # automatically if the columns exist.
end

#validates_format(name, options = {}) ⇒ Object



657
658
659
660
661
662
663
664
665
666
# File 'lib/data_mapper/shim.rb', line 657

def validates_format(name, options = {})
  validation_options = {}

  if with = options.delete(:with)
    validation_options.merge! :format => { :with => with }
  end

  validates name, validation_options
  handle_leftover_options(options)
end

#validates_is_confirmed(name, options = {}) ⇒ Object



631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/data_mapper/shim.rb', line 631

def validates_is_confirmed(name, options = {})
  confirmation_options = { }

  if message = options.delete(:message)
    confirmation_options.merge! :message => message
  end

  if condition = options.delete(:if)
    confirmation_options.merge! :if => condition
  end

  validates name, :confirmation => confirmation_options
  validates :"#{name}_confirmation", :presence => true, :if => confirmation_options[:if]

  handle_leftover_options(options)
end

#validates_is_unique(name, options = {}) ⇒ Object



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/data_mapper/shim.rb', line 585

def validates_is_unique(name, options = {})
  validation_options = { :uniqueness => true }

  if options.delete(:allow_nil)
    validation_options.merge! :allow_nil => true
  end

  if scope = options.delete(:scope)
    validation_options.merge! :uniqueness => { :scope => scope }
  end

  if condition = options.delete(:if)
    validation_options.merge! :if => condition
  end

  validates name, validation_options
  handle_leftover_options(options)
end

#validates_length(name, options) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/data_mapper/shim.rb', line 604

def validates_length(name, options)
  validation_options = {}

  if max = options.delete(:max)
    validation_options.merge! :maximum => max
  end

  if max = options.delete(:maximum)
    validation_options.merge! :maximum => max
  end

  if min = options.delete(:min)
    validation_options.merge! :minimum => min
  end

  if condition = options.delete(:if)
    validation_options.merge! :if => condition
  end

  if message = options.delete(:message)
    validation_options.merge! :message => message
  end

  validates name, :length => validation_options
  handle_leftover_options(options)
end

#validates_present(name, options = {}) ⇒ Object

Validations



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/data_mapper/shim.rb', line 562

def validates_present(name, options = {})
  validation_options = {}

  if message = options.delete(:message)
    validation_options.merge! :message => message
  end

  if condition = options.delete(:if)
    validation_options.merge! :if => condition
  end

  if on = options.delete(:when)
    if on.length > 1
      raise "Can't handle :when option with more than one value (had #{on})"
    else
      validation_options.merge! :on => on.first
    end
  end

  validates name, :presence => validation_options
  handle_leftover_options(options)
end

#validates_with_block(name, &block) ⇒ Object



648
649
650
651
652
653
654
655
# File 'lib/data_mapper/shim.rb', line 648

def validates_with_block(name, &block)
  validates_each name do |record, property_name|
    valid, error_message = record.instance_exec(record.__send__(property_name), &block)
    unless valid
      record.errors.add(name, error_message)
    end
  end
end

#validates_with_method(name, options) ⇒ Object



679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/data_mapper/shim.rb', line 679

def validates_with_method(name, options)
  validation_options = {}

  if on = options.delete(:when)
    case on
    when Array
      if on.length > 1
        raise "Can't handle :when option with more than one value (had #{on})"
      else
        validation_options.merge! :on => on.first
      end
    else
      validation_options.merge! :on => on
    end
  end

  method = options.delete(:method)

  # Validation methods made for DM return either true if the model validation passed,
  # or [false, "error message"] if validation failed. Here we add the error message to
  # the model's ActiveModel::Errors object.
  block = proc do
    valid, error_message = self.__send__ method
    unless valid
      self.errors.add(name, error_message)
    end
  end

  validate validation_options, &block
  handle_leftover_options(options)
end

#validates_within(name, options = {}) ⇒ Object



668
669
670
671
672
673
674
675
676
677
# File 'lib/data_mapper/shim.rb', line 668

def validates_within(name, options = {})
  validation_options = {}

  if set = options.delete(:set)
    validation_options.merge! :inclusion => { :in => set }
  end

  validates name, validation_options
  handle_leftover_options(options)
end