Module: Ruote

Defined in:
lib/ruote/version.rb,
lib/ruote/fei.rb,
lib/ruote/engine.rb,
lib/ruote/reader.rb,
lib/ruote/worker.rb,
lib/ruote/context.rb,
lib/ruote/observer.rb,
lib/ruote/tree_dot.rb,
lib/ruote/workitem.rb,
lib/ruote/dashboard.rb,
lib/ruote/util/deep.rb,
lib/ruote/util/look.rb,
lib/ruote/util/misc.rb,
lib/ruote/util/time.rb,
lib/ruote/util/tree.rb,
lib/ruote/reader/xml.rb,
lib/ruote/util/ometa.rb,
lib/ruote/reader/json.rb,
lib/ruote/svc/tracker.rb,
lib/ruote/util/filter.rb,
lib/ruote/util/lookup.rb,
lib/ruote/exp/fe_error.rb,
lib/ruote/storage/base.rb,
lib/ruote/util/hashdot.rb,
lib/ruote/part/template.rb,
lib/ruote/reader/radial.rb,
lib/ruote/receiver/base.rb,
lib/ruote/svc/dollar_sub.rb,
lib/ruote/log/wait_logger.rb,
lib/ruote/reader/ruby_dsl.rb,
lib/ruote/svc/treechecker.rb,
lib/ruote/util/subprocess.rb,
lib/ruote/part/participant.rb,
lib/ruote/id/wfid_generator.rb,
lib/ruote/svc/dispatch_pool.rb,
lib/ruote/svc/error_handler.rb,
lib/ruote/storage/fs_storage.rb,
lib/ruote/svc/expression_map.rb,
lib/ruote/svc/expression_map.rb,
lib/ruote/log/default_history.rb,
lib/ruote/log/storage_history.rb,
lib/ruote/dboard/process_error.rb,
lib/ruote/part/rev_participant.rb,
lib/ruote/storage/hash_storage.rb,
lib/ruote/svc/participant_list.rb,
lib/ruote/dboard/process_status.rb,
lib/ruote/part/code_participant.rb,
lib/ruote/part/null_participant.rb,
lib/ruote/part/smtp_participant.rb,
lib/ruote/util/process_observer.rb,
lib/ruote/part/block_participant.rb,
lib/ruote/part/local_participant.rb,
lib/ruote/part/no_op_participant.rb,
lib/ruote/id/mnemo_wfid_generator.rb,
lib/ruote/part/engine_participant.rb,
lib/ruote/part/storage_participant.rb,
lib/ruote/storage/composite_storage.rb

Overview

– Copyright © 2012, Hartog de Mik <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Made in Germany. ++

Defined Under Namespace

Modules: Dollar, Exp, HashDot, JsonReader, LocalParticipant, Look, Mem, RadialReader, ReceiverMixin, RubyDsl, RubyReader, StorageBase, TemplateMixin, WithH, WithMeta, XmlReader Classes: BlankSlate, BlockParticipant, CodeParticipant, CompositeStorage, Context, Dashboard, DefaultHistory, DispatchPool, DollarSubstitution, Engine, EngineParticipant, EngineVariables, ErrorHandler, ExpressionMap, FlowExpressionId, ForcedError, FsStorage, HashStorage, LoggerTimeout, MetaError, MnemoWfidGenerator, NoOpParticipant, NullParticipant, Observer, Participant, ParticipantEntry, ParticipantList, ParticipantRegistrationProxy, ProcessError, ProcessObserver, ProcessStatus, Reader, Receiver, RevParticipant, RuleSession, SmtpParticipant, StorageHistory, StorageParticipant, TestContext, Tracker, TreeChecker, ValidationError, WaitLogger, WfidGenerator, Worker, Workitem

Constant Summary collapse

VERSION =
'2.3.0.1'
WIN =

Will be set to true if the Ruby runtime is on Windows

(RUBY_PLATFORM.match(/mswin|mingw/) != nil)
JAVA =

