vendredi 15 mai 2015

Create module that throws exception in rails if conditions not met on load

I have a module in a rails 3 app that's included in multiple models. I want to force the app to fail to load if any of the models do not have an appropriate attr_accessor defined. Due to the architecture of the app it's not feasible to include the attr_accessors as a part of the module to be added to the class during the self.included function.

Here's what I've tried at present:

module MyModule
  def included(base)
    raise "Accessor 'enabled' is not defined in #{base.name}" unless base.method_defined? :enabled
  end
end

class MyModel < ActiveModel::Base
  # attr_accessor :enabled
  attr_accessor :attr_1, :attr_2
  include MyModule
end

In this instance, I'd want the app to fail to load because MyModel does not have an enabled method.

Aucun commentaire:

Enregistrer un commentaire