Skip to content

Instantly share code, notes, and snippets.

@swistak35
Last active December 14, 2015 11:08
Show Gist options
  • Save swistak35/5076606 to your computer and use it in GitHub Desktop.
Save swistak35/5076606 to your computer and use it in GitHub Desktop.
DCI using EVIL.RB, Wroc_Love.rb 2013
# 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
# 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