Module: CFoundry::V2::ModelMagic::QueryableBy

Included in:
CFoundry::V2::ModelMagic
Defined in:
lib/cfoundry/v2/model_magic/queryable_by.rb

Instance Method Summary collapse

Instance Method Details

#queryable_by(*names) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/cfoundry/v2/model_magic/queryable_by.rb', line 3

def queryable_by(*names)
  klass = self
  singular = object_name
  plural = plural_object_name

  query = ::CFoundry::V2::QUERIES[singular]

  query.module_eval do
    names.each do |name|
      #
      # def MODEL_by_ATTRIBUTE
      #
      define_method(:"#{singular}_by_#{name}") do |*args|
        send(:"#{plural}_by_#{name}", *args).first
      end

      #
      # def MODELs_by_ATTRIBUTE
      #
      define_method(:"#{plural}_by_#{name}") do |val, *args|
        options, _ = args
        options ||= {}
        options[:query] = [name, val]

        query_target(klass).send(plural, options)
      end
    end
  end

  const_set(:Queries, query)

  ClientMethods.module_eval do
    include query
  end
end