Class: Snapi::Function

Inherits:
Struct
  • Object
show all
Defined in:
lib/snapi/function.rb

Overview

Functions are a core part of capability declaration as a capability is basically a collection of functions.

Functions take arguments and return a pre-defined type of data structure.

Right now Functions are structs which accept arguments and return_type messages as well as a few DSL methods to help define them dynamically

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#argumentsObject

Returns the value of attribute arguments

Returns:

  • (Object)

    the current value of arguments



12
13
14
# File 'lib/snapi/function.rb', line 12

def arguments
  @arguments
end

#return_typeObject

Returns the value of attribute return_type

Returns:

  • (Object)

    the current value of return_type



12
13
14
# File 'lib/snapi/function.rb', line 12

def return_type
  @return_type
end

Instance Method Details

#argument(name) ⇒ Object

DSL setter to define a the meta information for an argument for the Function

Yields the argument to a given block for nice defition



21
22
23
24
25
26
27
28
# File 'lib/snapi/function.rb', line 21

def argument(name)
  arg = Argument.new
  if block_given?
    yield(arg)
  end
  self.arguments = {} if self.arguments == nil
  self.arguments[name] = arg
end

#return(type) ⇒ Object

DSL Setter to define the type of data returned by this function

TODO currently allows types of ‘none’, ‘raw’ or ‘structured’ but should support ‘structured



36
37
38
39
40
41
# File 'lib/snapi/function.rb', line 36

def return(type)
  valid = %w{ none raw structured }.include? type.to_s
  raise InvalidReturnTypeError unless valid

  self.return_type = type
end

#to_hashObject

Hash representation of function including argument meta-data as a hash.



47
48
49
50
51
# File 'lib/snapi/function.rb', line 47

def to_hash
  args_hash =  {}
  arguments.each { |k,v| args_hash[k] = v.attributes } if arguments
  { return_type: return_type }.merge args_hash
end

#valid_args?(args = {}) ⇒ Boolean

This method accepts a hash (as from a web request) which it uses to compare against its argument definitions in order to do some upfront validation before trying to run the function names as defined in the library_class

TODO: build up an errors hash to disclose what the issue is

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
71
# File 'lib/snapi/function.rb', line 62

def valid_args?(args={})
  valid = false
  arguments.each do |name, argument|
    if argument[:required]
      return false if args[name] == nil
    end
    valid =  argument.valid_input?(args[name])
  end
  return valid
end