Class: ActiveRepresenter::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Attributes, ActiveModel::Model
Defined in:
lib/active_representer/base.rb

Class Method Summary collapse

Class Method Details

.attr_collection(name, **options) ⇒ Object

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/active_representer/base.rb', line 41

def attr_collection(name, **options)
  unless name.is_a?(Symbol) || name.is_a?(String)
    raise ArgumentError.new("collection's name must be a Symbol or a String")
  end
  representer_name = \
    options[:representer_name] ? options[:representer_name] : guess_representrer_name(name.to_s)
  raise ArgumentError.new("representer_name must be a String") unless representer_name.is_a?(String)
  begin
    representer = representer_name.constantize
    collections[name.to_sym] = representer
  rescue NameError => e
    collections[name.to_sym] = nil
  end
  class_eval do
    attr_reader name.to_sym
  end
end

.attr_field(name, type = Type::Value.new, **options) ⇒ Object



37
38
39
# File 'lib/active_representer/base.rb', line 37

def attr_field(name, type = Type::Value.new, **options)
  attribute(name, type, **options)
end

.attribute_namesObject



63
64
65
# File 'lib/active_representer/base.rb', line 63

def attribute_names
  attribute_types.keys - ["wrapped"]
end

.collection_namesObject



59
60
61
# File 'lib/active_representer/base.rb', line 59

def collection_names
  collections.keys
end

.guess_representrer_name(name) ⇒ Object



67
68
69
# File 'lib/active_representer/base.rb', line 67

def guess_representrer_name(name)
  "#{name.singularize.camelize}Representer"
end

.wrap(wrapped) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/active_representer/base.rb', line 17

def wrap(wrapped)
  instance = new
  instance.wrapped = wrapped
  collection_names.each do |collection_name|
    next if wrapped[collection_name].nil?
    representer_klass = collections[collection_name]
    collection_value = \
      if representer_klass
        wrapped[collection_name].map { |item| representer_klass.wrap(item) }
      else
        wrapped[collection_name]
      end
    instance.instance_variable_set("@#{collection_name}", collection_value)
  end
  attribute_names.each do |attribute_name|
    instance.send("#{attribute_name}=", wrapped.send(attribute_name))
  end
  instance
end