module Rooftop::Coercions

Public Class Methods

included(base) click to toggle source
# File lib/rooftop/coercions.rb, line 3
def self.included(base)
  # Include Rooftop::HookCalls to allow us to push things into a list of hooks in the right order
  base.include Rooftop::HookCalls
  base.extend ClassMethods

  # Add the call to the :after_find hook to the list of hook calls, to be processed later.
  # This is where we iterate over our previously established list of coercions, and call each
  # in turn
  base.send(:add_to_hook, :after_find, ->(r){
    r.coercions.each do |field,coercion|
      if r.respond_to?(field)
        r.send("#{field}=",coercion.call(r.send(field)))
      end
    end
  })
  base.send(:before_save, ->(r) {
    r.coercions.each do |field,coercion|
      r.send(:"restore_#{field}!") unless r.new?
    end
  })
end

Public Instance Methods

coercions() click to toggle source

Instance method to get the class's coercions

# File lib/rooftop/coercions.rb, line 40
def coercions
  self.class.instance_variable_get(:"@coercions") || {}
end