Add behavior to individual objects and remove it later while preserving the existing behavior.
This is similar to Casting in that it adds and removes behaviors and preserves self
but it's different in that you can still use super
inside your methods.
Add Behavioral to your classes to add new features or override existing ones. Later you may remove your behaviors:
class Person
def initialize(name)
@name = name
end
attr_reader :name
include Behavioral
end
module Greeter
def hello
"Hello, I am #{self.name}"
end
def name
"The Greeter #{super}"
end
end
person = Person.new('Jim').with_behaviors(Greeter)
person.hello #=> "Hello, I am Jim"
person.without_behaviors(Greeter)
person.hello #=> NoMethodError
When you add behaviors, the methods are copied to the singleton_class
of your object. Later, if you ask the object if it is of that type, the answer will be false.
person = Person.new('Jim').with_behaviors(Greeter)
person.is_a?(Greeter) #=> false
#alternative
person = Person.new('Jim').extend(Greeter)
person.is_a?(Greeter) #=> true
Add this line to your application's Gemfile:
gem 'behavioral'
And then execute:
$ bundle
Or install it yourself as:
$ gem install behavioral
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request