Sha256: 75c5b2646bb0bc6544a5d5b709b1e58d43abddd0e24ee1ddc96bf7b312149aab

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

module AttrInitializable
  extend ActiveSupport::Concern

  module ClassMethods
    def attr_initializable(attributes, options = {})
      unless respond_to?(:protected_attributes)
        raise RuntimeError.new('`attr_initializable` relies on `attr_accessible`. ' \
           'Please add `protected_attributes` to your Gemfile to use `attr_initializable`.')
      end

      unless ActiveRecord::Base.respond_to?('_mass_assignment_sanitizer') &&
        ActiveRecord::Base.send('_mass_assignment_sanitizer').is_a?(ActiveModel::MassAssignmentSecurity::StrictSanitizer)
        puts "WARNING: Running with strict mass assignment sanitizer is recommended.\n" \
          "Please add config.active_record.mass_assignment_sanitizer = :strict to config/application.rb.\n"
      end

      role = options.delete(:as) || :default
      initializable_attributes[role] ||= []
      initializable_attributes[role] += Array(attributes)
    end

    def initializable_attributes
      @@initializable_attributes ||= {}
    end
  end

  included do
    def mass_assignment_authorizer(role = :default)
      authorizer = super
      authorizer += Array(self.class.initializable_attributes[role]) unless persisted?
      authorizer
    end
  end
end

ActiveRecord::Base.send :include, AttrInitializable

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
attr_initializable-0.1.0 lib/attr_initializable.rb