Class: Chewy::Fields::Base

Inherits:
Object show all
Defined in:
lib/chewy/fields/base.rb

Direct Known Subclasses

Root

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Base.



7
8
9
10
11
# File 'lib/chewy/fields/base.rb', line 7

def initialize(name, options = {})
  @name, @options = name.to_sym, options.deep_symbolize_keys
  @value = @options.delete(:value)
  @children = []
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



4
5
6
# File 'lib/chewy/fields/base.rb', line 4

def children
  @children
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/chewy/fields/base.rb', line 4

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/chewy/fields/base.rb', line 4

def options
  @options
end

#parentObject

Returns the value of attribute parent.



5
6
7
# File 'lib/chewy/fields/base.rb', line 5

def parent
  @parent
end

#valueObject (readonly)

Returns the value of attribute value.



4
5
6
# File 'lib/chewy/fields/base.rb', line 4

def value
  @value
end

Instance Method Details

#compose(object, *parent_objects) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/chewy/fields/base.rb', line 30

def compose(object, *parent_objects)
  objects = ([object] + parent_objects.flatten).uniq

  result = if value && value.is_a?(Proc)
    if value.arity == 0
      object.instance_exec(&value)
    elsif value.arity < 0
      value.call(*object)
    else
      value.call(*objects.first(value.arity))
    end
  elsif object.is_a?(Hash)
    object[name] || object[name.to_s]
  else
    object.send(name)
  end

  result = if result.respond_to?(:to_ary)
    result.to_ary.map { |result| compose_children(result, *objects) }
  else
    compose_children(result, *objects)
  end if children.any? && !multi_field?

  {name => result.as_json(root: false)}
end

#mappings_hashObject



21
22
23
24
25
26
27
28
# File 'lib/chewy/fields/base.rb', line 21

def mappings_hash
  mapping = children.any? ? {
    (multi_field? ? :fields : :properties) => children.map(&:mappings_hash).inject(:merge)
  } : {}
  mapping.reverse_merge!(options)
  mapping.reverse_merge!(type: (children.any? ? 'object' : 'string'))
  {name => mapping}
end

#multi_field?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/chewy/fields/base.rb', line 13

def multi_field?
  children.any? && !object_field?
end

#object_field?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/chewy/fields/base.rb', line 17

def object_field?
  (children.any? && options[:type].blank?) || ['object', 'nested'].include?(options[:type].to_s)
end