Class: Garnish::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Converter
Defined in:
lib/garnish/collection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Converter

#convert, #module_exists?

Constructor Details

#initialize(relation, template) ⇒ Collection

Returns a new instance of Collection.



11
12
13
14
# File 'lib/garnish/collection.rb', line 11

def initialize(relation, template)
  @relation = relation
  @template = template
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (protected)



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/garnish/collection.rb', line 44

def method_missing(method, *args, &block)
  resp = @relation.send(method, *args, &block)

  if resp.equal? @relation
    self
  elsif resp.instance_of? @relation.class
    Garnish::Collection.new(resp, @template)
  elsif resp.respond_to? :each
    Garnish::Collection.new(resp, @template)
  else
    convert(resp)
    resp
  end
end

Instance Attribute Details

#relationObject

Returns the value of attribute relation.



6
7
8
# File 'lib/garnish/collection.rb', line 6

def relation
  @relation
end

#templateObject

Returns the value of attribute template.



7
8
9
# File 'lib/garnish/collection.rb', line 7

def template
  @template
end

Instance Method Details

#each(&block) ⇒ Collection

Call each on the relation and return the block

Examples:

blog.posts.each { |post| post.name }

Returns:



22
23
24
# File 'lib/garnish/collection.rb', line 22

def each(&block)
  to_a.each { |member| block.call(member) }
end

#respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/garnish/collection.rb', line 38

def respond_to?(method)
  @relation.respond_to?(method)
end

#to_aCollection

Call to_a and return converted records

Examples:

blog.posts.each { |post| post.name }

Returns:



32
33
34
35
36
# File 'lib/garnish/collection.rb', line 32

def to_a
  records = @relation.to_a
  convert(records)
  records
end