Will be set to true if the Ruby runtime is JRuby

(RUBY_PLATFORM.match(/java/) != nil)
REGEX_IN_STRING =
/^\s*\/(.*)\/\s*$/

Class Method Summary collapse

Class Method Details

.comma_split(o) ⇒ Object

Returns an array. If the argument is an array, return it as is. Else turns the argument into a string and “comma splits” it.



199
200
201
202
# File 'lib/ruote/util/misc.rb', line 199

def self.comma_split(o)

  o.is_a?(Array) ? o : o.to_s.split(/\s*,\s*/).collect { |e| e.strip }
end

.constantize(s) ⇒ Object

(simpler than the one from active_support)



124
125
126
127
# File 'lib/ruote/util/misc.rb', line 124

def self.constantize(s)

  s.split('::').inject(Object) { |c, n| n == '' ? c : c.const_get(n) }
end

.decompose_tree(t, pos = '0', h = {}) ⇒ Object

Used by Ruote::ProcessStatus.

Given a tree

[ 'define', { 'name' => 'nada' }, [
  [ 'sequence', {}, [ [ 'alpha', {}, [] ], [ 'bravo', {}, [] ] ] ]
] ]

will output something like

{ '0' => [ 'define', { 'name' => 'nada' } ],
  '0_0' => [ 'sequence', {} ],
  '0_0_0' => [ 'alpha', {} ],
  '0_0_1' => [ 'bravo', {} ] },

An initial offset can be specifid with the ‘pos’ argument.

Don’t touch ‘h’, it’s an accumulator.



77
78
79
80
81
82
# File 'lib/ruote/util/tree.rb', line 77

def self.decompose_tree(t, pos='0', h={})

  h[pos] = t[0, 2]
  t[2].each_with_index { |c, i| decompose_tree(c, "#{pos}_#{i}", h) }
  h
end

.deep_delete(h, key) ⇒ Object Also known as: delete_all

Given a hash and a key, deletes all the entries with that key, in child hashes too.

Note: this method is not related to the “dot notation” methods in this lookup.rb file.

example

h = { 'a' => 1, 'b' => { 'a' => 2 } }
Ruote.deep_delete(h, 'a')
  # => { 'b' => {} }


45
46
47
48
49
50
# File 'lib/ruote/util/deep.rb', line 45

def self.deep_delete(h, key)

  h.delete(key)

  h.each { |k, v| deep_delete(v, key) if v.is_a?(Hash) }
end

.deep_mutate(coll, key_or_keys, parent = nil, &block) ⇒ Object

Dives into a nested structure of hashes and arrays to find match hash keys.

The method expects a block with 3 or 4 arguments.

3 arguments: collection, key and value 4 arguments: parent collection, collection, key and value

Warning: .deep_mutate forces hash keys to be strings. It’s a JSON world.

example

h = {
  'a' => 0,
  'b' => 1,
  'c' => { 'a' => 2, 'b' => { 'a' => 3 } },
  'd' => [ { 'a' => 0 }, { 'b' => 4 } ] }

Ruote.deep_mutate(h, 'a') do |coll, k, v|
  coll['a'] = 10
end

h # =>
  { 'a' => 10,
    'b' => 1,
    'c' => { 'a' => 10, 'b' => { 'a' => 10 } },
    'd' => [ { 'a' => 10 }, { 'b' => 4 } ] }

variations

Instead of a single key, it’s OK to pass an array of keys:

Ruote.deep_mutate(a, [ 'a', 'b' ]) do |coll, k, v|
  # ...
end

Regular expressions are made to match:

Ruote.deep_mutate(a, [ 'a', /^a\./ ]) do |coll, k, v|
  # ...
end

A single regular expression is OK:

Ruote.deep_mutate(a, /^user\./) do |coll, k, v|
  # ...
end


103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/ruote/util/deep.rb', line 103

