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



17
18
19
20
21
# File 'lib/halogen/definition.rb', line 17

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.



6
7
8
# File 'lib/halogen/definition.rb', line 6

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/halogen/definition.rb', line 6

def options
  @options
end

#procedureObject

Returns the value of attribute procedure.



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

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



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

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:



49
50
51
52
53
54
# File 'lib/halogen/definition.rb', line 49

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



26
27
28
29
30
# File 'lib/halogen/definition.rb', line 26

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