Method: Cequel::Record::ClassMethods#findOrCreateOrUpdate

Defined in:
lib/octocore/models.rb

#findOrCreateOrUpdate(args, options = {}) ⇒ Object

If a record exists, will find it and update it’s value with the

provided options. Else, will just create the record.


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/octocore/models.rb', line 92

def findOrCreateOrUpdate(args, options = {})
  cache_key = gen_cache_key(args)
  res = get_cached(args)
  if res
    dirty = false

    # handle price separately because of float issues
    if options.has_key?(:price)
      _v = options.delete(:price)
      dirty = _v.round(2) != res.price.round(2)
    end

    # remaining opts
    options.each do |k, v|
      if res.respond_to?(k)
        unless res.public_send(k) == v
          dirty = true
          res.public_send("#{ k }=", v)
        end
      end
    end

    if dirty
      res.save!
      Cequel::Record.redis.setex(cache_key, get_ttl,
                                 Octo::Utils.serialize(res))
    end
  else
    _args = args.merge(options)
    res = self.new(_args).save!
    Cequel::Record.redis.setex(cache_key, get_ttl,
                               Octo::Utils.serialize(res))
  end
  res
end