Module: Intermodal::Proxies::WillPaginate::Collection

Defined in:
lib/intermodal/proxies/will_paginate.rb

Instance Method Summary collapse

Instance Method Details

#as_json(*args) ⇒ Object

TODO: This needs its own spec



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/intermodal/proxies/will_paginate.rb', line 14

def as_json(*args)
  options = args.extract_options!
  _root = options.delete(:root)
  _collection_name = _root || :collection

  # Scrub out everything else
  presenter_options = {
    :root => (options[:always_nest_collections] && _root ? _collection_name.to_s.singularize : nil),
    :always_nest_collections => options[:always_nest_collections],
    :scope => options[:scope],
    :presenter => options[:presenter] }
  pagination_info.merge({ _collection_name => self.to_a.as_json(presenter_options)})
end

#pagination_infoObject



6
7
8
9
10
11
# File 'lib/intermodal/proxies/will_paginate.rb', line 6

def pagination_info
  { :page => self.current_page.to_i,
    :per_page => self.per_page.to_i,
    :total_pages => self.total_pages,
    :total_entries => self.total_entries }
end

#to_xml(*args) ⇒ Object

TODO: This needs its own spec TODO: Should be refactored to have clearer code



30
31
32
33
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/intermodal/proxies/will_paginate.rb', line 30

def to_xml(*args)
  options = args.extract_options!
  _collection = self

  # For a paginated collection of say, books, we want the following output:
  #
  # <books>
  #   <collection>
  #     <book>
  #       <title> ... </title>
  # ...
  #
  # Since Rails 3.0 magically assumes that a hash
  # 
  #   { :collection => [ {:title => ' ... ' } ] } 
  #
  # outputs to
  #
  #   <collection>
  #     <collection>
  #       <title> ... </title>
  #
  # We need to use a custom builder. We use very kludgy code, by calling #to_xml
  # again, but override builder so it will nest things properly.
  #
  # Actually, it is also depending on some magic. Presenter/API options are saved
  # in the builder class, so it uses that. Which means this isn't side-effect-free
  # code. Ugh.
  #
  # Ultimately, this needs to be more modular so that API writers can specify their
  # own builder. For now, we'll dictate the auto-generated XML and wait until someone
  # complains about it in the Github Issues tracker.
  collection_builder = proc do |opts, key|
    _builder = opts[:builder]

    _builder.collection do
      _collection.to_a.map do |r| 
        r.presentation(options.except(:root)).
          to_xml(
            :root => r.class.name.demodulize.underscore,
            :builder => opts[:builder],
            :skip_instruct => true )
      end
    end
  end

  # Merge information such as current page, total pages, total entries, etc.
  pagination_info.
    merge({ :collection => collection_builder }).
    to_xml(options)
end