Last active
December 14, 2015 11:08
-
-
Save swistak35/5076606 to your computer and use it in GitHub Desktop.
DCI using EVIL.RB, Wroc_Love.rb 2013
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Firstly, install gems: 'evilr' and 'include' | |
# Example with User in a shop application. | |
# He has two roles | |
# - buyer (with money on the account and so on) | |
# - reviewer (he can review books he bought) | |
require 'evilr' | |
require 'include' | |
class User | |
attr_reader :email | |
def initialize(email) | |
@email = email | |
@money = 0 | |
end | |
end | |
class Buyer | |
include User.to_module | |
attr_reader :money | |
# Yeah, these methods are kind of dumb, because we can 'buy' product for '-10', but it's implementation detail | |
def buy(item_price) | |
@money -= item_price | |
end | |
def add_money(amount) | |
@money += amount | |
end | |
end | |
class Reviewer < User | |
include User.to_module | |
def review(book_name) | |
puts "#{book_name} was amazing!" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example session in irb: | |
swistak35@raptop> irb | |
1.9.2p320 :001 > load 'dci_with_hacks.rb' | |
=> true | |
1.9.2p320 :002 > x = Buyer.new("Swistak35") | |
=> #<Buyer:0x00000001505a18 @email="Swistak35", @money=0> | |
1.9.2p320 :003 > x.money | |
=> 0 | |
1.9.2p320 :004 > x.add_money 10 | |
=> 10 | |
1.9.2p320 :005 > x.money | |
=> 10 | |
1.9.2p320 :007 > x.class = Reviewer | |
=> Reviewer | |
1.9.2p320 :008 > x.review "Ding dong" | |
Ding dong was amazing! | |
=> nil | |
1.9.2p320 :009 > x.money | |
NoMethodError: undefined method `money' for #<Reviewer:0x00000001505a18> | |
from (irb):9 | |
from /home/swistak35/.rvm/rubies/ruby-1.9.2-p320/bin/irb:16:in `<main>' | |
1.9.2p320 :010 > x.class = Buyer | |
=> Buyer | |
1.9.2p320 :011 > x.money | |
=> 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment