Class: CaringForm::Tools::Referee

Inherits:
Object
  • Object
show all
Defined in:
lib/caring_form/tools/referee.rb

Overview

A referee is a tool used to execute rules stored in a field attribute against value(s) retrieved from a form instance. The referee decides if the rule is true or false for the form instance.

i.e.:

field = OpenStruct.new(:optional => {:absent => :band_name})
form = OpenStruct.new(:band_name => "")
referee = Tools::Referee.new(field)

# We want to know if the field is optional 
referee.decide(:optional, form) # => true, because the band name is absent
form.band_name = "Everything But The Girl"
referee.decide(:optional, form) # => false, now that there is a band name, the field is not optional anymore

# We also need to verify that on the front-end, so the referee can translate
# the rule into a data attribute key value pair
def form.field_id(name); "form_name_index_#{name}"; end
referee.rule_as_data_attribute(:optional, form)  # => data-optional-if-absent="#form_name_index_band_name"

Instance Method Summary collapse

Constructor Details

#initialize(field) ⇒ Referee

Returns a new instance of Referee.



22
23
24
# File 'lib/caring_form/tools/referee.rb', line 22

def initialize(field)
  @field = field
end

Instance Method Details

#decide(property, form) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/caring_form/tools/referee.rb', line 26

def decide(property, form)
  case (value = @field.send(property))
  when true then true
  when false then false
  else
    execute_rule(value, form)
  end
end

#execute_rule(rule, form) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/caring_form/tools/referee.rb', line 35

def execute_rule(rule, form)
  type = rule.keys.first
  attribute = rule[type]
  case type
  when :absent then  form.send(attribute).blank?
  when :present then form.send(attribute).present?
  else
    false
  end
end

#is_rule?(property) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/caring_form/tools/referee.rb', line 46

def is_rule?(property)
  @field.send(property).is_a?(Hash)
end

#rule_as_data_attribute(property, form) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/caring_form/tools/referee.rb', line 50

def rule_as_data_attribute(property, form)
  rule = @field.send(property)
  if rule.respond_to?(:keys) && (type = rule.keys.first)
    name = :"data-#{property}-if-#{type}"
    id   = "##{form.field_id(rule[type])}"
    {name => id}
  else
    {}
  end
end