Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/acts_as_interface.rb
Overview
Include ActsAsInterface to easily define abstract methods Example: Superclass class Person
abstract_methods :dance, :eat
abstract_methods :sleep, :play, :visibility => :private
callbacks :prance
abstract_methods :foo, :for => :class
callbacks :france, :for => :class, :visibility => :protected
end
me = MyClass.new me.dance #raises NotImplementedError me.play #raises NoMethodError: private method ‘close_book` called me.send(:play) #calls empty method play me.prance #calls empty method prance Person.foo #raises NotImplementedError
Example: ActiveRecord Module module ActsAsPerson
# included in active record objects where abstracted methods can be either attributes of the model or defined by the model
def self.included(base)
base.instance_eval do
include ActsAsInterface
abstract_methods :name, :dance
end
end
end
Instance Method Summary collapse
Instance Method Details
#define_abstract_method(abstract_method_name, options) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/acts_as_interface.rb', line 34 def define_abstract_method(abstract_method_name, ) model_columns = [] error_on_column_load = false begin model_columns = respond_to?(:columns) ? columns : [] rescue error_on_column_load = true end unless method_defined?(abstract_method_name) or error_on_column_load or model_columns.any? { |column| column.name.to_sym == abstract_method_name } define_method(abstract_method_name) do |*abstract_method_args| if .has_key?(:default) [:default] else class_name = [:for] == :class ? self : self.class raise NotImplementedError, "#{abstract_method_name} not defined for #{class_name}" end end send([:visibility], abstract_method_name) if [:visibility] end end |