def self.deep_mutate(coll, key_or_keys, parent=nil, &block)

  keys = key_or_keys.is_a?(Array) ? key_or_keys : [ key_or_keys ]

  if coll.is_a?(Hash)

    coll.dup.each do |k, v|

      # ensure that all keys are strings

      unless k.is_a?(String)
        coll.delete(k)
        k = k.to_s
        coll[k] = v
      end

      # call the mutation blocks for each match

      if keys.find { |kk| kk.is_a?(Regexp) ? kk.match(k) : kk == k }

        if block.arity > 3
          block.call(parent, coll, k, v)
        else
          block.call(coll, k, v)
        end

      elsif v.is_a?(Array) || v.is_a?(Hash)

        deep_mutate(v, keys, coll, &block)
      end
    end

  elsif coll.is_a?(Array)

    coll.each { |e| deep_mutate(e, keys, coll, &block) }

  #else # nothing
  end
end

.define(*attributes, &block) ⇒ Object

Not really a reader, more an AST builder.

pdef = Ruote.define :name => 'take_out_garbage' do
  sequence do
    take_out_regular_garbage
    take_out_glass
    take_out_paper
  end
end

engine.launch(pdef)


43
44
45
46
# File 'lib/ruote/reader/ruby_dsl.rb', line 43

def self.define(*attributes, &block)

  RubyDsl.create_branch('define', attributes, &block)
end

.do_filter(filter, hash, options) ⇒ Object

Used by Ruote.filter



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/ruote/util/filter.rb', line 96

def self.do_filter(filter, hash, options)

  hash = Rufus::Json.dup(hash)

  hash['~'] = Rufus::Json.dup(hash)
  hash['~~'] = Rufus::Json.dup(options[:double_tilde] || hash)
    # the 'originals'

  deviations = filter.collect { |rule|
    RuleSession.new(hash, rule).run
  }.flatten(1)

  hash.delete('~')
  hash.delete('~~')
  hash.delete('~~~')
    # remove the 'originals'

  if deviations.empty?
    hash
  elsif options[:no_raise]
    deviations
  else
    raise ValidationError.new(deviations)
  end
end

.extract_fei(o) ⇒ Object

Given something, tries to return the fei (Ruote::FlowExpressionId) in it.



74
75
76
77
# File 'lib/ruote/fei.rb', line 74

def self.extract_fei(o)

  Ruote::FlowExpressionId.extract(o)
end

.extract_id(o) ⇒ Object

Will do its best to return a wfid (String) or a fei (Hash instance) extract from the given o argument.



65
66
67
68
69
70
# File 'lib/ruote/fei.rb', line 65

def self.extract_id(o)

  return o if o.is_a?(String) and o.index('!').nil? # wfid

  Ruote::FlowExpressionId.extract_h(o)
end

.extract_wfid(o) ⇒ Object

Given an object, will return the wfid (workflow instance id) nested into it (or nil if it can’t find or doesn’t know how to find).

The wfid is a String instance.



84
85
86
87
88
89
90
# File 'lib/ruote/fei.rb', line 84

def self.extract_wfid(o)

  return o.strip == '' ? nil : o if o.is_a?(String)
  return o.wfid if o.respond_to?(:wfid)
  return o['wfid'] || o.fetch('fei', {})['wfid'] if o.respond_to?(:[])
  nil
end

.filter(filter, hash, options = {}) ⇒ Object

Given a filter (a list of rules) and a hash (probably workitem fields) performs the validations / transformations dictated by the rules.

See the Ruote::Exp::FilterExpression for more information.

Raises:

  • (ArgumentError)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/ruote/util/filter.rb', line 48

def self.filter(filter, hash, options={})

  raise ArgumentError.new(
    "not a filter : #{filter}"
  ) unless filter.is_a?(Array)

  filters = or_split(filter)

  result = nil

  filters.each do |fl|

    result = begin
      do_filter(fl, hash, options)
    rescue ValidationError => err
      err
    end

    return result if result.is_a?(Hash)
      # success
  end

  raise(result) if result.is_a?(ValidationError)

  result
