-
Notifications
You must be signed in to change notification settings - Fork 4
Usage Details
Andy Maleh edited this page Apr 8, 2015
·
1 revision
- SuperModule must always be included at the top of a module's body at code-time
- SuperModule inclusion can be optionally followed by other basic or super module inclusions
- A super module can only be included in a class or another super module
- SuperModule adds zero cost to instantiation of including classes and invocation of included methods (both class and instance)
Create a ruby file called super_module_irb_example.rb with the following content:
require 'rubygems' # to be backwards compatible with Ruby 1.8.7
require 'super_module'
module RequiresAttributes
include SuperModule
def self.requires(*attributes)
attributes.each {|attribute| required_attributes << attribute}
end
def self.required_attributes
@required_attributes ||= []
end
def requirements_satisfied?
!!self.class.required_attributes.reduce(true) { |result, required_attribute| result && send(required_attribute) }
end
end
class MediaAuthorization
include RequiresAttributes
attr_accessor :user_id, :credit_card_id
requires :user_id, :credit_card_id
end
Open irb
(Interactive Ruby) and paste the following code snippets in. You should get the output denoted by the rockets (=>
).
require './super_module_irb_example.rb'
=> true
MediaAuthorization.required_attributes
=> [:user_id, :credit_card_id]
media_authorization = MediaAuthorization.new # resulting object print-out varies
=> #MediaAuthorization:0x832b36be1
media_authorization.requirements_satisfied?
=> false
media_authorization.user_id = 387
=> 387
media_authorization.requirements_satisfied?
=> false
media_authorization.credit_card_id = 37
=> 37
media_authorization.requirements_satisfied?
=> true