Class: ActiveRecord::Base
- Inherits:
-
Object
- Object
- ActiveRecord::Base
- Defined in:
- lib/bootstripe-rails/model_additions.rb
Constant Summary collapse
- DONT_TRUNCATE =
[:schema_migrations]
Class Method Summary collapse
- .loaded_models ⇒ Object
- .ordered ⇒ Object
- .randomize ⇒ Object
-
.truncate_models!(options = {}) ⇒ Object
Truncates all tables in the database.
-
.upsert(lookup, params, options = {}) ⇒ Object
Options: :merge_lookup => true/false [defaults to true].
Instance Method Summary collapse
Class Method Details
.loaded_models ⇒ Object
25 26 27 |
# File 'lib/bootstripe-rails/model_additions.rb', line 25 def self.loaded_models ActiveRecord::Base.send(:descendants) end |
.ordered ⇒ Object
37 38 39 |
# File 'lib/bootstripe-rails/model_additions.rb', line 37 def self.ordered order 'created_at ASC' end |
.randomize ⇒ Object
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:
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!(={}) if adapter = ActiveRecord::Base.connection.adapter_name exclude = [*[:exclude]].collect(&:to_sym) if [: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, = {}) merge_lookup = [: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 |