Module: Glamazon::Finder

Included in:
Associations::HasMany
Defined in:
lib/glamazon/finder.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/glamazon/finder.rb', line 6

def method_missing(meth, *args, &blk)
  # Dynamic finders, e.g. Klass.find_by_foo('bar)
  a = extract_attribute_from_method_name(meth)
  if /find_by_([_a-zA-Z]\w*)/.match(meth.to_s)
    self.class.instance_eval do
      define_method(meth) { |val| all.detect { |o| o[a] == val } }
    end
    send meth, args.first
  elsif /find_all_by_([_a-zA-Z]\w*)/.match(meth.to_s)
    self.class.instance_eval do
      define_method(meth) { |val| all.select { |o| o[a] == val } }
    end
    send meth, args.first
  elsif /find_or_create_by_([_a-zA-Z]\w*)/.match(meth.to_s)
    self.class.instance_eval do
      define_method(meth) do |val|
        send("find_by_#{a}", val) || create(a.to_sym => val)
      end
    end
    send meth, args.first
  else
    super
  end
end

Instance Method Details

#find(id) ⇒ Object



3
4
5
# File 'lib/glamazon/finder.rb', line 3

def find(id)
  find_by_id(id)
end