Module: Mcfly::Model::ClassMethods

Defined in:
lib/mcfly/has_mcfly.rb

Instance Method Summary collapse

Instance Method Details

#has_mcfly(options = {}) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mcfly/has_mcfly.rb', line 27

def has_mcfly(options = {})
  # FIXME: this methods gets a append_only option sometimes.  It
  # needs to add model level validations which prevent update
  # when this option is present. Note that we need to allow
  # delete.  Deletion of Mcfly objects obsoletes them by setting
  # obsoleted_dt.

  send :include, InstanceMethods
  before_validation :record_validation

  # FIXME: :created_dt should also be readonly.  However, we set
  # it for debugging purposes.  Should consider making this
  # readonly once we're in production.  Also, :user_id should be
  # read-only.  We should only set whodunnit and let PostgreSQL
  # set it.
  attr_readonly :group_id, :obsoleted_dt, :o_user_id #, :user_id
end

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



76
77
78
79
# File 'lib/mcfly/has_mcfly.rb', line 76

def mcfly_belongs_to(name, options = {})
  validates_with Mcfly::Model::AssociationValidator, field: name
  belongs_to(name, options)
end

#mcfly_lookup(name, options = {}, &block) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/mcfly/has_mcfly.rb', line 45

def mcfly_lookup(name, options = {}, &block)
  delorean_fn(name, options) do |ts, *args|
    raise "time cannot be nil" if ts.nil?
    self.where("obsoleted_dt >= ? AND created_dt < ?", ts, ts).scoping do
      block.call(ts, *args)
    end
  end
end

#mcfly_validates_uniqueness_of(*attr_names) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/mcfly/has_mcfly.rb', line 54

def mcfly_validates_uniqueness_of(*attr_names)
  # Set MCFLY_UNIQUENESS class constant to the args passed.
  # This is useful for introspection.  FIXME: won't work if
  # mcfly_validates_uniqueness_of is called multiple times on
  # the same class.
  self.const_set(:MCFLY_UNIQUENESS, attr_names)

  attr_names << {} unless attr_names.last.is_a?(Hash)

  attr_names.last[:scope] ||= []

  # add :obsoleted_dt to the uniqueness scope
  attr_names.last[:scope] << :obsoleted_dt
  
  # Set uniqueness error message if not set.  FIXME: need to
  # figure out how to change the base message.  It still
  # prepends the pluralized main attr.
  attr_names.last[:message] ||= "- record must be unique"

  validates_uniqueness_of(*attr_names)
end