Class: ActiveModel::Serializer::Association::HasOne

Inherits:
ActiveModel::Serializer::Association show all
Defined in:
lib/active_model/serializer/associations.rb

Overview

:nodoc:

Instance Attribute Summary

Attributes inherited from ActiveModel::Serializer::Association

#embed_ids, #embed_in_root, #embed_objects, #name, #object

Instance Method Summary collapse

Methods inherited from ActiveModel::Serializer::Association

#key

Constructor Details

#initialize(name, options = {}, serializer_options = {}) ⇒ HasOne

Returns a new instance of HasOne.



114
115
116
117
# File 'lib/active_model/serializer/associations.rb', line 114

def initialize(name, options={}, serializer_options={})
  super
  @polymorphic = options[:polymorphic]
end

Instance Method Details

#embeddable?Boolean

Returns:

  • (Boolean)


133
134
135
# File 'lib/active_model/serializer/associations.rb', line 133

def embeddable?
  super || !polymorphic?
end

#id_keyObject



129
130
131
# File 'lib/active_model/serializer/associations.rb', line 129

def id_key
  "#{name}_id".to_sym
end

#rootObject



119
120
121
122
123
124
125
126
127
# File 'lib/active_model/serializer/associations.rb', line 119

def root
  if root = options[:root]
    root
  elsif polymorphic?
    object.class.to_s.pluralize.demodulize.underscore.to_sym
  else
    name.to_s.pluralize.to_sym
  end
end

#serializablesObject



137
138
139
140
# File 'lib/active_model/serializer/associations.rb', line 137

def serializables
  value = object && find_serializable(object)
  value ? [value] : []
end

#serializeObject



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/active_model/serializer/associations.rb', line 142

def serialize
  if object
    if polymorphic?
      {
        :type => polymorphic_key,
        polymorphic_key => find_serializable(object).serializable_hash
      }
    else
      find_serializable(object).serializable_hash
    end
  end
end

#serialize_idsObject



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/active_model/serializer/associations.rb', line 155

def serialize_ids
  if object
    serializer = find_serializable(object)
    id =
      if serializer.respond_to?(embed_key)
        serializer.send(embed_key)
      else
        object.read_attribute_for_serialization(embed_key)
      end

    if polymorphic?
      {
        type: polymorphic_key,
        id: id
      }
    else
      id
    end
  end
end