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(klass, context_name) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/attribute_serializer.rb', line 58

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

  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
49
# File 'lib/attribute_serializer.rb', line 42

def generate(context_name, object)
  return object if object.is_a?(Hash) && context_name == :default
  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:

  • (ArgumentError)


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

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