Module: CsvRecord::Reader::ClassMethods

Defined in:
lib/csv_record/csv_readers/class_reader.rb

Constant Summary collapse

DYNAMIC_FINDER_PATTERN =
/^find_by_(.+)$/

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



54
55
56
57
58
59
60
61
62
# File 'lib/csv_record/csv_readers/class_reader.rb', line 54

def method_missing(meth, *args, &block)
  if meth.to_s =~ DYNAMIC_FINDER_PATTERN
    dynamic_finder $1, *args, &block
  else
    super # You *must* call super if you don't handle the
          # method, otherwise you'll mess up Ruby's method
          # lookup.
  end
end

Instance Method Details

#__count__Object Also known as: count



40
41
42
43
44
# File 'lib/csv_record/csv_readers/class_reader.rb', line 40

def __count__
  open_database_file do |csv|
    csv.entries.size
  end
end

#__doppelganger_fields__Object Also known as: doppelganger_fields



22
23
24
# File 'lib/csv_record/csv_readers/class_reader.rb', line 22

def __doppelganger_fields__
  self.__fields__.map &:doppelganger
end

#__fields__Object Also known as: fields



18
19
20
# File 'lib/csv_record/csv_readers/class_reader.rb', line 18

def __fields__
  @fields ||= CsvRecord::CsvFields.new
end

#__find__(condition) ⇒ Object Also known as: find



46
47
48
# File 'lib/csv_record/csv_readers/class_reader.rb', line 46

def __find__(condition)
  (__where__ id: condition.to_param).first
end

#__where__(params) ⇒ Object Also known as: where



50
51
52
# File 'lib/csv_record/csv_readers/class_reader.rb', line 50

def __where__(params)
  CsvRecord::Query.new self, params
end

#allObject



26
27
28
29
30
# File 'lib/csv_record/csv_readers/class_reader.rb', line 26

def all
  open_database_file do |csv|
    csv.entries.map { |attributes| self.build attributes }
  end
end

#build(params = {}) {|inst| ... } ⇒ Object

Yields:

  • (inst)


7
8
9
10
11
12
13
14
15
16
# File 'lib/csv_record/csv_readers/class_reader.rb', line 7

def build(params={})
  inst = new
  params.each do |key, value|
    attribute = fields.find_with_doppelganger(key)
    attr_name = attribute ? attribute.name : key
    inst.public_send "#{attr_name}=", value
  end if params
  yield inst if block_given?
  inst
end

#firstObject



32
33
34
# File 'lib/csv_record/csv_readers/class_reader.rb', line 32

def first
  all.first
end

#lastObject



36
37
38
# File 'lib/csv_record/csv_readers/class_reader.rb', line 36

def last
  all.last
end

#respond_to?(meth) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/csv_record/csv_readers/class_reader.rb', line 64

def respond_to?(meth)
  (meth.to_s =~ DYNAMIC_FINDER_PATTERN) || super
end