Module: AttributeSerializer

Extended by:
AttributeSerializer
Included in:
AttributeSerializer
Defined in:
lib/attribute_serializer.rb

Overview

Implementation

Defined Under Namespace

Classes: Context

Instance Method Summary collapse

Instance Method Details

#add_context_set(klass, context_name, attribs, &delegate_methods) ⇒ Object



37
38
39
40
# File 'lib/attribute_serializer.rb', line 37

def add_context_set(klass, context_name, attribs, &delegate_methods)
  key = [klass, context_name]
  contexts[key] = Context.new klass, attribs, &delegate_methods
end

#context_for(key) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/attribute_serializer.rb', line 56

def context_for(key)
  closest_context_match = contexts.keys.select do |klass,context_name|
    key.first.ancestors.include?(klass) && key.last == context_name
  end.min_by { |(klass, _)| key.first.ancestors.index(klass) }

  contexts[closest_context_match]
end

#contextsObject



33
34
35
# File 'lib/attribute_serializer.rb', line 33

def contexts
  @contexts ||= {}
end

#generate(context_name, object) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/attribute_serializer.rb', line 42

def generate(context_name, object)
  if object.respond_to? :collect
    object.collect { |o| generate_single(o.class, context_name, o) }
  else
    generate_single(object.class, context_name, object)
  end
end

#generate_single(klass, context_name, object) ⇒ Object

Raises:



50
51
52
53
54
# File 'lib/attribute_serializer.rb', line 50

def generate_single(klass, context_name, object)
  context = context_for([klass, context_name])
  raise ArgumentError, "no contextual attributes setup for #{klass}:#{context_name}" unless context
  context.generate(object)
end