end

.flatten_keys(o, prefix = '', accu = []) ⇒ Object

Ruote.flatten_keys({ ‘a’ => ‘b’, ‘c’ => [ 1, 2, 3 ] })

  # =>
[ 'a', 'c', 'c.0', 'c.1', 'c.2' ]


525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/ruote/util/filter.rb', line 525

def self.flatten_keys(o, prefix='', accu=[])

  if o.is_a?(Array)

    o.each_with_index do |elt, i|
      pre = "#{prefix}#{i}"
      accu << pre
      flatten_keys(elt, pre + '.', accu)
    end

  elsif o.is_a?(Hash)

    o.keys.sort.each do |key|
      pre = "#{prefix}#{key}"
      accu << pre
      flatten_keys(o[key], pre + '.', accu)
    end
  end

  accu
end

.fulldup(object) ⇒ Object

Deep object duplication



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/ruote/util/misc.rb', line 50

def self.fulldup(object)

  return object.fulldup if object.respond_to?(:fulldup)
    # trusting client objects providing a fulldup() implementation
    # Tomaso Tosolini 2007.12.11

  begin
    return Marshal.load(Marshal.dump(object))
      # as soon as possible try to use that Marshal technique
      # it's quite fast
  rescue TypeError => te
  end

  #if object.is_a?(REXML::Element)
  #  d = REXML::Document.new object.to_s
  #  return d if object.kind_of?(REXML::Document)
  #  return d.root
  #end
    # avoiding "TypeError: singleton can't be dumped"

  o = object.class.allocate

  # some kind of collection ?

  if object.is_a?(Array)
    object.each { |i| o << fulldup(i) }
  elsif object.is_a?(Hash)
    object.each { |k, v| o[fulldup(k)] = fulldup(v) }
  end

  # duplicate the attributes of the object

  object.instance_variables.each do |v|
    value = object.instance_variable_get(v)
    value = fulldup(value)
    begin
      o.instance_variable_set(v, value)
    rescue
      # ignore, must be readonly
    end
  end

  o
end

.generate_subid(salt) ⇒ Object

This function is used to generate the subids. Each flow expression receives such an id (it’s useful for cursors, loops and forgotten branches).



96
97
98
99
100
# File 'lib/ruote/fei.rb', line 96

def self.generate_subid(salt)

  Digest::MD5.hexdigest(
    "#{rand}-#{salt}-#{$$}-#{Thread.current.object_id}#{Time.now.to_f}")
end

.has_key?(collection, key) ⇒ Boolean

h = { ‘a’ => { ‘b’ => [ 1, 3, 4 ] } }

p Ruote.lookup(h, 'a.b.1') # => true

Returns:

  • (Boolean)


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/ruote/util/lookup.rb', line 56

def self.has_key?(collection, key)

  return collection if key == '.'

  key, rest = pop_key(key)

  return has_key?(fetch(collection, key), rest) if rest.any?

  if collection.respond_to?(:has_key?)
    collection.has_key?(key)
  elsif collection.respond_to?(:[])
    key.to_i < collection.size
  else
    false
  end
end

.is_a_fei?(o) ⇒ Boolean

A shortcut for

Ruote::FlowExpressionId.is_a_fei?(o)

Returns:

  • (Boolean)


57
58
59
60
# File 'lib/ruote/fei.rb', line 57

def self.is_a_fei?(o)

  Ruote::FlowExpressionId.is_a_fei?(o)
end

.is_cron_string(s) ⇒ Object

Waiting for a better implementation of it in rufus-scheduler 2.0.4



90
91
92
93
94
95
96
97
98
# File 'lib/ruote/util/time.rb', line 90

def self.is_cron_string(s)

  ss = s.split(' ')

  return false if ss.size < 5 || ss.size > 6
  return false if s.match(/\d{4}/)

  true
