Class: Halogen::Definition

Inherits:
Object
  • Object
show all
Defined in:
lib/halogen/definition.rb

Overview

Stores instructions for how to render a value for a given representer instance

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options, procedure) ⇒ Halogen::Definition

Construct a new Definition instance

Parameters:

  • name (Symbol, String)

    definition name

  • options (Hash)

    hash of options


19
20
21
22
23
# File 'lib/halogen/definition.rb', line 19

def initialize(name, options, procedure)
  @name      = name.to_sym
  @options   = Halogen::HashUtil.symbolize_keys!(options)
  @procedure = procedure
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name


8
9
10
# File 'lib/halogen/definition.rb', line 8

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options


8
9
10
# File 'lib/halogen/definition.rb', line 8

def options
  @options
end

#procedureObject

Returns the value of attribute procedure


10
11
12
# File 'lib/halogen/definition.rb', line 10

def procedure
  @procedure
end

Instance Method Details

#enabled?(instance) ⇒ true, false

Returns whether this definition should be included based on its conditional guard, if any.

Returns:

  • (true, false)

    whether this definition should be included based on its conditional guard, if any


37
38
39
40
41
42
43
44
45
# File 'lib/halogen/definition.rb', line 37

def enabled?(instance)
  if options.key?(:if)
    !!eval_guard(instance, options.fetch(:if))
  elsif options.key?(:unless)
    !eval_guard(instance, options.fetch(:unless))
  else
    true
  end
end

#validatetrue

Returns if nothing is raised.

Returns:

  • (true)

    if nothing is raised

Raises:


51
52
53
54
55
56
# File 'lib/halogen/definition.rb', line 51

def validate
  return true unless options.key?(:value) && procedure

  fail InvalidDefinition,
       "Cannot specify both value and procedure for #{name}"
end

#value(instance) ⇒ Object

Parameters:

  • instance (Object)

    the representer instance with which to evaluate the stored procedure


28
29
30
31
32
# File 'lib/halogen/definition.rb', line 28

def value(instance)
  options.fetch(:value) do
    procedure ? instance.instance_eval(&procedure) : instance.send(name)
  end
end