Module: JetstreamBridge::ModelUtils
- Defined in:
- lib/jetstream_bridge/core/model_utils.rb
Class Method Summary collapse
- .ar_class?(klass) ⇒ Boolean
- .assign_known_attrs(record, attrs) ⇒ Object
- .constantize(name) ⇒ Object
-
.find_or_init_by_best(klass, *keysets) ⇒ Object
find_or_initialize_by on the first keyset whose columns exist; else new.
- .has_columns?(klass, *cols) ⇒ Boolean
- .json_dump(obj) ⇒ Object
- .json_load(str) ⇒ Object
Class Method Details
.ar_class?(klass) ⇒ Boolean
13 14 15 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 13 def ar_class?(klass) defined?(ActiveRecord::Base) && klass <= ActiveRecord::Base end |
.assign_known_attrs(record, attrs) ⇒ Object
23 24 25 26 27 28 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 23 def assign_known_attrs(record, attrs) attrs.each do |k, v| setter = :"#{k}=" record.public_send(setter, v) if record.respond_to?(setter) end end |
.constantize(name) ⇒ Object
9 10 11 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 9 def constantize(name) name.to_s.split('::').reduce(Object) { |m, c| m.const_get(c) } end |
.find_or_init_by_best(klass, *keysets) ⇒ Object
find_or_initialize_by on the first keyset whose columns exist; else new
31 32 33 34 35 36 37 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 31 def find_or_init_by_best(klass, *keysets) keysets.each do |keys| next if keys.nil? || keys.empty? return klass.find_or_initialize_by(keys) if has_columns?(klass, keys.keys) end klass.new end |
.has_columns?(klass, *cols) ⇒ Boolean
17 18 19 20 21 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 17 def has_columns?(klass, *cols) return false unless ar_class?(klass) cols.flatten.all? { |c| klass.column_names.include?(c.to_s) } end |
.json_dump(obj) ⇒ Object
39 40 41 42 43 44 45 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 39 def json_dump(obj) return obj if obj.is_a?(String) Oj.dump(obj, mode: :compat) rescue Oj::Error, TypeError obj.to_s end |
.json_load(str) ⇒ Object
47 48 49 50 51 52 53 |
# File 'lib/jetstream_bridge/core/model_utils.rb', line 47 def json_load(str) return str if str.is_a?(Hash) Oj.load(str.to_s, mode: :strict) rescue Oj::Error {} end |