Class: HashField

Inherits:
Field show all
Defined in:
lib/yodel/models/core/fields/hash_field.rb

Constant Summary

Constants inherited from Field

Field::TYPES

Instance Attribute Summary

Attributes inherited from Field

#name, #options

Instance Method Summary collapse

Methods inherited from Field

#default_input_type, #display?, field_from_type, from_options, #include_in_search_keywords?, #index?, #inherited?, #method_missing, #numeric?, #required?, #searchable?, #strip_nil?, #to_json, #to_str, #unique?, #validate

Constructor Details

#initialize(name, options = {}) ⇒ HashField

TODO: validate should defer to @element_type over each element



3
4
5
6
# File 'lib/yodel/models/core/fields/hash_field.rb', line 3

def initialize(name, options={})
  @element_type = Field.from_options(name, 'type' => options['of'].to_s) if options['of']
  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Field

Instance Method Details

#from_json(value, record) ⇒ Object



39
40
41
42
# File 'lib/yodel/models/core/fields/hash_field.rb', line 39

def from_json(value, record)
  return {} if value.blank? || !value.is_a?(Hash)
  process(value, record, :from_json)
end

#json_action(action, value, record) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/yodel/models/core/fields/hash_field.rb', line 8

def json_action(action, value, record)
  hash = record.get_raw(name)
  
  if action == 'remove'
    value = [value] unless value.is_a?(Array)
    keys = value.collect(&:to_s)
    hash.delete_if {|key, _| keys.include?(key)}
  else
    raise "Set or merge actions on a hash must be passed a hash" unless value.is_a?(Hash)
    value = process(value, record, :from_json)
    if action == 'set'
      hash = value
    elsif action == 'merge'
      hash.merge!(value)
    end
  end
  
  record.set_raw(name, hash)
  record.changed!(name)
end

#typecast(value, record) ⇒ Object



29
30
31
32
# File 'lib/yodel/models/core/fields/hash_field.rb', line 29

def typecast(value, record)
  value = {} unless value.is_a?(Hash)
  ChangeSensitiveHash.new(record, name, process(value, record, :typecast))
end

#untypecast(value, record) ⇒ Object



34
35
36
37
# File 'lib/yodel/models/core/fields/hash_field.rb', line 34

def untypecast(value, record)
  return {} if value.blank? || !value.respond_to?(:to_hash)
  process(value, record, :untypecast)
end