Class: Rooftop::Content::Collection

Inherits:
Array
  • Object
show all
Defined in:
lib/rooftop/content/collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(content_fields) ⇒ Collection

Returns a new instance of Collection.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rooftop/content/collection.rb', line 4

def initialize(content_fields)
  content_fields.each do |field|
    # if the field has a 'fields' key, it is a repeater field. Collect the sub-fields and
    # set the field content to the collection of repeated fields
    if field.has_key?('fields')
      repeated_fields = field[:fields].collect do |repeated_fields|
        repeated_fields.collect{|field| Rooftop::Content::Field.new(field)}
      end
      
      field.delete(:fields)
      field[:value] = repeated_fields
    end

    self << Rooftop::Content::Field.new(field)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



39
40
41
42
43
44
45
46
# File 'lib/rooftop/content/collection.rb', line 39

def method_missing(method, *args, &block)
  fields = named(method)
  if fields.length > 0
    fields.first.value
  else
    raise Rooftop::Content::FieldNotFoundError, "No field named #{method} was found"
  end
end

Instance Method Details

#field_namesObject Also known as: names



33
34
35
# File 'lib/rooftop/content/collection.rb', line 33

def field_names
  collect(&:name)
end

#find_by(hash) ⇒ Object

Find content_fields by attribute. Assume there will only be one attribute in the search

Raises:



22
23
24
25
26
27
# File 'lib/rooftop/content/collection.rb', line 22

def find_by(hash)
  raise ArgumentError, "you can only find a field by one attribute at a time" unless hash.length == 1
  attr = hash.first.first
  val = hash.first.last
  self.select {|l| l.send(attr) == val.to_s}
end

#named(name) ⇒ Object



29
30
31
# File 'lib/rooftop/content/collection.rb', line 29

def named(name)
  find_by(name: name.to_s)
end

#respond_to_missing?(method, private = false) ⇒ Boolean

Returns:



48
49
50
51
52
53
54
# File 'lib/rooftop/content/collection.rb', line 48

def respond_to_missing?(method, private=false)
  if named(method).length == 0
    super
  else
    true
  end
end