end

.is_definition_tree?(arg) ⇒ Boolean

Returns true if the argument is a process definition tree (whose root is ‘define’, ‘process_definition’ or ‘workflow_definition’.

Returns:

  • (Boolean)


62
63
64
65
# File 'lib/ruote/util/subprocess.rb', line 62

def self.is_definition_tree?(arg)

  Ruote::Exp::DefineExpression.is_definition?(arg) && is_tree?(arg)
end

.is_pos_tree?(arg) ⇒ Boolean

Mainly used by Ruote.lookup_subprocess, returns true if the argument is is an array [ position, tree ].

Returns:

  • (Boolean)


80
81
82
83
84
85
86
# File 'lib/ruote/util/subprocess.rb', line 80

def self.is_pos_tree?(arg)

  arg.is_a?(Array) &&
  arg.size == 2 &&
  arg[0].is_a?(String) &&
  is_tree?(arg[1])
end

.is_tree?(arg) ⇒ Boolean

Returns true if the given argument is a process definition tree (its root doesn’t need to be ‘define’ or ‘process_definition’ though).

Returns:

  • (Boolean)


70
71
72
73
74
75
# File 'lib/ruote/util/subprocess.rb', line 70

def self.is_tree?(arg)

  arg.is_a?(Array) && arg.size == 3 &&
  arg[0].is_a?(String) && arg[1].is_a?(Hash) && arg[2].is_a?(Array) &&
  (arg.last.empty? || arg.last.find { |e| ! is_tree?(e) }.nil?)
end

.is_uri?(s) ⇒ Boolean

Returns true if the string seems to correpond to a URI

TODO : wouldn’t it be better to simply use URI.parse() ?

Returns:

  • (Boolean)


99
100
101
102
# File 'lib/ruote/util/misc.rb', line 99

def self.is_uri?(s)

  s && (s.index('/') || s.match(/\.[^ ]+$/))
end

.keys_to_s(h) ⇒ Object

Makes sure all they keys in the given hash are turned into strings in the resulting hash.



132
133
134
135
# File 'lib/ruote/util/misc.rb', line 132

def self.keys_to_s(h)

  h.remap { |(k, v), h| h[k.to_s] = v }
end

.keys_to_sym(h) ⇒ Object

Makes sure all they keys in the given hash are turned into symbols in the resulting hash.

Mostly used in ruote-amqp.



142
143
144
145
# File 'lib/ruote/util/misc.rb', line 142

def self.keys_to_sym(h)

  h.remap { |(k, v), h| h[k.to_sym] = v }
end

.local_ipObject

From coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/

Returns the (one of the) local IP address.



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/ruote/util/misc.rb', line 166

def self.local_ip

  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
    # turn off reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect('64.233.187.99', 1)
    s.addr.last
  end

rescue

  nil

ensure
  Socket.do_not_reverse_lookup = orig
end

.lookup(collection, key, container_lookup = false) ⇒ Object

h = { ‘a’ => { ‘b’ => [ 1, 3, 4 ] } }

p Ruote.lookup(h, 'a.b.1') # => 3


37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ruote/util/lookup.rb', line 37

def self.lookup(collection, key, container_lookup=false)

  return collection if key == '.'

  key, rest = pop_key(key)
  value = fetch(collection, key)

  return [ key, collection ] if container_lookup && rest.size == 0
  return [ rest.first, value ] if container_lookup && rest.size == 1
  return value if rest.size == 0
  return nil if value == nil

  lookup(value, rest, container_lookup)
end

.lookup_subprocess(fexp, ref) ⇒ Object

This method is used by the ‘subprocess’ expression and by the EngineParticipant.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ruote/util/subprocess.rb', line 35

def self.lookup_subprocess(fexp, ref)

  val = fexp.lookup_variable(ref)

  # a classical subprocess stored in a variable ?

  return [ '0', val ] if is_tree?(val)
  return val if is_pos_tree?(val)

  # maybe subprocess :ref => 'uri'

  subtree = fexp.context.reader.read(ref) rescue nil

  if subtree && is_definition_tree?(subtree)
    _, subtree = Ruote::Exp::DefineExpression.reorganize(subtree)
  end

  return [ '0', subtree ] if is_tree?(subtree)

  # no luck ...

  raise "no subprocess named '#{ref}' found"
end

.narrow_to_number(o) ⇒ Object

Tries to return an Integer or a Float from the given input. Returns



113
114
115
116
117
118
119
120
# File 'lib/ruote/util/misc.rb', line 113

def self.narrow_to_number(o)

  return o if [ Fixnum, Bignum, Float ].include?(o.class)

  s = o.to_s

  (s.index('.') ? Float(s) : Integer(s)) rescue nil
end

.neutralize(s) ⇒ Object

Returns a neutralized version of s, suitable as a filename.



106
107
108
109
# File 'lib/ruote/util/misc.rb', line 106

def self.neutralize(s)

  s.to_s.strip.gsub(/[ \/:;\*\\\+\?]/, '_')
end

.now_to_utc_sObject

Returns a parseable representation of the UTC time now.

like “2009/11/23 11:11:50.947109 UTC”



57
58
59
60
# File 'lib/ruote/util/time.rb', line 57

def self.now_to_utc_s

  time_to_utc_s(Time.now)
end

.or_split(filter) ⇒ Object

Used by Ruote.filter



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/ruote/util/filter.rb', line 77

def self.or_split(filter)

  return filter if filter.first.is_a?(Array)
  return [ filter ] if filter.empty? or ( ! filter.include?('or'))

  # [ {}, 'or', {}, {}, 'or', {} ]

  filter.inject([ [] ]) do |result, fl|
    if fl.is_a?(Hash)
      result.last << fl
    else
      result << []
    end
    result
  end
end

.p_caller(*msg) ⇒ Object

Prints the current call stack to stdout



40
41
42
43
44
45
46
# File 'lib/ruote/util/misc.rb', line 40

def self.p_caller(*msg)

  puts
  puts "  == #{msg.inspect} =="
  caller(1).each { |l| puts "  #{l}" }
  puts
end

.parse_ruby(ruby_string) ⇒ Object

Attempts to parse a string of Ruby code (and return the AST).



186
187
188
189
190
191
192
193
194
# File 'lib/ruote/util/misc.rb', line 186

def self.parse_ruby(ruby_string)

  Rufus::TreeChecker.parse(ruby_string)

rescue NoMethodError

  raise NoMethodError.new(
    "/!\\ please upgrade your rufus-treechecker gem /!\\")
end

.participant_send(participant, methods, arguments) ⇒ Object

Given a participant, a method name or an array of method names and a hash of arguments, will do its best to set the instance variables corresponding to the arguments (if possible) and to call the method with the right number of arguments…

Made it a Ruote module method so that RevParticipant might use it independently.

If the arguments hash contains a value keyed :default, that value is returned when none of the methods is responded to by the participant. Else if :default is not set or is set to nil, a NoMethodError.

Raises:

  • (NoMethodError)


182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/ruote/svc/dispatch_pool.rb', line 182

def self.participant_send(participant, methods, arguments)

  default = arguments.delete(:default)

  # set instance variables if possible

  arguments.each do |key, value|
    setter = "#{key}="
    participant.send(setter, value) if participant.respond_to?(setter)
  end

  # call the method, with the right arity

  Array(methods).each do |method|

    next unless participant.respond_to?(method)

    return participant.send(method) if participant.method(method).arity == 0

    args = arguments.keys.sort.collect { |k| arguments[k] }
      # luckily, our arg keys are in the alphabetical order (fei, flavour)

    return participant.send(method, *args)
  end

  return default unless default == nil

  raise NoMethodError.new(
    "undefined method `#{methods.first}' for #{participant.class}")
end

.process_definition(*attributes, &block) ⇒ Object

Same as Ruote.define()

pdef = Ruote.process_definition :name => 'take_out_garbage' do
  sequence do
    take_out_regular_garbage
    take_out_paper
  end
end

engine.launch(pdef)


59
60
61
62
# File 'lib/ruote/reader/ruby_dsl.rb', line 59

def self.process_definition(*attributes, &block)

  define(*attributes, &block)
end

.recompose_tree(h, pos = '0') ⇒ Object

Used by Ruote::ProcessStatus.

Given a decomposed tree like

{ '0' => [ 'define', { 'name' => 'nada' } ],
  '0_0' => [ 'sequence', {} ],
  '0_0_0' => [ 'alpha', {} ],
  '0_0_1' => [ 'bravo', {} ] },

will recompose it to

[ 'define', { 'name' => 'nada' }, [
  [ 'sequence', {}, [ [ 'alpha', {}, [] ], [ 'bravo', {}, [] ] ] ]
] ]

A starting point in the recomposition can be given with the ‘pos’ argument.



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/ruote/util/tree.rb', line 101

def self.recompose_tree(h, pos='0')

  t = h[pos]

  return nil unless t

  t << []
  i = 0

  loop do
    tt = recompose_tree(h, "#{pos}_#{i}")
    break unless tt
    t.last << tt
    i = i + 1
  end

  t
end

.regex_or_s(s) ⇒ Object

regex_or_s(“/nada/”) #==> /nada/

regex_or_s("nada") #==> "nada"
regex_or_s(/nada/) #==> /nada/


153
154
155
156
157
158
159
160
# File 'lib/ruote/util/misc.rb', line 153

def self.regex_or_s(s)

  if s.is_a?(String) && m = REGEX_IN_STRING.match(s)
    Regexp.new(m[1])
  else
    s
  end
end

.s_to_at(s) ⇒ Object

Turns a date or a duration to a Time object pointing AT a point in time…

(my prose is weak)



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ruote/util/time.rb', line 66

def self.s_to_at(s)

  at = if s.index(' ')
    #
    # date

    Rufus.to_ruby_time(s)# rescue nil

  else
    #
    # duration

    Time.now.utc.to_f + Rufus.parse_time_string(s)
  end

  case at
    when DateTime then at.to_time.utc
    when Float then Time.at(at).utc
    else at
  end
end

.schedule_to_h(sched) ⇒ Object

Refines a schedule as found in the ruote storage into something a bit easier to present.



1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
# File 'lib/ruote/dashboard.rb', line 1223

def self.schedule_to_h(sched)

  h = sched.dup

  class << h; attr_accessor :h; end
  h.h = sched
    #
    # for the sake of ProcessStatus#to_h

  h.delete('_rev')
  h.delete('type')
  msg = h.delete('msg')
  owner = h.delete('owner')

  h['wfid'] = owner['wfid']
  h['action'] = msg['action']
  h['type'] = msg['flavour']
  h['owner'] = Ruote::FlowExpressionId.new(owner)

  h['target'] = Ruote::FlowExpressionId.new(msg['fei']) if msg['fei']

  h
end

.set(collection, key, value) ⇒ Object

h = { ‘customer’ => { ‘name’ => ‘alpha’ } }

Ruote.set(h, 'customer.name', 'bravo')

h #=> { 'customer' => { 'name' => 'bravo' } }


79
80
81
82
83
84
85
86
87
88
89
# File 'lib/ruote/util/lookup.rb', line 79

def self.set(collection, key, value)

  k, c = lookup(collection, key, true)

  if c
    k = k.to_i if c.is_a?(Array)
    c[k] = value
  else
    collection[key] = value
  end
end

.sid(fei) ⇒ Object

A shorter shortcut for

Ruote::FlowExpressionId.to_storage_id(fei)


48
49
50
51
# File 'lib/ruote/fei.rb', line 48

def self.sid(fei)

  Ruote::FlowExpressionId.to_storage_id(fei)
end

.time_to_utc_s(t) ⇒ Object

Produces the UTC string representation of a Time

like “2009/11/23 11:11:50.947109 UTC”



48
49
50
51
# File 'lib/ruote/util/time.rb', line 48

def self.time_to_utc_s(t)

  "#{t.utc.strftime('%Y-%m-%d %H:%M:%S')}.#{sprintf('%06d', t.usec)} UTC"
end

.to_storage_id(fei) ⇒ Object

A shortcut for

Ruote::FlowExpressionId.to_storage_id(fei)


39
40
41
42
# File 'lib/ruote/fei.rb', line 39

def self.to_storage_id(fei)

  Ruote::FlowExpressionId.to_storage_id(fei)
end

.to_tree(&block) ⇒ Object Also known as: tree

Similar in purpose to Ruote.define and Ruote.process_definition but instead of returning a [process] definition, returns the tree.

tree = Ruote.process_definition :name => 'take_out_garbage' do
  sequence do
    take_out_regular_garbage
    take_out_paper
  end
end

p tree
  # => [ 'sequence', {}, [ [ 'take_out_regular_garbage', {}, [] ], [ 'take_out_paper', {}, [] ] ] ],

This is useful when modifying a process instance via methods like re_apply :

engine.re_apply(
  fei,
  :tree => Ruote.to_tree {
    sequence do
      participant 'alfred'
      participant 'bob'
    end
  })
    #
    # cancels the segment of process at fei and replaces it with
    # a simple alfred-bob sequence.


91
92
93
94
# File 'lib/ruote/reader/ruby_dsl.rb', line 91

def self.to_tree(&block)

  RubyDsl.create_branch('x', {}, &block).last.first
end

.tree_to_dot(tree, name = 'ruote process definition') ⇒ Object

Turns a process definition tree to a graphviz dot representation.

www.graphviz.org



32
33
34
35
36
37
# File 'lib/ruote/tree_dot.rb', line 32

def self.tree_to_dot(tree, name='ruote process definition')

  s = "digraph \"#{name}\" {\n"
  s << branch_to_dot('0', tree).join("\n")
  s << "\n}\n"
end

.tree_to_s(tree, expid = '0') ⇒ Object

Turning a tree into a numbered string view

require 'ruote/util/tree'
require 'ruote/reader/ruby_dsl'

pdef = Ruote.process_definition :name => 'def0' do
  sequence do
    alpha
    bravo
  end
end

p pdef
  # => ["define", {"name"=>"def0"}, [["sequence", {}, [["alpha", {}, []], ["bravo", {}, []]]]]]

puts Ruote.tree_to_s(pdef)
  # =>
  #    0  define {"name"=>"def0"}
  #      0_0  sequence {}
  #        0_0_0  alpha {}
  #        0_0_1  bravo {}


50
51
52
53
54
55
56
# File 'lib/ruote/util/tree.rb', line 50

def self.tree_to_s(tree, expid='0')

  d = expid.split('_').size - 1
  s = "#{' ' * d * 2}#{expid}  #{tree[0]} #{tree[1].inspect}\n"
  tree[2].each_with_index { |t, i| s << tree_to_s(t, "#{expid}_#{i}") }
  s
end

.unset(collection, key) ⇒ Object

h = { ‘customer’ => { ‘name’ => ‘alpha’, ‘rank’ => ‘1st’ } }

r = Ruote.unset(h, 'customer.rank')

h # => { 'customer' => { 'name' => 'alpha' } }
r # => '1st'


97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/ruote/util/lookup.rb', line 97

def self.unset(collection, key)

  k, c = lookup(collection, key, true)

  if c.nil?
    collection.delete(key)
  elsif c.is_a?(Array)
    c.delete_at(Integer(k)) rescue nil
  elsif c.is_a?(Hash)
    c.delete(k)
  else
    nil
  end
end