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
12
# File 'lib/chewy/fields/base.rb', line 7

def initialize(name, options = {})
  @name = name.to_sym
  @options = 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(*objects) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/chewy/fields/base.rb', line 34

def compose(*objects)
  object = objects.first

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

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

  {name => result}
end

#mappings_hashObject



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/chewy/fields/base.rb', line 22

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

#multi_field?Boolean

Returns:

  • (Boolean)


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

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

#object_field?Boolean

Returns:

  • (Boolean)


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

def object_field?
  (children.present? && options[:type].blank?) || %w[object nested].include?(options[:type].to_s)
end