Module: ActiveRecord::Concerns::Seeds
- Defined in:
- app/lib/active_record/concerns/seeds.rb
Instance Method Summary collapse
-
#create(model, attrs, vals = nil) ⇒ Object
> first_or_initialize => snippets.aktagon.com/snippets/620-rails-find-or-initialize-and-find-or-create-methods-are-deprecated.
-
#iterate(model, h, ref = nil) ⇒ Object
> Iterate over hash or array => stackoverflow.com/a/16413593/1143732.
Instance Method Details
#create(model, attrs, vals = nil) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'app/lib/active_record/concerns/seeds.rb', line 11 def create model, attrs, vals=nil # => Model # => http://stackoverflow.com/a/32869926/1143732 model = model.to_s.titleize.gsub(" ","::") model = model.constantize rescue nil # => Model exists unless model.nil? # => Setup payload = model.where(attrs).first_or_initialize is_new = payload.new_record? # => Action payload.update vals || attrs # => Output if payload.valid? puts "#{payload.class.name} #{is_new ? 'Created' : 'Updated'} - #{payload.ref}" + (payload.has_attribute?(:val) ? " → #{payload.val}" : nil) else puts "#{payload.class.name} Error - #{payload.errors.}" end else puts "Model Not Initialized" end end |
#iterate(model, h, ref = nil) ⇒ Object
> Iterate over hash or array
> stackoverflow.com/a/16413593/1143732
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'app/lib/active_record/concerns/seeds.rb', line 46 def iterate model, h, ref=nil return h unless h.is_a?(Hash) || h.is_a?(Array) # => Return if not hash # => Linebreak puts "\n" # => Proceed if hash/array h.each do |k,v| # If v is nil, an array is being iterated and the value is k. # If v is not nil, a hash is being iterated and the value is v. value = v || k # Ref # If exists, need to prepend ref_ reference = v ? "#{ref}#{'_' if ref}#{k}" : ref # => Iterate or continue if value.is_a?(Hash) || value.is_a?(Array) iterate model, value, k else create model, { ref: reference, val: value }, { seed: true } end end end |