Module: Datapathy::Model::DynamicFinders::ClassMethods

Defined in:
lib/datapathy/model/dynamic_finders.rb

Defined Under Namespace

Classes: DynamicFinderMatch

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_id, *arguments, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/datapathy/model/dynamic_finders.rb', line 8

def method_missing(method_id, *arguments, &block)
  if match = DynamicFinderMatch.match(method_id)
    if match.finder?
      define_find_by(method_id, match)
    elsif match.instantiator?
      define_find_or_create_by(method_id, match)
    end
    send(method_id, *arguments, &block)
  else
    super
  end
end

Instance Method Details

#define_find_by(method_id, match) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/datapathy/model/dynamic_finders.rb', line 21

def define_find_by(method_id, match)
  self.class_eval %{
    def self.#{method_id}(*args)
      find_attributes = Hash[[:#{match.attribute_names.join(',:')}].zip(args)]

      #{match.finder == :first ? "detect(find_attributes)" : "select(find_attributes)"}
    end
  }, __FILE__, __LINE__
end

#define_find_or_create_by(method_id, match) ⇒ Object



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

def define_find_or_create_by(method_id, match)
  self.class_eval %{
    def self.#{method_id}(*args)
      if args[0].is_a?(Hash)
        attributes = args[0]
        find_attributes = attributes.slice(*[:#{match.attribute_names.join(',:')}])
      end

      record = detect(find_attributes)

      if record.nil?
        record = self.new(attributes)
        #{'record.save' if match.instantiator == :create}
      end

      record
    end
  }, __FILE__, __LINE__
end