Class: StateAttr::ClassMethods::State
- Inherits:
-
Object
- Object
- StateAttr::ClassMethods::State
- Defined in:
- lib/state_attr/state.rb
Instance Method Summary collapse
-
#allowed ⇒ Object
array of allowed stated.
-
#allowed?(state) ⇒ Boolean
validate if can switch to given state.
-
#initialize(parent, field, machine, logger, options) ⇒ State
constructor
A new instance of State.
-
#is?(*symbols) ⇒ Boolean
validates if state is one of the given states.
-
#switch(state) ⇒ Object
if allowed switch to given state, if not raise exception.
- #to_s ⇒ Object
- #to_yaml(*opts) ⇒ Object
-
#value ⇒ Object
(also: #current, #to_sym)
current state value.
Constructor Details
#initialize(parent, field, machine, logger, options) ⇒ State
Returns a new instance of State.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/state_attr/state.rb', line 5 def initialize(parent, field, machine, logger, ) @parent = parent @field = field @options = groups = @options[:groups] || {} @machine = {} #convert different types of input to array of symbols machine.each { |key, value| @machine[key] = if value.nil? [nil] elsif groups.keys.include? value Array(groups[value]).map(&:to_sym) else Array(value).map(&:to_sym) end } @logger = logger @callback = "on_#{@field}_change".to_sym end |
Instance Method Details
#allowed ⇒ Object
array of allowed stated
45 46 47 48 |
# File 'lib/state_attr/state.rb', line 45 def allowed result = @machine[read_state] || [] result end |
#allowed?(state) ⇒ Boolean
validate if can switch to given state
51 52 53 |
# File 'lib/state_attr/state.rb', line 51 def allowed?(state) allowed.include?(state) || is?(state) end |
#is?(*symbols) ⇒ Boolean
validates if state is one of the given states
40 41 42 |
# File 'lib/state_attr/state.rb', line 40 def is?(*symbols) !symbols.flatten.select { |state| read_state == state }.empty? end |
#switch(state) ⇒ Object
if allowed switch to given state, if not raise exception
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/state_attr/state.rb', line 56 def switch(state) state = state.try(:to_sym) if (allowed?(state)) write_state(state) elsif @options[:switch_not_allowed] == :silent @logger.error "#{@parent.class.name} changing #{@field} from '#{read_state}' to '#{state}' is not allowed, allowed states are '#{allowed*'\', \''}'" false else raise "#{@parent.class.name} error, changing #{@field} from '#{read_state}' to '#{state}' is not allowed, allowed states are '#{allowed*'\', \''}'" end end |
#to_s ⇒ Object
25 26 27 |
# File 'lib/state_attr/state.rb', line 25 def to_s read_state.to_s end |
#to_yaml(*opts) ⇒ Object
28 29 30 |
# File 'lib/state_attr/state.rb', line 28 def to_yaml( *opts ) to_s.to_yaml( *opts ) end |
#value ⇒ Object Also known as: current, to_sym
current state value
33 34 35 |
# File 'lib/state_attr/state.rb', line 33 def value read_state end |