class Functio::Function

Represents a function.

Constants

MAX_NAME_SIZE

Maximum size of the function name.

NAME_PATTERN

Pattern for valid function name format.

Attributes

expression[R]

Expression instance used for Function definition.

name[R]

Function name.

Public Class Methods

build(attributes) click to toggle source

Builds a new Function instance by Function attributes. attributes is a Hash containing :name and :definition. Raises InvalidFunctionError if some of the attributes are invalid. Raises DivisionByZeroError if :definition contains a division by zero.

# File lib/functio/function.rb, line 42
def self.build(attributes)
  expression = Expression.new(attributes[:definition])
  new(name: attributes[:name], expression: expression)
rescue InvalidExpressionError
  raise InvalidFunctionError, 'definition must be a valid expression'
end
new(args) click to toggle source

Constructs a Function instance. The parameter args is a Hash containing the function :name and an :expression instance.

# File lib/functio/function.rb, line 51
def initialize(args)
  @name = validate_name(args[:name])
  @expression = args[:expression]
end

Public Instance Methods

==(other) click to toggle source

Compares equality between Function instances. Returns true if Function#attributes of this instance is equal to Function#attributes of other.

# File lib/functio/function.rb, line 80
def ==(other)
  attributes == other.attributes
end
attributes() click to toggle source

Function attributes.

# File lib/functio/function.rb, line 62
def attributes
  { name: name, definition: definition }
end
definition() click to toggle source

Function definition.

# File lib/functio/function.rb, line 57
def definition
  expression.expression
end
params() click to toggle source

Returns the function input parameters in an Array of Strings.

# File lib/functio/function.rb, line 67
def params
  expression.variables
end
use(args = {}) click to toggle source

Uses function with args Hash. The keys of args Hash are the input parameters and the values are the input arguments.

# File lib/functio/function.rb, line 73
def use(args = {})
  expression.evaluate(args)
end

Private Instance Methods

valid_name_format?(name) click to toggle source
# File lib/functio/function.rb, line 100
def valid_name_format?(name)
  name =~ NAME_PATTERN
end
valid_name_size?(name) click to toggle source
# File lib/functio/function.rb, line 96
def valid_name_size?(name)
  name.size <= MAX_NAME_SIZE
end
validate_name(name) click to toggle source
# File lib/functio/function.rb, line 86
def validate_name(name)
  raise InvalidFunctionError,
        "name size can't be greater than #{MAX_NAME_SIZE} characters" unless
    valid_name_size?(name)
  raise InvalidFunctionError,
        'name must be alphanumeric and begin with a letter' unless
    valid_name_format?(name)
  name
end