Skip to content

Instantly share code, notes, and snippets.

@tdantas
Created November 16, 2012 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdantas/4087037 to your computer and use it in GitHub Desktop.
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
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