Class: Excelizer::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/excelizer.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.attr_downloadable(*attrs) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/excelizer.rb', line 6

def self.attr_downloadable(*attrs)
  attrs.each do |attr|
    define_method(attr) do
      self.instance_variable_get("@#{attr}")
    end
  end
end

.attr_headers(*attrs) ⇒ Object



14
15
16
# File 'lib/excelizer.rb', line 14

def self.attr_headers(*attrs)
  @headers = attrs.to_a
end

Instance Method Details

#build_xls(collection = model_class.all) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/excelizer.rb', line 18

def build_xls(collection=model_class.all)
  if @headers
    headers = @headers
  else
    headers = *methods.select { |m| self.method(m).owner == self.class }.map { |m| m.to_s.titleize }
  end
  records = get_collection_data(collection)

  Excelizer::Writer.write headers, records
end

#get_collection_data(collection = model_class.all) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/excelizer.rb', line 29

def get_collection_data(collection=model_class.all)
  model_methods = model_clean_attributes model_class

  # Gets the methods in the class definition and attr_downloadable
  own_methods = methods.select { |m| self.method(m).owner == self.class }

  # If the model class has the same method as the one defined in
  # attr_downloadble, that method will be called.
  collection.map do |model_instance|
    @model = model_instance
    own_methods.map do |attr|
      # Checks if the model has a method with the same name and
      # if the class definition overrides the model method
      reciever = self
      if model_methods.include?(attr.to_s) && reciever.send(attr).nil?
        reciever = model_instance
      end
      reciever.send(attr)
    end.compact
  end
end

#model_classObject



51
52
53
# File 'lib/excelizer.rb', line 51

def model_class
  Object.const_get self.class.name.gsub "Downloader", ""
end

#model_clean_attributes(model_class_ref) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/excelizer.rb', line 55

def model_clean_attributes(model_class_ref)
  explicit_attribute_keys = model_class_ref.new.attributes.keys

  if model_class_ref.respond_to?(:protected_attributes)
    explicit_attribute_keys - model_class_ref.protected_attributes.to_a
  else
    explicit_attribute_keys
  end
end