Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/bootstripe-rails/model_additions.rb

Constant Summary collapse

DONT_TRUNCATE =
[:schema_migrations]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.loaded_modelsObject



25
26
27
# File 'lib/bootstripe-rails/model_additions.rb', line 25

def self.loaded_models
  ActiveRecord::Base.send(:descendants)
end

.orderedObject



37
38
39
# File 'lib/bootstripe-rails/model_additions.rb', line 37

def self.ordered
  order 'created_at ASC'
end

.randomizeObject



29
30
31
32
33
34
35
# File 'lib/bootstripe-rails/model_additions.rb', line 29

def self.randomize
  if adapter = ActiveRecord::Base.connection.adapter_name
    order(adapter.match(/postgres/i) ? 'RANDOM()' : 'RAND()')
  else
    raise 'No ActiveRecord adapter specified!'
  end
end

.truncate_models!(options = {}) ⇒ Object

Truncates all tables in the database

options:

Parameters:

  • :exclude (Array)

    tables to exclude from the truncation



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bootstripe-rails/model_additions.rb', line 45

def self.truncate_models!(options={})
  if adapter = ActiveRecord::Base.connection.adapter_name
    exclude = [*options[:exclude]].collect(&:to_sym) if options[:exclude]
    exclude = ([exclude] + DONT_TRUNCATE).flatten.compact.uniq

    ActiveRecord::Base.connection.tables.each do |table_name|
      trunc_method = adapter.match(/sqlite/i) ? "DELETE FROM" : "TRUNCATE TABLE"
      ActiveRecord::Base.connection.execute("#{trunc_method} #{table_name}") if !exclude.include?(table_name.to_sym)
    end
  else
    raise 'No ActiveRecord adapter specified!'
  end
end

.upsert(lookup, params, options = {}) ⇒ Object

Options: :merge_lookup => true/false [defaults to true]



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/bootstripe-rails/model_additions.rb', line 7

def self.upsert(lookup, params, options = {})
  merge_lookup = options[:merge_lookup] || true
  subject = nil

  transaction do
    subject = where(lookup).first

    if subject
      subject.update_attributes(params)
    else
      params = params.merge(lookup) if merge_lookup
      subject = create(params)
    end
  end

  subject
end

Instance Method Details

#clone!(params = {}) ⇒ Object



59
60
61
62
63
64
# File 'lib/bootstripe-rails/model_additions.rb', line 59

def clone!(params = {})
  cl = self.class.new
  time = Time.current
  cl.send :attributes=, HashWithIndifferentAccess.new(self.attributes).except(:id).merge(:created_at => time, :updated_at => time).merge(params), false
  cl
end