Created
November 16, 2012 12:41
-
-
Save tdantas/4087037 to your computer and use it in GitHub Desktop.
Flavour - The module to avoid ifs when your model is State driven behaviour
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
module Flavour | |
module ClassMethods | |
def watch(&block) | |
@watchable = block | |
end | |
def watchable | |
@watchable | |
end | |
def state(state_name, options = {} , &block) | |
@state_behavior = @state_behavior || {} | |
@state_behavior[state_name] = (Class.new &block).new | |
end | |
def state_behavior | |
@state_behavior | |
end | |
end | |
module InstanceMethods | |
def method_missing(method, *args, &block) | |
instance_state = self.instance_eval &self.class.watchable | |
if self.class.state_behavior[instance_state.to_sym].respond_to? method.to_sym | |
self.class.state_behavior[instance_state.to_sym].send(method.to_sym, *args, &block) | |
else | |
super | |
end | |
end | |
end | |
def self.included(base) | |
base.send(:include, InstanceMethods) | |
base.extend ClassMethods | |
end | |
end | |
class Invoice | |
include Flavour | |
attr_accessor :invoice_state | |
watch { self.invoice_state } | |
state :draft do | |
def calculate | |
self.total | |
end | |
def signature | |
"Invoice Not Finalized" | |
end | |
end | |
state :final do | |
def calculate | |
self.total = self.total + self.total * 0.10 | |
end | |
def signature | |
"2178 - Proccessed by Computer AT/192" | |
end | |
end | |
def initialize(initial_state = :draft) | |
self.invoice_state = initial_state | |
end | |
def total | |
100 | |
end | |
end | |
invoice = Invoice.new | |
invoice.invoice_state = :final | |
puts invoice.signature |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment