Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This
- require 'activesupport'
- Object.class_eval do
- def self.has_behavior(behavior, options={})
- options.reverse_merge!({:from => name.underscore})
- require "#{options[:from]}/#{behavior}"
- mod = "#{options[:from].camelize}::#{behavior.to_s.camelize}".constantize
- include mod::InstanceMethods if defined?(mod::InstanceMethods)
- extend mod::ClassMethods if defined?(mod::ClassMethods)
- mod.initialize(self) if mod.respond_to?(:initialize)
- end
- end
- # Or in Rails
- ActiveRecord::Base.class_eval do
- def self.has_behavior(behavior, options={})
- options.reverse_merge!({:from => name.underscore})
- require "#{options[:from]}/#{behavior}"
- mod = "#{options[:from].camelize}::#{behavior.to_s.camelize}".constantize
- include mod::InstanceMethods if defined?(mod::InstanceMethods)
- extend mod::ClassMethods if defined?(mod::ClassMethods)
- mod.initialize(self) if mod.respond_to?(:initialize)
- end
- end
- # With
- module SharedBehaviors::Authenticated
- module InstanceMethods
- # Instance methods
- end
- module ClassMethods
- # Class methods
- end
- def initialize(klass)
- klass.class_eval do
- # do stuff
- end
- klass.send(:foo)
- end
- end
- # Or with
- module User::Authenticated
- module InstanceMethods
- # Instance methods
- end
- module ClassMethods
- # Class methods
- end
- def initialize(klass)
- klass.class_eval do
- # do stuff
- end
- klass.send(:foo)
- end
- end
- # Will:
- # 1. require 'shared_behaviors/authenticated'
- # 2. Get the module SharedBehaviors::Authenticated
- # 3. include SharedBehaviors::Authenticated::InstanceMethods if SharedBehaviors::Authenticated has InstanceMethods
- # 4. extend SharedBehaviors::Authenticated::ClassMethods if SharedBehaviors::Authenticated has ClassMethods
- # 5. call SharedBehaviors::Authenticated.initialize(User)
- class User < ActiveRecord::Base
- has_behavior :authenticated, :from => :shared_behaviors
- end
- # Will:
- # 1. require 'user/authenticated'
- # 2. Get the module User::Authenticated
- # 3. include User::Authenticated::InstanceMethods if User::Authenticated has InstanceMethods
- # 4. extend User::Authenticated::ClassMethods if User::Authenticated has ClassMethods
- # 5. call User::Authenticated.initialize(User)
- class User < ActiveRecord::Base
- has_behavior :authenticated
- end
Add Comment
Please, Sign In to add comment