Sha256: b28659f312d6985c3df88d7b7ba872c0d3a4ddd76ca2286059f7747fb26b8e84

Contents?: true

Size: 1.57 KB

Versions: 3

Compression:

Stored size: 1.57 KB

Contents

# @see https://github.com/opennorth/pupa-ruby#opencivicdata-compatibility

module Pupa::Model
  # This unfortunately won't cause the behavior of any model that has already
  # included `Pupa::Model` to change.
  class << self
    def append_features(base)
      if base.instance_variable_defined?("@_dependencies")
        base.instance_variable_get("@_dependencies") << self
        return false
      else
        return false if base < self
        @_dependencies.each { |dep| base.send(:include, dep) }
        super
        base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
        base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
        base.class_eval do # XXX
          set_callback(:save, :before) do |object|
            object._type = object._type.camelize.demodulize.underscore
          end
        end
      end
    end
  end
end

# `set_callback` is called by `class_eval` in `ActiveSupport::Concern`. Without
# monkey-patching `ActiveSupport::Concern`, we can either iterate `ObjectSpace`,
# implement something like ActiveSupport's `DescendantsTracker` for inclusion
# instead of inheritance, or go back to `Pupa::Model` being a superclass instead
# of a mixin to take advantage of `DescendantsTracker` itself.
#
# Instead of adding a callback, we can override `to_h` when `persist` is `true`.
ObjectSpace.each_object(Class) do |base|
  if base.include?(Pupa::Model)
    base.class_eval do
      set_callback(:save, :before) do |object|
        object._type = object._type.camelize.demodulize.underscore
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pupa-0.1.0 lib/pupa/refinements/opencivicdata.rb
pupa-0.0.13 lib/pupa/refinements/opencivicdata.rb
pupa-0.0.12 lib/pupa/refinements/opencivicdata.rb