Class: StateAttr::ClassMethods::State

Inherits:
Object
  • Object
show all
Defined in:
lib/state_attr/state.rb

Instance Method Summary collapse

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, options)
  @parent = parent
  @field = field
  @options = 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

#allowedObject

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

Returns:

  • (Boolean)


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

Returns:

  • (Boolean)


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_sObject



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

#valueObject 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